2 # Implements SFA Credentials
4 # Credentials are signed XML files that assign a subject gid privileges to an object gid
12 from random import randint
13 from xml.dom.minidom import Document, parseString
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
24 # Two years, in minutes
25 DEFAULT_CREDENTIAL_LIFETIME = 1051200
29 # . make privs match between PG and PL
30 # . Need to add support for other types of credentials, e.g. tickets
34 signature_template = \
36 <Signature xml:id="Sig_%s" xmlns="http://www.w3.org/2000/09/xmldsig#">
38 <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
39 <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
42 <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
44 <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
45 <DigestValue></DigestValue>
61 # Convert a string into a bool
64 if str.lower() in ['yes','true','1']:
71 # Utility function to get the text of an XML element
73 def getTextNode(element, subele):
74 sub = element.getElementsByTagName(subele)[0]
75 if len(sub.childNodes) > 0:
76 return sub.childNodes[0].nodeValue
81 # Utility function to set the text of an XML element
82 # It creates the element, adds the text to it,
83 # and then appends it to the parent.
85 def append_sub(doc, parent, element, text):
86 ele = doc.createElement(element)
87 ele.appendChild(doc.createTextNode(text))
88 parent.appendChild(ele)
91 # Signature contains information about an xmlsec1 signature
92 # for a signed-credential
95 class Signature(object):
98 def __init__(self, string=None):
100 self.issuer_gid = None
118 def set_refid(self, id):
121 def get_issuer_gid(self):
126 def set_issuer_gid(self, gid):
130 doc = parseString(self.xml)
131 sig = doc.getElementsByTagName("Signature")[0]
132 self.set_refid(sig.getAttribute("xml:id").strip("Sig_"))
133 keyinfo = sig.getElementsByTagName("X509Data")[0]
134 szgid = getTextNode(keyinfo, "X509Certificate")
135 szgid = "-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----" % szgid
136 self.set_issuer_gid(GID(string=szgid))
139 self.xml = signature_template % (self.get_refid(), self.get_refid())
143 # A credential provides a caller gid with privileges to an object gid.
144 # A signed credential is signed by the object's authority.
146 # Credentials are encoded in one of two ways. The legacy style places
147 # it in the subjectAltName of an X509 certificate. The new credentials
148 # are placed in signed XML.
151 # In general, a signed credential obtained externally should
152 # not be changed else the signature is no longer valid. So, once
153 # you have loaded an existing signed credential, do not call encode() or sign() on it.
156 class Credential(object):
160 # Create a Credential object
162 # @param create If true, create a blank x509 certificate
163 # @param subject If subject!=None, create an x509 cert with the subject name
164 # @param string If string!=None, load the credential from the string
165 # @param filename If filename!=None, load the credential from the file
167 def __init__(self, create=False, subject=None, string=None, filename=None):
168 self.gidCaller = None
169 self.gidObject = None
170 self.expiration = None
171 self.privileges = None
172 self.issuer_privkey = None
173 self.issuer_gid = None
174 self.issuer_pubkey = None
176 self.signature = None
184 # Check if this is a legacy credential, translate it if so
185 if string or filename:
189 str = file(filename).read()
191 if str.strip().startswith("-----"):
192 self.legacy = CredentialLegacy(False,string=str)
193 self.translate_legacy(str)
198 # Find an xmlsec1 path
199 self.xmlsec_path = ''
200 paths = ['/usr/bin','/usr/local/bin','/bin','/opt/bin','/opt/local/bin']
202 if os.path.isfile(path + '/' + 'xmlsec1'):
203 self.xmlsec_path = path + '/' + 'xmlsec1'
207 def get_signature(self):
208 if not self.signature:
210 return self.signature
212 def set_signature(self, sig):
217 # Translate a legacy credential into a new one
219 # @param String of the legacy credential
221 def translate_legacy(self, str):
222 legacy = CredentialLegacy(False,string=str)
223 self.gidCaller = legacy.get_gid_caller()
224 self.gidObject = legacy.get_gid_object()
225 lifetime = legacy.get_lifetime()
227 # Default to two years
228 self.set_lifetime(DEFAULT_CREDENTIAL_LIFETIME)
230 self.set_lifetime(int(lifetime))
231 self.lifeTime = legacy.get_lifetime()
232 self.set_privileges(legacy.get_privileges())
233 self.get_privileges().delegate_all_privileges(legacy.get_delegate())
236 # Need the issuer's private key and name
237 # @param key Keypair object containing the private key of the issuer
238 # @param gid GID of the issuing authority
240 def set_issuer_keys(self, privkey, gid):
241 self.issuer_privkey = privkey
242 self.issuer_gid = gid
246 # Set this credential's parent
247 def set_parent(self, cred):
252 # set the GID of the caller
254 # @param gid GID object of the caller
256 def set_gid_caller(self, gid):
258 # gid origin caller is the caller's gid by default
259 self.gidOriginCaller = gid
262 # get the GID of the object
264 def get_gid_caller(self):
265 if not self.gidCaller:
267 return self.gidCaller
270 # set the GID of the object
272 # @param gid GID object of the object
274 def set_gid_object(self, gid):
278 # get the GID of the object
280 def get_gid_object(self):
281 if not self.gidObject:
283 return self.gidObject
286 # set the lifetime of this credential
288 # @param lifetime lifetime of credential
289 # . if lifeTime is a datetime object, it is used for the expiration time
290 # . if lifeTime is an integer value, it is considered the number of minutes
291 # remaining before expiration
293 def set_lifetime(self, lifeTime):
294 if isinstance(lifeTime, int):
295 self.expiration = datetime.timedelta(seconds=lifeTime*60) + datetime.datetime.utcnow()
297 self.expiration = lifeTime
300 # get the lifetime of the credential (in minutes)
302 def get_lifetime(self):
303 if not self.expiration:
305 return self.expiration
311 # @param privs either a comma-separated list of privileges of a RightList object
313 def set_privileges(self, privs):
314 if isinstance(privs, str):
315 self.privileges = RightList(string = privs)
317 self.privileges = privs
321 # return the privileges as a RightList object
323 def get_privileges(self):
324 if not self.privileges:
326 return self.privileges
329 # determine whether the credential allows a particular operation to be
332 # @param op_name string specifying name of operation ("lookup", "update", etc)
334 def can_perform(self, op_name):
335 rights = self.get_privileges()
340 return rights.can_perform(op_name)
344 # Encode the attributes of the credential into an XML string
345 # This should be done immediately before signing the credential.
347 # In general, a signed credential obtained externally should
348 # not be changed else the signature is no longer valid. So, once
349 # you have loaded an existing signed credential, do not call encode() or sign() on it.
352 # Create the XML document
354 signed_cred = doc.createElement("signed-credential")
355 doc.appendChild(signed_cred)
357 # Fill in the <credential> bit
358 cred = doc.createElement("credential")
359 cred.setAttribute("xml:id", self.get_refid())
360 signed_cred.appendChild(cred)
361 append_sub(doc, cred, "type", "privilege")
362 append_sub(doc, cred, "serial", "8")
363 append_sub(doc, cred, "owner_gid", self.gidCaller.save_to_string())
364 append_sub(doc, cred, "owner_urn", self.gidCaller.get_urn())
365 append_sub(doc, cred, "target_gid", self.gidObject.save_to_string())
366 append_sub(doc, cred, "target_urn", self.gidObject.get_urn())
367 append_sub(doc, cred, "uuid", "")
368 if not self.expiration:
369 self.set_lifetime(3600)
370 self.expiration = self.expiration.replace(microsecond=0)
371 append_sub(doc, cred, "expires", self.expiration.isoformat())
372 privileges = doc.createElement("privileges")
373 cred.appendChild(privileges)
376 rights = self.get_privileges()
377 for right in rights.rights:
378 priv = doc.createElement("privilege")
379 append_sub(doc, priv, "name", right.kind)
380 append_sub(doc, priv, "can_delegate", str(right.delegate).lower())
381 privileges.appendChild(priv)
383 # Add the parent credential if it exists
385 sdoc = parseString(self.parent.get_xml())
386 p_cred = doc.importNode(sdoc.getElementsByTagName("credential")[0], True)
387 p = doc.createElement("parent")
388 p.appendChild(p_cred)
392 # Create the <signatures> tag
393 signatures = doc.createElement("signatures")
394 signed_cred.appendChild(signatures)
396 # Add any parent signatures
398 cur_cred = self.parent
400 sdoc = parseString(cur_cred.get_signature().get_xml())
401 ele = doc.importNode(sdoc.getElementsByTagName("Signature")[0], True)
402 signatures.appendChild(ele)
405 cur_cred = cur_cred.parent
409 # Get the finished product
410 self.xml = doc.toxml()
413 def save_to_random_tmp_file(self):
415 filename = "/tmp/cred_%d" % randint(0,999999999)
416 if not os.path.isfile(filename):
419 self.save_to_file(filename)
422 def save_to_file(self, filename, save_parents=True):
425 f = open(filename, "w")
429 def save_to_string(self, save_parents=True):
439 def set_refid(self, rid):
443 # Figure out what refids exist, and update this credential's id
444 # so that it doesn't clobber the others. Returns the refids of
447 def updateRefID(self):
449 self.set_refid('ref0')
454 next_cred = self.parent
456 refs.append(next_cred.get_refid())
458 next_cred = next_cred.parent
463 # Find a unique refid for this credential
464 rid = self.get_refid()
467 rid = "ref%d" % (val + 1)
472 # Return the set of parent credential ref ids
481 # Sign the XML file created by encode()
484 # In general, a signed credential obtained externally should
485 # not be changed else the signature is no longer valid. So, once
486 # you have loaded an existing signed credential, do not call encode() or sign() on it.
489 if not self.issuer_privkey or not self.issuer_gid:
491 doc = parseString(self.get_xml())
492 sigs = doc.getElementsByTagName("signatures")[0]
494 # Create the signature template to be signed
495 signature = Signature()
496 signature.set_refid(self.get_refid())
497 sdoc = parseString(signature.get_xml())
498 sig_ele = doc.importNode(sdoc.getElementsByTagName("Signature")[0], True)
499 sigs.appendChild(sig_ele)
501 self.xml = doc.toxml()
504 # Split the issuer GID into multiple certificates if it's a chain
505 chain = GID(filename=self.issuer_gid)
508 gid_files.append(chain.save_to_random_tmp_file(False))
509 if chain.get_parent():
510 chain = chain.get_parent()
515 # Call out to xmlsec1 to sign it
516 ref = 'Sig_%s' % self.get_refid()
517 filename = self.save_to_random_tmp_file()
518 signed = os.popen('%s --sign --node-id "%s" --privkey-pem %s,%s %s' \
519 % (self.xmlsec_path, ref, self.issuer_privkey, ",".join(gid_files), filename)).read()
522 for gid_file in gid_files:
527 # This is no longer a legacy credential
538 # Retrieve the attributes of the credential from the XML.
539 # This is automatically called by the various get_* methods of
540 # this class and should not need to be called explicitly.
545 doc = parseString(self.xml)
547 signed_cred = doc.getElementsByTagName("signed-credential")
549 # Is this a signed-cred or just a cred?
550 if len(signed_cred) > 0:
551 cred = signed_cred[0].getElementsByTagName("credential")[0]
552 signatures = signed_cred[0].getElementsByTagName("signatures")
553 if len(signatures) > 0:
554 sigs = signatures[0].getElementsByTagName("Signature")
556 cred = doc.getElementsByTagName("credential")[0]
560 self.set_refid(cred.getAttribute("xml:id"))
561 sz_expires = getTextNode(cred, "expires")
563 self.expiration = datetime.datetime.strptime(sz_expires, '%Y-%m-%dT%H:%M:%S')
564 self.lifeTime = getTextNode(cred, "expires")
565 self.gidCaller = GID(string=getTextNode(cred, "owner_gid"))
566 self.gidObject = GID(string=getTextNode(cred, "target_gid"))
570 privs = cred.getElementsByTagName("privileges")[0]
572 for priv in privs.getElementsByTagName("privilege"):
573 kind = getTextNode(priv, "name")
574 deleg = str2bool(getTextNode(priv, "can_delegate"))
576 # Convert * into the default privileges for the credential's type
577 _ , type = urn_to_hrn(self.gidObject.get_urn())
578 rl = rlist.determine_rights(type, self.gidObject.get_urn())
582 rlist.add(Right(kind.strip(), deleg))
583 self.set_privileges(rlist)
587 parent = cred.getElementsByTagName("parent")
589 parent_doc = parent[0].getElementsByTagName("credential")[0]
590 parent_xml = parent_doc.toxml()
591 self.parent = Credential(string=parent_xml)
594 # Assign the signatures to the credentials
596 Sig = Signature(string=sig.toxml())
600 if cur_cred.get_refid() == Sig.get_refid():
601 cur_cred.set_signature(Sig)
604 cur_cred = cur_cred.parent
611 # . All of the signatures are valid and that the issuers trace back
612 # to trusted roots (performed by xmlsec1)
613 # . The XML matches the credential schema
614 # . That the issuer of the credential is the authority in the target's urn
615 # . In the case of a delegated credential, this must be true of the root
616 # . That all of the gids presented in the credential are valid
618 # -- For Delegates (credentials with parents)
619 # . The privileges must be a subset of the parent credentials
620 # . The privileges must have "can_delegate" set for each delegated privilege
621 # . The target gid must be the same between child and parents
622 # . The expiry time on the child must be no later than the parent
623 # . The signer of the child must be the owner of the parent
625 # -- Verify does *NOT*
626 # . ensure that an xmlrpc client's gid matches a credential gid, that
627 # must be done elsewhere
629 # @param trusted_certs: The certificates of trusted CA certificates
631 def verify(self, trusted_certs):
635 trusted_cert_objects = [GID(filename=f) for f in trusted_certs]
637 # Use legacy verification if this is a legacy credential
639 self.legacy.verify_chain(trusted_cert_objects)
640 if self.legacy.client_gid:
641 self.legacy.client_gid.verify_chain(trusted_cert_objects)
642 if self.legacy.object_gid:
643 self.legacy.object_gid.verify_chain(trusted_cert_objects)
646 # Verify the signatures
647 filename = self.save_to_random_tmp_file()
648 cert_args = " ".join(['--trusted-pem %s' % x for x in trusted_certs])
650 # Verify the gids of this cred and of its parents
654 cur_cred.get_gid_object().verify_chain(trusted_cert_objects)
655 cur_cred.get_gid_caller().verify_chain(trusted_cert_objects)
657 cur_cred = cur_cred.parent
662 refs.append("Sig_%s" % self.get_refid())
664 parentRefs = self.updateRefID()
665 for ref in parentRefs:
666 refs.append("Sig_%s" % ref)
669 verified = os.popen('%s --verify --node-id "%s" %s %s 2>&1' \
670 % (self.xmlsec_path, ref, cert_args, filename)).read()
671 if not verified.strip().startswith("OK"):
672 raise CredentialNotVerifiable("xmlsec1 error: " + verified)
675 # Verify the parents (delegation)
677 self.verify_parent(self.parent)
678 # Make sure the issuer is the target's authority
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())
689 # Find the root credential's signature
693 cur_cred = cur_cred.parent
695 root_issuer = cur_cred.get_signature().get_issuer_gid().get_urn()
698 # Ensure that the signer of the root credential is the target_authority
699 target_authority = hrn_to_urn(target_authority, 'authority')
701 if root_issuer != target_authority:
702 raise CredentialNotVerifiable("issuer (%s) != authority of target (%s)" \
703 % (root_issuer, target_authority))
706 # -- For Delegates (credentials with parents) verify that:
707 # . The privileges must be a subset of the parent credentials
708 # . The privileges must have "can_delegate" set for each delegated privilege
709 # . The target gid must be the same between child and parents
710 # . The expiry time on the child must be no later than the parent
711 # . The signer of the child must be the owner of the parent
713 def verify_parent(self, parent_cred):
714 # make sure the rights given to the child are a subset of the
715 # parents rights (and check delegate bits)
716 if not parent_cred.get_privileges().is_superset(self.get_privileges()):
717 raise ChildRightsNotSubsetOfParent(
718 self.parent.get_privileges().save_to_string() + " " +
719 self.get_privileges().save_to_string())
721 # make sure my target gid is the same as the parent's
722 if not parent_cred.get_gid_object().save_to_string() == \
723 self.get_gid_object().save_to_string():
724 raise CredentialNotVerifiable("target gid not equal between parent and child")
726 # make sure my expiry time is <= my parent's
727 if not parent_cred.get_lifetime() >= self.get_lifetime():
728 raise CredentialNotVerifiable("delegated credential expires after parent")
730 # make sure my signer is the parent's caller
731 if not parent_cred.get_gid_caller().save_to_string(False) == \
732 self.get_signature().get_issuer_gid().save_to_string(False):
733 raise CredentialNotVerifiable("delegated credential not signed by parent caller")
735 if parent_cred.parent:
736 parent_cred.verify_parent(parent_cred.parent)
739 # Dump the contents of a credential to stdout in human-readable format
741 # @param dump_parents If true, also dump the parent certificates
743 def dump(self, dump_parents=False):
744 print "CREDENTIAL", self.get_subject()
746 print " privs:", self.get_privileges().save_to_string()
749 gidCaller = self.get_gid_caller()
751 gidCaller.dump(8, dump_parents)
754 gidObject = self.get_gid_object()
756 gidObject.dump(8, dump_parents)
759 if self.parent and dump_parents:
761 self.parent.dump_parents()