2 # Implements SFA Credentials
4 # Credentials are signed XML files that assign a subject gid privileges to an object gid
13 from random import randint
16 from xml.dom.minidom import Document, parseString
17 from sfa.trust.credential_legacy import CredentialLegacy
18 from sfa.trust.certificate import Certificate
19 from sfa.trust.rights import *
20 from sfa.trust.gid import *
21 from sfa.util.faults import *
22 from sfa.util.sfalogging import logger
23 from lxml import etree
27 # Two years, in minutes
28 DEFAULT_CREDENTIAL_LIFETIME = 1051200
32 # . make privs match between PG and PL
33 # . Need to test delegation, xml verification
34 # . Need to add support for other types of credentials, e.g. tickets
37 signature_template = \
39 <Signature xml:id="Sig_%s" xmlns="http://www.w3.org/2000/09/xmldsig#">
41 <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
42 <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
45 <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
47 <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
48 <DigestValue></DigestValue>
66 # Utility function to get the text of an XML element
68 def getTextNode(element, subele):
69 sub = element.getElementsByTagName(subele)[0]
70 if len(sub.childNodes) > 0:
71 return sub.childNodes[0].nodeValue
78 # Signature contains information about an xmlsec1 signature
79 # for a signed-credential
81 class Signature(object):
86 def __init__(self, string=None):
103 def set_refid(self, id):
106 def get_issuer_gid(self):
111 def set_issuer_gid(self, gid):
115 doc = parseString(self.xml)
116 sig = doc.getElementsByTagName("Signature")[0]
117 self.set_refid(sig.getAttribute("xml:id").strip("Sig_"))
118 keyinfo = sig.getElementsByTagName("X509Data")[0]
119 szgid = getTextNode(keyinfo, "X509Certificate")
120 szgid = "-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----" % szgid
121 self.set_issuer_gid(GID(string=szgid))
124 self.xml = signature_template % (self.get_refid(), self.get_refid())
128 # Credential is a tuple:
129 # (GIDCaller, GIDObject, Expiration (in UTC time), Privileges)
131 # These fields are encoded in one of two ways. The legacy style places
132 # it in the subjectAltName of an X509 certificate. The new credentials
133 # are placed in signed XML.
136 class Credential(object):
141 issuer_privkey = None
151 # Create a Credential object
153 # @param create If true, create a blank x509 certificate
154 # @param subject If subject!=None, create an x509 cert with the subject name
155 # @param string If string!=None, load the credential from the string
156 # @param filename If filename!=None, load the credential from the file
158 def __init__(self, create=False, subject=None, string=None, filename=None):
160 # Check if this is a legacy credential, translate it if so
161 if string or filename:
165 str = file(filename).read()
167 if str.strip().startswith("-----"):
168 self.legacy = CredentialLegacy(False,string=str)
169 self.translate_legacy(str)
175 def get_signature(self):
176 if not self.signature:
178 return self.signature
180 def set_signature(self, sig):
185 # Translate a legacy credential into a new one
187 # @param String of the legacy credential
189 def translate_legacy(self, str):
190 legacy = CredentialLegacy(False,string=str)
191 self.gidCaller = legacy.get_gid_caller()
192 self.gidObject = legacy.get_gid_object()
193 lifetime = legacy.get_lifetime()
195 # Default to two years
196 self.set_lifetime(DEFAULT_CREDENTIAL_LIFETIME)
198 self.set_lifetime(int(lifetime))
199 self.lifeTime = legacy.get_lifetime()
200 self.set_privileges(legacy.get_privileges())
201 self.get_privileges().delegate_all_privileges(legacy.get_delegate())
204 # Need the issuer's private key and name
205 # @param key Keypair object containing the private key of the issuer
206 # @param gid GID of the issuing authority
208 def set_issuer_keys(self, privkey, gid):
209 self.issuer_privkey = privkey
210 self.issuer_gid = gid
214 # Set this credential's parent
215 def set_parent(self, cred):
220 # set the GID of the caller
222 # @param gid GID object of the caller
224 def set_gid_caller(self, gid):
226 # gid origin caller is the caller's gid by default
227 self.gidOriginCaller = gid
230 # get the GID of the object
232 def get_gid_caller(self):
233 if not self.gidCaller:
235 return self.gidCaller
238 # set the GID of the object
240 # @param gid GID object of the object
242 def set_gid_object(self, gid):
246 # get the GID of the object
248 def get_gid_object(self):
249 if not self.gidObject:
251 return self.gidObject
254 # set the lifetime of this credential
256 # @param lifetime lifetime of credential
257 # . if lifeTime is a datetime object, it is used for the expiration time
258 # . if lifeTime is an integer value, it is considered the number of minutes
259 # remaining before expiration
261 def set_lifetime(self, lifeTime):
262 if isinstance(lifeTime, int):
263 self.expiration = datetime.timedelta(seconds=lifeTime*60) + datetime.datetime.utcnow()
265 self.expiration = lifeTime
268 # get the lifetime of the credential (in minutes)
270 def get_lifetime(self):
271 if not self.expiration:
273 return self.expiration
279 # @param privs either a comma-separated list of privileges of a RightList object
281 def set_privileges(self, privs):
282 if isinstance(privs, str):
283 self.privileges = RightList(string = privs)
285 self.privileges = privs
289 # return the privileges as a RightList object
291 def get_privileges(self):
292 if not self.privileges:
294 return self.privileges
297 # determine whether the credential allows a particular operation to be
300 # @param op_name string specifying name of operation ("lookup", "update", etc)
302 def can_perform(self, op_name):
303 rights = self.get_privileges()
308 return rights.can_perform(op_name)
310 def append_sub(self, doc, parent, element, text):
311 ele = doc.createElement(element)
312 ele.appendChild(doc.createTextNode(text))
313 parent.appendChild(ele)
316 # Encode the attributes of the credential into an XML string
317 # This should be done immediately before signing the credential.
322 # Create the XML document
324 signed_cred = doc.createElement("signed-credential")
325 doc.appendChild(signed_cred)
327 # Fill in the <credential> bit
328 cred = doc.createElement("credential")
329 cred.setAttribute("xml:id", self.get_refid())
330 signed_cred.appendChild(cred)
331 self.append_sub(doc, cred, "type", "privilege")
332 self.append_sub(doc, cred, "serial", "8")
333 self.append_sub(doc, cred, "owner_gid", self.gidCaller.save_to_string())
334 self.append_sub(doc, cred, "owner_urn", self.gidCaller.get_urn())
335 self.append_sub(doc, cred, "target_gid", self.gidObject.save_to_string())
336 self.append_sub(doc, cred, "target_urn", self.gidObject.get_urn())
337 self.append_sub(doc, cred, "uuid", "")
338 if not self.expiration:
339 self.set_lifetime(3600)
340 self.expiration = self.expiration.replace(microsecond=0)
341 self.append_sub(doc, cred, "expires", self.expiration.isoformat())
342 privileges = doc.createElement("privileges")
343 cred.appendChild(privileges)
346 rights = self.get_privileges()
347 for right in rights.rights:
348 priv = doc.createElement("privilege")
349 self.append_sub(doc, priv, "name", right.kind)
350 self.append_sub(doc, priv, "can_delegate", str(right.delegate))
351 privileges.appendChild(priv)
353 # Add the parent credential if it exists
355 sdoc = parseString(self.parent.get_xml())
356 p_cred = doc.importNode(sdoc.getElementsByTagName("credential")[0], True)
357 p = doc.createElement("parent")
358 p.appendChild(p_cred)
362 # Create the <signatures> tag
363 signatures = doc.createElement("signatures")
364 signed_cred.appendChild(signatures)
366 # Add any parent signatures
368 cur_cred = self.parent
370 sdoc = parseString(cur_cred.get_signature().get_xml())
371 ele = doc.importNode(sdoc.getElementsByTagName("Signature")[0], True)
372 signatures.appendChild(ele)
375 cur_cred = cur_cred.parent
379 # Get the finished product
380 self.xml = doc.toxml()
385 def save_to_random_tmp_file(self):
386 filename = "/tmp/cred_%d" % randint(0,999999999)
387 self.save_to_file(filename)
390 def save_to_file(self, filename, save_parents=True):
393 f = open(filename, "w")
397 def save_to_string(self, save_parents=True):
407 def set_refid(self, rid):
411 # Figure out what refids exist, and update this credential's id
412 # so that it doesn't clobber the others. Returns the refids of
415 def updateRefID(self):
417 self.set_refid('ref0')
422 next_cred = self.parent
424 refs.append(next_cred.get_refid())
426 next_cred = next_cred.parent
431 # Find a unique refid for this credential
432 rid = self.get_refid()
435 rid = "ref%d" % (val + 1)
440 # Return the set of parent credential ref ids
449 if not self.issuer_privkey or not self.issuer_gid:
451 doc = parseString(self.get_xml())
452 sigs = doc.getElementsByTagName("signatures")[0]
454 # Create the signature template to be signed
455 signature = Signature()
456 signature.set_refid(self.get_refid())
457 sdoc = parseString(signature.get_xml())
458 sig_ele = doc.importNode(sdoc.getElementsByTagName("Signature")[0], True)
459 sigs.appendChild(sig_ele)
461 self.xml = doc.toxml()
464 # Split the issuer GID into multiple certificates if it's a chain
465 chain = GID(filename=self.issuer_gid)
468 gid_files.append(chain.save_to_random_tmp_file(False))
469 if chain.get_parent():
470 chain = chain.get_parent()
475 # Call out to xmlsec1 to sign it
476 ref = 'Sig_%s' % self.get_refid()
477 filename = self.save_to_random_tmp_file()
478 signed = os.popen('/usr/bin/xmlsec1 --sign --node-id "%s" --privkey-pem %s,%s %s' \
479 % (ref, self.issuer_privkey, ",".join(gid_files), filename)).read()
484 # This is no longer a legacy credential
495 # Retrieve the attributes of the credential from the XML.
496 # This is automatically caleld by the various get_* methods of
497 # this class and should not need to be called explicitly.
502 doc = parseString(self.xml)
504 signed_cred = doc.getElementsByTagName("signed-credential")
506 # Is this a signed-cred or just a cred?
507 if len(signed_cred) > 0:
508 cred = signed_cred[0].getElementsByTagName("credential")[0]
509 signatures = signed_cred[0].getElementsByTagName("signatures")
510 if len(signatures) > 0:
511 sigs = signatures[0].getElementsByTagName("Signature")
513 cred = doc.getElementsByTagName("credential")[0]
517 self.set_refid(cred.getAttribute("xml:id"))
518 sz_expires = getTextNode(cred, "expires")
520 self.expiration = datetime.datetime.strptime(sz_expires, '%Y-%m-%dT%H:%M:%S')
521 self.lifeTime = getTextNode(cred, "expires")
522 self.gidCaller = GID(string=getTextNode(cred, "owner_gid"))
523 self.gidObject = GID(string=getTextNode(cred, "target_gid"))
527 privs = cred.getElementsByTagName("privileges")[0]
529 for priv in privs.getElementsByTagName("privilege"):
530 kind = getTextNode(priv, "name")
531 deleg = bool(getTextNode(priv, "can_delegate"))
532 rlist.add(Right(kind.strip(), deleg))
533 self.set_privileges(rlist)
537 parent = cred.getElementsByTagName("parent")
539 parent_doc = parent[0].getElementsByTagName("credential")[0]
540 parent_xml = parent_doc.toxml()
541 self.parent = Credential(string=parent_xml)
544 # Assign the signatures to the credentials
546 Sig = Signature(string=sig.toxml())
550 if cur_cred.get_refid() == Sig.get_refid():
551 cur_cred.set_signature(Sig)
554 cur_cred = cur_cred.parent
561 # . All of the signatures are valid and that the issuers trace back
562 # to trusted roots (performed by xmlsec1)
563 # . The XML matches the credential schema
564 # . That the issuer of the credential is the authority in the target's urn
565 # . In the case of a delegated credential, this must be true of the root
566 # . That all of the gids presented in the credential are valid
568 # -- For Delegates (credentials with parents)
569 # . The privileges must be a subset of the parent credentials
570 # . The privileges must have "can_delegate" set for each delegated privilege
571 # . The target gid must be the same between child and parents
572 # . The expiry time on the child must be no later than the parent
573 # . The signer of the child must be the owner of the parent
575 # -- Verify does *NOT*
576 # . ensure that an xmlrpc client's gid matches a credential gid, that
577 # must be done elsewhere
579 # @param trusted_certs: The certificates of trusted CA certificates
581 def verify(self, trusted_certs):
585 # Check for schema conformance
589 trusted_cert_objects = [GID(filename=f) for f in trusted_certs]
591 # Use legacy verification if this is a legacy credential
593 self.legacy.verify_chain(trusted_cert_objects)
594 if self.legacy.client_gid:
595 self.legacy.client_gid.verify_chain(trusted_cert_objects)
596 if self.legacy.object_gid:
597 self.legacy.object_gid.verify_chain(trusted_cert_objects)
600 # Verify the signatures
601 filename = self.save_to_random_tmp_file()
602 cert_args = " ".join(['--trusted-pem %s' % x for x in trusted_certs])
604 # Verify the gids of this cred and of its parents
608 cur_cred.get_gid_object().verify_chain(trusted_cert_objects)
609 cur_cred.get_gid_caller().verify_chain(trusted_cert_objects)
611 cur_cred = cur_cred.parent
616 refs.append("Sig_%s" % self.get_refid())
618 parentRefs = self.updateRefID()
619 for ref in parentRefs:
620 refs.append("Sig_%s" % ref)
623 verified = os.popen('/usr/bin/xmlsec1 --verify --node-id "%s" %s %s 2>&1' \
624 % (ref, cert_args, filename)).read()
625 if not verified.strip().startswith("OK"):
626 raise CredentialNotVerifiable("xmlsec1 error: " + verified)
630 # Verify the parents (delegation)
632 self.verify_parent(self.parent)
634 # Make sure the issuer is the target's authority
641 # Make sure the issuer of this credential is the target's authority
642 def verify_issuer(self):
643 target_authority = get_authority(self.get_gid_object().get_urn())
645 # Find the root credential's signature
650 cur_cred = cur_cred.parent
652 root_issuer = cur_cred.get_signature().get_issuer_gid().get_urn()
656 # Ensure that the signer of the root credential is the target_authority
657 target_authority = hrn_to_urn(target_authority, 'authority')
659 if root_issuer != target_authority:
660 raise CredentialNotVerifiable("issuer (%s) != authority of target (%s)" \
661 % (root_issuer, target_authority))
664 # -- For Delegates (credentials with parents) verify that:
665 # . The privileges must be a subset of the parent credentials
666 # . The privileges must have "can_delegate" set for each delegated privilege
667 # . The target gid must be the same between child and parents
668 # . The expiry time on the child must be no later than the parent
669 # . The signer of the child must be the owner of the parent
671 def verify_parent(self, parent_cred):
672 # make sure the rights given to the child are a subset of the
673 # parents rights (and check delegate bits)
674 if not parent_cred.get_privileges().is_superset(self.get_privileges()):
675 raise ChildRightsNotSubsetOfParent(
676 self.parent.get_privileges().save_to_string() + " " +
677 self.get_privileges().save_to_string())
679 # make sure my target gid is the same as the parent's
680 if not parent_cred.get_gid_object().save_to_string() == \
681 self.get_gid_object().save_to_string():
682 raise CredentialNotVerifiable("target gid not equal between parent and child")
684 # make sure my expiry time is <= my parent's
685 if not parent_cred.get_lifetime() >= self.get_lifetime():
686 raise CredentialNotVerifiable("delegated credential expires after parent")
688 # make sure my signer is the parent's caller
689 if not parent_cred.get_gid_caller().save_to_string(False) == \
690 self.get_signature().get_issuer_gid().save_to_string(False):
691 raise CredentialNotVerifiable("delegated credential not signed by parent caller")
693 if parent_cred.parent:
694 parent_cred.verify_parent(parent_cred.parent)
697 # Dump the contents of a credential to stdout in human-readable format
699 # @param dump_parents If true, also dump the parent certificates
701 def dump(self, dump_parents=False):
702 print "CREDENTIAL", self.get_subject()
704 print " privs:", self.get_privileges().save_to_string()
707 gidCaller = self.get_gid_caller()
709 gidCaller.dump(8, dump_parents)
712 gidObject = self.get_gid_object()
714 gidObject.dump(8, dump_parents)
717 if self.parent and dump_parents:
719 self.parent.dump_parents()