2 # Implements SFA Credentials
4 # Credentials are signed XML files that assign a subject gid privileges to an object gid
12 from xml.dom.minidom import Document, parseString
13 from tempfile import mkstemp
15 from sfa.trust.credential_legacy import CredentialLegacy
16 from sfa.trust.rights import *
17 from sfa.trust.gid import *
18 from sfa.util.faults import *
20 from sfa.util.sfalogging import logger
21 from dateutil.parser import parse
25 # Two years, in seconds
26 DEFAULT_CREDENTIAL_LIFETIME = 60 * 60 * 24 * 365 * 2
30 # . fix verify_issuer() and call it at the end of verify()
31 # . make privs match between PG and PL
32 # . Need to add support for other types of credentials, e.g. tickets
36 signature_template = \
38 <Signature xml:id="Sig_%s" xmlns="http://www.w3.org/2000/09/xmldsig#">
40 <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
41 <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
44 <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
46 <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
47 <DigestValue></DigestValue>
63 # Convert a string into a bool
66 if str.lower() in ['yes','true','1']:
73 # Utility function to get the text of an XML element
75 def getTextNode(element, subele):
76 sub = element.getElementsByTagName(subele)[0]
77 if len(sub.childNodes) > 0:
78 return sub.childNodes[0].nodeValue
83 # Utility function to set the text of an XML element
84 # It creates the element, adds the text to it,
85 # and then appends it to the parent.
87 def append_sub(doc, parent, element, text):
88 ele = doc.createElement(element)
89 ele.appendChild(doc.createTextNode(text))
90 parent.appendChild(ele)
93 # Signature contains information about an xmlsec1 signature
94 # for a signed-credential
97 class Signature(object):
100 def __init__(self, string=None):
102 self.issuer_gid = None
120 def set_refid(self, id):
123 def get_issuer_gid(self):
128 def set_issuer_gid(self, gid):
132 doc = parseString(self.xml)
133 sig = doc.getElementsByTagName("Signature")[0]
134 self.set_refid(sig.getAttribute("xml:id").strip("Sig_"))
135 keyinfo = sig.getElementsByTagName("X509Data")[0]
136 szgid = getTextNode(keyinfo, "X509Certificate")
137 szgid = "-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----" % szgid
138 self.set_issuer_gid(GID(string=szgid))
141 self.xml = signature_template % (self.get_refid(), self.get_refid())
145 # A credential provides a caller gid with privileges to an object gid.
146 # A signed credential is signed by the object's authority.
148 # Credentials are encoded in one of two ways. The legacy style places
149 # it in the subjectAltName of an X509 certificate. The new credentials
150 # are placed in signed XML.
153 # In general, a signed credential obtained externally should
154 # not be changed else the signature is no longer valid. So, once
155 # you have loaded an existing signed credential, do not call encode() or sign() on it.
158 class Credential(object):
162 # Create a Credential object
164 # @param create If true, create a blank x509 certificate
165 # @param subject If subject!=None, create an x509 cert with the subject name
166 # @param string If string!=None, load the credential from the string
167 # @param filename If filename!=None, load the credential from the file
169 def __init__(self, create=False, subject=None, string=None, filename=None):
170 self.gidCaller = None
171 self.gidObject = None
172 self.expiration = None
173 self.privileges = None
174 self.issuer_privkey = None
175 self.issuer_gid = None
176 self.issuer_pubkey = None
178 self.signature = None
186 # Check if this is a legacy credential, translate it if so
187 if string or filename:
191 str = file(filename).read()
193 if str.strip().startswith("-----"):
194 self.legacy = CredentialLegacy(False,string=str)
195 self.translate_legacy(str)
200 # Find an xmlsec1 path
201 self.xmlsec_path = ''
202 paths = ['/usr/bin','/usr/local/bin','/bin','/opt/bin','/opt/local/bin']
204 if os.path.isfile(path + '/' + 'xmlsec1'):
205 self.xmlsec_path = path + '/' + 'xmlsec1'
209 def get_signature(self):
210 if not self.signature:
212 return self.signature
214 def set_signature(self, sig):
219 # Translate a legacy credential into a new one
221 # @param String of the legacy credential
223 def translate_legacy(self, str):
224 legacy = CredentialLegacy(False,string=str)
225 self.gidCaller = legacy.get_gid_caller()
226 self.gidObject = legacy.get_gid_object()
227 lifetime = legacy.get_lifetime()
229 # Default to two years
230 self.set_lifetime(DEFAULT_CREDENTIAL_LIFETIME)
232 self.set_lifetime(int(lifetime))
233 self.lifeTime = legacy.get_lifetime()
234 self.set_privileges(legacy.get_privileges())
235 self.get_privileges().delegate_all_privileges(legacy.get_delegate())
238 # Need the issuer's private key and name
239 # @param key Keypair object containing the private key of the issuer
240 # @param gid GID of the issuing authority
242 def set_issuer_keys(self, privkey, gid):
243 self.issuer_privkey = privkey
244 self.issuer_gid = gid
248 # Set this credential's parent
249 def set_parent(self, cred):
254 # set the GID of the caller
256 # @param gid GID object of the caller
258 def set_gid_caller(self, gid):
260 # gid origin caller is the caller's gid by default
261 self.gidOriginCaller = gid
264 # get the GID of the object
266 def get_gid_caller(self):
267 if not self.gidCaller:
269 return self.gidCaller
272 # set the GID of the object
274 # @param gid GID object of the object
276 def set_gid_object(self, gid):
280 # get the GID of the object
282 def get_gid_object(self):
283 if not self.gidObject:
285 return self.gidObject
288 # set the lifetime of this credential
290 # @param lifetime lifetime of credential
291 # . if lifeTime is a datetime object, it is used for the expiration time
292 # . if lifeTime is an integer value, it is considered the number of seconds
293 # remaining before expiration
295 def set_lifetime(self, lifeTime):
296 if isinstance(lifeTime, int):
297 self.expiration = datetime.timedelta(seconds=lifeTime) + datetime.datetime.utcnow()
299 self.expiration = lifeTime
302 # get the lifetime of the credential (in datetime format)
304 def get_lifetime(self):
305 if not self.expiration:
307 return self.expiration
313 # @param privs either a comma-separated list of privileges of a RightList object
315 def set_privileges(self, privs):
316 if isinstance(privs, str):
317 self.privileges = RightList(string = privs)
319 self.privileges = privs
323 # return the privileges as a RightList object
325 def get_privileges(self):
326 if not self.privileges:
328 return self.privileges
331 # determine whether the credential allows a particular operation to be
334 # @param op_name string specifying name of operation ("lookup", "update", etc)
336 def can_perform(self, op_name):
337 rights = self.get_privileges()
342 return rights.can_perform(op_name)
346 # Encode the attributes of the credential into an XML string
347 # This should be done immediately before signing the credential.
349 # In general, a signed credential obtained externally should
350 # not be changed else the signature is no longer valid. So, once
351 # you have loaded an existing signed credential, do not call encode() or sign() on it.
354 # Create the XML document
356 signed_cred = doc.createElement("signed-credential")
357 doc.appendChild(signed_cred)
359 # Fill in the <credential> bit
360 cred = doc.createElement("credential")
361 cred.setAttribute("xml:id", self.get_refid())
362 signed_cred.appendChild(cred)
363 append_sub(doc, cred, "type", "privilege")
364 append_sub(doc, cred, "serial", "8")
365 append_sub(doc, cred, "owner_gid", self.gidCaller.save_to_string())
366 append_sub(doc, cred, "owner_urn", self.gidCaller.get_urn())
367 append_sub(doc, cred, "target_gid", self.gidObject.save_to_string())
368 append_sub(doc, cred, "target_urn", self.gidObject.get_urn())
369 append_sub(doc, cred, "uuid", "")
370 if not self.expiration:
371 self.set_lifetime(DEFAULT_CREDENTIAL_LIFETIME)
372 self.expiration = self.expiration.replace(microsecond=0)
373 append_sub(doc, cred, "expires", self.expiration.isoformat())
374 privileges = doc.createElement("privileges")
375 cred.appendChild(privileges)
378 rights = self.get_privileges()
379 for right in rights.rights:
380 priv = doc.createElement("privilege")
381 append_sub(doc, priv, "name", right.kind)
382 append_sub(doc, priv, "can_delegate", str(right.delegate).lower())
383 privileges.appendChild(priv)
385 # Add the parent credential if it exists
387 sdoc = parseString(self.parent.get_xml())
388 p_cred = doc.importNode(sdoc.getElementsByTagName("credential")[0], True)
389 p = doc.createElement("parent")
390 p.appendChild(p_cred)
394 # Create the <signatures> tag
395 signatures = doc.createElement("signatures")
396 signed_cred.appendChild(signatures)
398 # Add any parent signatures
400 cur_cred = self.parent
402 sdoc = parseString(cur_cred.get_signature().get_xml())
403 ele = doc.importNode(sdoc.getElementsByTagName("Signature")[0], True)
404 signatures.appendChild(ele)
407 cur_cred = cur_cred.parent
411 # Get the finished product
412 self.xml = doc.toxml()
415 def save_to_random_tmp_file(self):
416 fp, filename = mkstemp(suffix='cred', text=True)
417 fp = os.fdopen(fp, "w")
418 self.save_to_file(filename, save_parents=True, filep=fp)
421 def save_to_file(self, filename, save_parents=True, filep=None):
427 f = open(filename, "w")
431 def save_to_string(self, save_parents=True):
441 def set_refid(self, rid):
445 # Figure out what refids exist, and update this credential's id
446 # so that it doesn't clobber the others. Returns the refids of
449 def updateRefID(self):
451 self.set_refid('ref0')
456 next_cred = self.parent
458 refs.append(next_cred.get_refid())
460 next_cred = next_cred.parent
465 # Find a unique refid for this credential
466 rid = self.get_refid()
469 rid = "ref%d" % (val + 1)
474 # Return the set of parent credential ref ids
483 # Sign the XML file created by encode()
486 # In general, a signed credential obtained externally should
487 # not be changed else the signature is no longer valid. So, once
488 # you have loaded an existing signed credential, do not call encode() or sign() on it.
491 if not self.issuer_privkey or not self.issuer_gid:
493 doc = parseString(self.get_xml())
494 sigs = doc.getElementsByTagName("signatures")[0]
496 # Create the signature template to be signed
497 signature = Signature()
498 signature.set_refid(self.get_refid())
499 sdoc = parseString(signature.get_xml())
500 sig_ele = doc.importNode(sdoc.getElementsByTagName("Signature")[0], True)
501 sigs.appendChild(sig_ele)
503 self.xml = doc.toxml()
506 # Split the issuer GID into multiple certificates if it's a chain
507 chain = GID(filename=self.issuer_gid)
510 gid_files.append(chain.save_to_random_tmp_file(False))
511 if chain.get_parent():
512 chain = chain.get_parent()
517 # Call out to xmlsec1 to sign it
518 ref = 'Sig_%s' % self.get_refid()
519 filename = self.save_to_random_tmp_file()
520 signed = os.popen('%s --sign --node-id "%s" --privkey-pem %s,%s %s' \
521 % (self.xmlsec_path, ref, self.issuer_privkey, ",".join(gid_files), filename)).read()
524 for gid_file in gid_files:
529 # This is no longer a legacy credential
540 # Retrieve the attributes of the credential from the XML.
541 # This is automatically called by the various get_* methods of
542 # this class and should not need to be called explicitly.
547 doc = parseString(self.xml)
549 signed_cred = doc.getElementsByTagName("signed-credential")
551 # Is this a signed-cred or just a cred?
552 if len(signed_cred) > 0:
553 cred = signed_cred[0].getElementsByTagName("credential")[0]
554 signatures = signed_cred[0].getElementsByTagName("signatures")
555 if len(signatures) > 0:
556 sigs = signatures[0].getElementsByTagName("Signature")
558 cred = doc.getElementsByTagName("credential")[0]
562 self.set_refid(cred.getAttribute("xml:id"))
563 self.set_lifetime(parse(getTextNode(cred, "expires")))
564 self.gidCaller = GID(string=getTextNode(cred, "owner_gid"))
565 self.gidObject = GID(string=getTextNode(cred, "target_gid"))
569 privs = cred.getElementsByTagName("privileges")[0]
571 for priv in privs.getElementsByTagName("privilege"):
572 kind = getTextNode(priv, "name")
573 deleg = str2bool(getTextNode(priv, "can_delegate"))
575 # Convert * into the default privileges for the credential's type
576 _ , type = urn_to_hrn(self.gidObject.get_urn())
577 rl = rlist.determine_rights(type, self.gidObject.get_urn())
581 rlist.add(Right(kind.strip(), deleg))
582 self.set_privileges(rlist)
586 parent = cred.getElementsByTagName("parent")
588 parent_doc = parent[0].getElementsByTagName("credential")[0]
589 parent_xml = parent_doc.toxml()
590 self.parent = Credential(string=parent_xml)
593 # Assign the signatures to the credentials
595 Sig = Signature(string=sig.toxml())
599 if cur_cred.get_refid() == Sig.get_refid():
600 cur_cred.set_signature(Sig)
603 cur_cred = cur_cred.parent
610 # . All of the signatures are valid and that the issuers trace back
611 # to trusted roots (performed by xmlsec1)
612 # . The XML matches the credential schema
613 # . That the issuer of the credential is the authority in the target's urn
614 # . In the case of a delegated credential, this must be true of the root
615 # . That all of the gids presented in the credential are valid
617 # -- For Delegates (credentials with parents)
618 # . The privileges must be a subset of the parent credentials
619 # . The privileges must have "can_delegate" set for each delegated privilege
620 # . The target gid must be the same between child and parents
621 # . The expiry time on the child must be no later than the parent
622 # . The signer of the child must be the owner of the parent
624 # -- Verify does *NOT*
625 # . ensure that an xmlrpc client's gid matches a credential gid, that
626 # must be done elsewhere
628 # @param trusted_certs: The certificates of trusted CA certificates
630 def verify(self, trusted_certs):
634 trusted_cert_objects = [GID(filename=f) for f in trusted_certs]
636 # Use legacy verification if this is a legacy credential
638 self.legacy.verify_chain(trusted_cert_objects)
639 if self.legacy.client_gid:
640 self.legacy.client_gid.verify_chain(trusted_cert_objects)
641 if self.legacy.object_gid:
642 self.legacy.object_gid.verify_chain(trusted_cert_objects)
645 # Verify the signatures
646 filename = self.save_to_random_tmp_file()
647 cert_args = " ".join(['--trusted-pem %s' % x for x in trusted_certs])
649 # Verify the gids of this cred and of its parents
653 cur_cred.get_gid_object().verify_chain(trusted_cert_objects)
654 cur_cred.get_gid_caller().verify_chain(trusted_cert_objects)
656 cur_cred = cur_cred.parent
661 refs.append("Sig_%s" % self.get_refid())
663 parentRefs = self.updateRefID()
664 for ref in parentRefs:
665 refs.append("Sig_%s" % ref)
668 verified = os.popen('%s --verify --node-id "%s" %s %s 2>&1' \
669 % (self.xmlsec_path, ref, cert_args, filename)).read()
670 if not verified.strip().startswith("OK"):
671 raise CredentialNotVerifiable("xmlsec1 error: " + verified)
674 # Verify the parents (delegation)
676 self.verify_parent(self.parent)
678 # Make sure the issuer is the target's authority
679 #self.verify_issuer()
684 # Make sure the issuer of this credential is the target's authority
685 def verify_issuer(self):
686 target_authority = get_authority(self.get_gid_object().get_urn())
688 # Find the root credential's signature
692 cur_cred = cur_cred.parent
694 root_issuer = cur_cred.get_signature().get_issuer_gid().get_urn()
697 # Ensure that the signer of the root credential is the target_authority
698 target_authority = hrn_to_urn(target_authority, 'authority')
700 if root_issuer != target_authority:
701 raise CredentialNotVerifiable("issuer (%s) != authority of target (%s) for target (%s)" \
702 % (root_issuer, target_authority, self.get_gid_object().get_urn()))
705 # -- For Delegates (credentials with parents) verify that:
706 # . The privileges must be a subset of the parent credentials
707 # . The privileges must have "can_delegate" set for each delegated privilege
708 # . The target gid must be the same between child and parents
709 # . The expiry time on the child must be no later than the parent
710 # . The signer of the child must be the owner of the parent
712 def verify_parent(self, parent_cred):
713 # make sure the rights given to the child are a subset of the
714 # parents rights (and check delegate bits)
715 if not parent_cred.get_privileges().is_superset(self.get_privileges()):
716 raise ChildRightsNotSubsetOfParent(
717 self.parent.get_privileges().save_to_string() + " " +
718 self.get_privileges().save_to_string())
720 # make sure my target gid is the same as the parent's
721 if not parent_cred.get_gid_object().save_to_string() == \
722 self.get_gid_object().save_to_string():
723 raise CredentialNotVerifiable("target gid not equal between parent and child")
725 # make sure my expiry time is <= my parent's
726 if not parent_cred.get_lifetime() >= self.get_lifetime():
727 raise CredentialNotVerifiable("delegated credential expires after parent")
729 # make sure my signer is the parent's caller
730 if not parent_cred.get_gid_caller().save_to_string(False) == \
731 self.get_signature().get_issuer_gid().save_to_string(False):
732 raise CredentialNotVerifiable("delegated credential not signed by parent caller")
734 if parent_cred.parent:
735 parent_cred.verify_parent(parent_cred.parent)
738 # Dump the contents of a credential to stdout in human-readable format
740 # @param dump_parents If true, also dump the parent certificates
742 def dump(self, dump_parents=False):
743 print "CREDENTIAL", self.get_subject()
745 print " privs:", self.get_privileges().save_to_string()
748 gidCaller = self.get_gid_caller()
750 gidCaller.dump(8, dump_parents)
753 gidObject = self.get_gid_object()
755 gidObject.dump(8, dump_parents)
758 if self.parent and dump_parents:
760 self.parent.dump_parents()