1 #----------------------------------------------------------------------
2 # Copyright (c) 2008 Board of Trustees, Princeton University
4 # Permission is hereby granted, free of charge, to any person obtaining
5 # a copy of this software and/or hardware specification (the "Work") to
6 # deal in the Work without restriction, including without limitation the
7 # rights to use, copy, modify, merge, publish, distribute, sublicense,
8 # and/or sell copies of the Work, and to permit persons to whom the Work
9 # is furnished to do so, subject to the following conditions:
11 # The above copyright notice and this permission notice shall be
12 # included in all copies or substantial portions of the Work.
14 # THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
18 # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
19 # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 # OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
22 #----------------------------------------------------------------------
24 # Implements SFA Credentials
26 # Credentials are signed XML files that assign a subject gid privileges to an object gid
34 from xml.dom.minidom import Document, parseString
35 from tempfile import mkstemp
37 from sfa.trust.credential_legacy import CredentialLegacy
38 from sfa.trust.rights import *
39 from sfa.trust.gid import *
40 from sfa.util.faults import *
42 from sfa.util.sfalogging import logger
43 from dateutil.parser import parse
47 # Two years, in seconds
48 DEFAULT_CREDENTIAL_LIFETIME = 60 * 60 * 24 * 365 * 2
52 # . make privs match between PG and PL
53 # . Need to add support for other types of credentials, e.g. tickets
56 signature_template = \
58 <Signature xml:id="Sig_%s" xmlns="http://www.w3.org/2000/09/xmldsig#">
60 <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
61 <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
64 <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
66 <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
67 <DigestValue></DigestValue>
83 # Convert a string into a bool
86 if str.lower() in ['yes','true','1']:
92 # Utility function to get the text of an XML element
94 def getTextNode(element, subele):
95 sub = element.getElementsByTagName(subele)[0]
96 if len(sub.childNodes) > 0:
97 return sub.childNodes[0].nodeValue
102 # Utility function to set the text of an XML element
103 # It creates the element, adds the text to it,
104 # and then appends it to the parent.
106 def append_sub(doc, parent, element, text):
107 ele = doc.createElement(element)
108 ele.appendChild(doc.createTextNode(text))
109 parent.appendChild(ele)
112 # Signature contains information about an xmlsec1 signature
113 # for a signed-credential
116 class Signature(object):
118 def __init__(self, string=None):
120 self.issuer_gid = None
137 def set_refid(self, id):
140 def get_issuer_gid(self):
145 def set_issuer_gid(self, gid):
149 doc = parseString(self.xml)
150 sig = doc.getElementsByTagName("Signature")[0]
151 self.set_refid(sig.getAttribute("xml:id").strip("Sig_"))
152 keyinfo = sig.getElementsByTagName("X509Data")[0]
153 szgid = getTextNode(keyinfo, "X509Certificate")
154 szgid = "-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----" % szgid
155 self.set_issuer_gid(GID(string=szgid))
158 self.xml = signature_template % (self.get_refid(), self.get_refid())
162 # A credential provides a caller gid with privileges to an object gid.
163 # A signed credential is signed by the object's authority.
165 # Credentials are encoded in one of two ways. The legacy style places
166 # it in the subjectAltName of an X509 certificate. The new credentials
167 # are placed in signed XML.
170 # In general, a signed credential obtained externally should
171 # not be changed else the signature is no longer valid. So, once
172 # you have loaded an existing signed credential, do not call encode() or sign() on it.
174 class Credential(object):
177 # Create a Credential object
179 # @param create If true, create a blank x509 certificate
180 # @param subject If subject!=None, create an x509 cert with the subject name
181 # @param string If string!=None, load the credential from the string
182 # @param filename If filename!=None, load the credential from the file
183 # FIXME: create and subject are ignored!
184 def __init__(self, create=False, subject=None, string=None, filename=None):
185 self.gidCaller = None
186 self.gidObject = None
187 self.expiration = None
188 self.privileges = None
189 self.issuer_privkey = None
190 self.issuer_gid = None
191 self.issuer_pubkey = None
193 self.signature = None
198 # Check if this is a legacy credential, translate it if so
199 if string or filename:
203 str = file(filename).read()
205 if str.strip().startswith("-----"):
206 self.legacy = CredentialLegacy(False,string=str)
207 self.translate_legacy(str)
212 # Find an xmlsec1 path
213 self.xmlsec_path = ''
214 paths = ['/usr/bin','/usr/local/bin','/bin','/opt/bin','/opt/local/bin']
216 if os.path.isfile(path + '/' + 'xmlsec1'):
217 self.xmlsec_path = path + '/' + 'xmlsec1'
221 def get_signature(self):
222 if not self.signature:
224 return self.signature
226 def set_signature(self, sig):
231 # Translate a legacy credential into a new one
233 # @param String of the legacy credential
235 def translate_legacy(self, str):
236 legacy = CredentialLegacy(False,string=str)
237 self.gidCaller = legacy.get_gid_caller()
238 self.gidObject = legacy.get_gid_object()
239 lifetime = legacy.get_lifetime()
241 # Default to two years
242 self.set_lifetime(DEFAULT_CREDENTIAL_LIFETIME)
244 self.set_lifetime(int(lifetime))
245 self.lifeTime = legacy.get_lifetime()
246 self.set_privileges(legacy.get_privileges())
247 self.get_privileges().delegate_all_privileges(legacy.get_delegate())
250 # Need the issuer's private key and name
251 # @param key Keypair object containing the private key of the issuer
252 # @param gid GID of the issuing authority
254 def set_issuer_keys(self, privkey, gid):
255 self.issuer_privkey = privkey
256 self.issuer_gid = gid
260 # Set this credential's parent
261 def set_parent(self, cred):
266 # set the GID of the caller
268 # @param gid GID object of the caller
270 def set_gid_caller(self, gid):
272 # gid origin caller is the caller's gid by default
273 self.gidOriginCaller = gid
276 # get the GID of the object
278 def get_gid_caller(self):
279 if not self.gidCaller:
281 return self.gidCaller
284 # set the GID of the object
286 # @param gid GID object of the object
288 def set_gid_object(self, gid):
292 # get the GID of the object
294 def get_gid_object(self):
295 if not self.gidObject:
297 return self.gidObject
300 # set the lifetime of this credential
302 # @param lifetime lifetime of credential
303 # . if lifeTime is a datetime object, it is used for the expiration time
304 # . if lifeTime is an integer value, it is considered the number of seconds
305 # remaining before expiration
307 def set_lifetime(self, lifeTime):
308 if isinstance(lifeTime, int):
309 self.expiration = datetime.timedelta(seconds=lifeTime) + datetime.datetime.utcnow()
311 self.expiration = lifeTime
314 # get the lifetime of the credential (in datetime format)
316 def get_lifetime(self):
317 if not self.expiration:
319 return self.expiration
325 # @param privs either a comma-separated list of privileges of a RightList object
327 def set_privileges(self, privs):
328 if isinstance(privs, str):
329 self.privileges = RightList(string = privs)
331 self.privileges = privs
335 # return the privileges as a RightList object
337 def get_privileges(self):
338 if not self.privileges:
340 return self.privileges
343 # determine whether the credential allows a particular operation to be
346 # @param op_name string specifying name of operation ("lookup", "update", etc)
348 def can_perform(self, op_name):
349 rights = self.get_privileges()
354 return rights.can_perform(op_name)
358 # Encode the attributes of the credential into an XML string
359 # This should be done immediately before signing the credential.
361 # In general, a signed credential obtained externally should
362 # not be changed else the signature is no longer valid. So, once
363 # you have loaded an existing signed credential, do not call encode() or sign() on it.
366 # Create the XML document
368 signed_cred = doc.createElement("signed-credential")
369 doc.appendChild(signed_cred)
371 # Fill in the <credential> bit
372 cred = doc.createElement("credential")
373 cred.setAttribute("xml:id", self.get_refid())
374 signed_cred.appendChild(cred)
375 append_sub(doc, cred, "type", "privilege")
376 append_sub(doc, cred, "serial", "8")
377 append_sub(doc, cred, "owner_gid", self.gidCaller.save_to_string())
378 append_sub(doc, cred, "owner_urn", self.gidCaller.get_urn())
379 append_sub(doc, cred, "target_gid", self.gidObject.save_to_string())
380 append_sub(doc, cred, "target_urn", self.gidObject.get_urn())
381 append_sub(doc, cred, "uuid", "")
382 if not self.expiration:
383 self.set_lifetime(DEFAULT_CREDENTIAL_LIFETIME)
384 self.expiration = self.expiration.replace(microsecond=0)
385 append_sub(doc, cred, "expires", self.expiration.isoformat())
386 privileges = doc.createElement("privileges")
387 cred.appendChild(privileges)
390 rights = self.get_privileges()
391 for right in rights.rights:
392 priv = doc.createElement("privilege")
393 append_sub(doc, priv, "name", right.kind)
394 append_sub(doc, priv, "can_delegate", str(right.delegate).lower())
395 privileges.appendChild(priv)
397 # Add the parent credential if it exists
399 sdoc = parseString(self.parent.get_xml())
400 p_cred = doc.importNode(sdoc.getElementsByTagName("credential")[0], True)
401 p = doc.createElement("parent")
402 p.appendChild(p_cred)
406 # Create the <signatures> tag
407 signatures = doc.createElement("signatures")
408 signed_cred.appendChild(signatures)
410 # Add any parent signatures
412 for cur_cred in self.get_credential_list()[1:]:
413 sdoc = parseString(cur_cred.get_signature().get_xml())
414 ele = doc.importNode(sdoc.getElementsByTagName("Signature")[0], True)
415 signatures.appendChild(ele)
417 # Get the finished product
418 self.xml = doc.toxml()
421 def save_to_random_tmp_file(self):
422 fp, filename = mkstemp(suffix='cred', text=True)
423 fp = os.fdopen(fp, "w")
424 self.save_to_file(filename, save_parents=True, filep=fp)
427 def save_to_file(self, filename, save_parents=True, filep=None):
433 f = open(filename, "w")
437 def save_to_string(self, save_parents=True):
447 def set_refid(self, rid):
451 # Figure out what refids exist, and update this credential's id
452 # so that it doesn't clobber the others. Returns the refids of
455 def updateRefID(self):
457 self.set_refid('ref0')
462 next_cred = self.parent
464 refs.append(next_cred.get_refid())
466 next_cred = next_cred.parent
471 # Find a unique refid for this credential
472 rid = self.get_refid()
475 rid = "ref%d" % (val + 1)
480 # Return the set of parent credential ref ids
489 # Sign the XML file created by encode()
492 # In general, a signed credential obtained externally should
493 # not be changed else the signature is no longer valid. So, once
494 # you have loaded an existing signed credential, do not call encode() or sign() on it.
497 if not self.issuer_privkey or not self.issuer_gid:
499 doc = parseString(self.get_xml())
500 sigs = doc.getElementsByTagName("signatures")[0]
502 # Create the signature template to be signed
503 signature = Signature()
504 signature.set_refid(self.get_refid())
505 sdoc = parseString(signature.get_xml())
506 sig_ele = doc.importNode(sdoc.getElementsByTagName("Signature")[0], True)
507 sigs.appendChild(sig_ele)
509 self.xml = doc.toxml()
512 # Split the issuer GID into multiple certificates if it's a chain
513 chain = GID(filename=self.issuer_gid)
516 gid_files.append(chain.save_to_random_tmp_file(False))
517 if chain.get_parent():
518 chain = chain.get_parent()
523 # Call out to xmlsec1 to sign it
524 ref = 'Sig_%s' % self.get_refid()
525 filename = self.save_to_random_tmp_file()
526 signed = os.popen('%s --sign --node-id "%s" --privkey-pem %s,%s %s' \
527 % (self.xmlsec_path, ref, self.issuer_privkey, ",".join(gid_files), filename)).read()
530 for gid_file in gid_files:
535 # This is no longer a legacy credential
544 # Retrieve the attributes of the credential from the XML.
545 # This is automatically called by the various get_* methods of
546 # this class and should not need to be called explicitly.
551 doc = parseString(self.xml)
553 signed_cred = doc.getElementsByTagName("signed-credential")
555 # Is this a signed-cred or just a cred?
556 if len(signed_cred) > 0:
557 cred = signed_cred[0].getElementsByTagName("credential")[0]
558 signatures = signed_cred[0].getElementsByTagName("signatures")
559 if len(signatures) > 0:
560 sigs = signatures[0].getElementsByTagName("Signature")
562 cred = doc.getElementsByTagName("credential")[0]
565 self.set_refid(cred.getAttribute("xml:id"))
566 self.set_lifetime(parse(getTextNode(cred, "expires")))
567 self.gidCaller = GID(string=getTextNode(cred, "owner_gid"))
568 self.gidObject = GID(string=getTextNode(cred, "target_gid"))
572 privs = cred.getElementsByTagName("privileges")[0]
574 for priv in privs.getElementsByTagName("privilege"):
575 kind = getTextNode(priv, "name")
576 deleg = str2bool(getTextNode(priv, "can_delegate"))
578 # Convert * into the default privileges for the credential's type
579 _ , type = urn_to_hrn(self.gidObject.get_urn())
580 rl = rlist.determine_rights(type, self.gidObject.get_urn())
584 rlist.add(Right(kind.strip(), deleg))
585 self.set_privileges(rlist)
589 parent = cred.getElementsByTagName("parent")
591 parent_doc = parent[0].getElementsByTagName("credential")[0]
592 parent_xml = parent_doc.toxml()
593 self.parent = Credential(string=parent_xml)
596 # Assign the signatures to the credentials
598 Sig = Signature(string=sig.toxml())
600 for cur_cred in self.get_credential_list():
601 if cur_cred.get_refid() == Sig.get_refid():
602 cur_cred.set_signature(Sig)
607 # trusted_certs: A list of trusted GID filenames (not GID objects!)
608 # Chaining is not supported within the GIDs by xmlsec1.
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
617 # . The credential is not expired
619 # -- For Delegates (credentials with parents)
620 # . The privileges must be a subset of the parent credentials
621 # . The privileges must have "can_delegate" set for each delegated privilege
622 # . The target gid must be the same between child and parents
623 # . The expiry time on the child must be no later than the parent
624 # . The signer of the child must be the owner of the parent
626 # -- Verify does *NOT*
627 # . ensure that an xmlrpc client's gid matches a credential gid, that
628 # must be done elsewhere
630 # @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]
636 trusted_cert_objects = []
637 ok_trusted_certs = []
638 for f in trusted_certs:
640 # Failures here include unreadable files
642 trusted_cert_objects.append(GID(filename=f))
643 ok_trusted_certs.append(f)
644 except Exception, exc:
645 logger.error("Failed to load trusted cert from %s: %r", f, exc)
646 trusted_certs = ok_trusted_certs
648 # Use legacy verification if this is a legacy credential
650 self.legacy.verify_chain(trusted_cert_objects)
651 if self.legacy.client_gid:
652 self.legacy.client_gid.verify_chain(trusted_cert_objects)
653 if self.legacy.object_gid:
654 self.legacy.object_gid.verify_chain(trusted_cert_objects)
657 # make sure it is not expired
658 if self.get_lifetime() < datetime.datetime.utcnow():
659 raise CredentialNotVerifiable("Credential expired at %s" % self.expiration.isoformat())
661 # Verify the signatures
662 filename = self.save_to_random_tmp_file()
663 cert_args = " ".join(['--trusted-pem %s' % x for x in trusted_certs])
665 # Verify the gids of this cred and of its parents
666 for cur_cred in self.get_credential_list():
667 cur_cred.get_gid_object().verify_chain(trusted_cert_objects)
668 cur_cred.get_gid_caller().verify_chain(trusted_cert_objects)
671 refs.append("Sig_%s" % self.get_refid())
673 parentRefs = self.updateRefID()
674 for ref in parentRefs:
675 refs.append("Sig_%s" % ref)
678 verified = os.popen('%s --verify --node-id "%s" %s %s 2>&1' \
679 % (self.xmlsec_path, ref, cert_args, filename)).read()
680 if not verified.strip().startswith("OK"):
681 raise CredentialNotVerifiable("xmlsec1 error verifying cert: " + verified)
684 # Verify the parents (delegation)
686 self.verify_parent(self.parent)
688 # Make sure the issuer is the target's authority
693 # Creates a list of the credential and its parents, with the root
694 # (original delegated credential) as the last item in the list
695 def get_credential_list(self):
699 list.append(cur_cred)
701 cur_cred = cur_cred.parent
707 # Make sure the credential's target gid was signed by (or is the same) the entity that signed
708 # the original credential or an authority over that namespace.
709 def verify_issuer(self):
710 root_cred = self.get_credential_list()[-1]
711 root_target_gid = root_cred.get_gid_object()
712 root_cred_signer = root_cred.get_signature().get_issuer_gid()
714 if root_target_gid.is_signed_by_cert(root_cred_signer):
715 # cred signer matches target signer, return success
718 root_target_gid_str = root_target_gid.save_to_string()
719 root_cred_signer_str = root_cred_signer.save_to_string()
720 if root_target_gid_str == root_cred_signer_str:
721 # cred signer is target, return success
724 # See if it the signer is an authority over the domain of the target
725 # Maybe should be (hrn, type) = urn_to_hrn(root_cred_signer.get_urn())
726 root_cred_signer_type = root_cred_signer.get_type()
727 if (root_cred_signer_type == 'authority'):
728 #logger.debug('Cred signer is an authority')
729 # signer is an authority, see if target is in authority's domain
730 hrn = root_cred_signer.get_hrn()
731 if root_target_gid.get_hrn().startswith(hrn):
734 # We've required that the credential be signed by an authority
735 # for that domain. Reasonable and probably correct.
736 # A looser model would also allow the signer to be an authority
737 # in my control framework - eg My CA or CH. Even if it is not
738 # the CH that issued these, eg, user credentials.
740 # Give up, credential does not pass issuer verification
742 raise CredentialNotVerifiable("Could not verify credential owned by %s for object %s. Cred signer %s not the trusted authority for Cred target %s" % (self.gidCaller.get_urn(), self.gidObject.get_urn(), root_cred_signer.get_hrn(), root_target_gid.get_hrn()))
746 # -- For Delegates (credentials with parents) verify that:
747 # . The privileges must be a subset of the parent credentials
748 # . The privileges must have "can_delegate" set for each delegated privilege
749 # . The target gid must be the same between child and parents
750 # . The expiry time on the child must be no later than the parent
751 # . The signer of the child must be the owner of the parent
752 def verify_parent(self, parent_cred):
753 # make sure the rights given to the child are a subset of the
754 # parents rights (and check delegate bits)
755 if not parent_cred.get_privileges().is_superset(self.get_privileges()):
756 raise ChildRightsNotSubsetOfParent(
757 self.parent.get_privileges().save_to_string() + " " +
758 self.get_privileges().save_to_string())
760 # make sure my target gid is the same as the parent's
761 if not parent_cred.get_gid_object().save_to_string() == \
762 self.get_gid_object().save_to_string():
763 raise CredentialNotVerifiable("Target gid not equal between parent and child")
765 # make sure my expiry time is <= my parent's
766 if not parent_cred.get_lifetime() >= self.get_lifetime():
767 raise CredentialNotVerifiable("Delegated credential expires after parent")
769 # make sure my signer is the parent's caller
770 if not parent_cred.get_gid_caller().save_to_string(False) == \
771 self.get_signature().get_issuer_gid().save_to_string(False):
772 raise CredentialNotVerifiable("Delegated credential not signed by parent caller")
775 if parent_cred.parent:
776 parent_cred.verify_parent(parent_cred.parent)
779 # Dump the contents of a credential to stdout in human-readable format
781 # @param dump_parents If true, also dump the parent certificates
783 def dump(self, dump_parents=False):
784 # FIXME: get_subject doesnt exist
785 # print "CREDENTIAL", self.get_subject()
788 print " privs:", self.get_privileges().save_to_string()
791 gidCaller = self.get_gid_caller()
793 gidCaller.dump(8, dump_parents)
796 gidObject = self.get_gid_object()
798 gidObject.dump(8, dump_parents)
801 if self.parent and dump_parents:
803 self.parent.dump_parents()