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 if str.lower() in ['yes','true','1']:
32 # Two years, in minutes
33 DEFAULT_CREDENTIAL_LIFETIME = 1051200
37 # . make privs match between PG and PL
38 # . Need to test delegation, xml verification
39 # . Need to add support for other types of credentials, e.g. tickets
42 signature_template = \
44 <Signature xml:id="Sig_%s" xmlns="http://www.w3.org/2000/09/xmldsig#">
46 <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
47 <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
50 <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
52 <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
53 <DigestValue></DigestValue>
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
83 # Signature contains information about an xmlsec1 signature
84 # for a signed-credential
86 class Signature(object):
91 def __init__(self, string=None):
108 def set_refid(self, id):
111 def get_issuer_gid(self):
116 def set_issuer_gid(self, gid):
120 doc = parseString(self.xml)
121 sig = doc.getElementsByTagName("Signature")[0]
122 self.set_refid(sig.getAttribute("xml:id").strip("Sig_"))
123 keyinfo = sig.getElementsByTagName("X509Data")[0]
124 szgid = getTextNode(keyinfo, "X509Certificate")
125 szgid = "-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----" % szgid
126 self.set_issuer_gid(GID(string=szgid))
129 self.xml = signature_template % (self.get_refid(), self.get_refid())
133 # Credential is a tuple:
134 # (GIDCaller, GIDObject, Expiration (in UTC time), Privileges)
136 # These fields are encoded in one of two ways. The legacy style places
137 # it in the subjectAltName of an X509 certificate. The new credentials
138 # are placed in signed XML.
141 class Credential(object):
146 issuer_privkey = None
156 # Create a Credential object
158 # @param create If true, create a blank x509 certificate
159 # @param subject If subject!=None, create an x509 cert with the subject name
160 # @param string If string!=None, load the credential from the string
161 # @param filename If filename!=None, load the credential from the file
163 def __init__(self, create=False, subject=None, string=None, filename=None):
165 # Check if this is a legacy credential, translate it if so
166 if string or filename:
170 str = file(filename).read()
172 if str.strip().startswith("-----"):
173 self.legacy = CredentialLegacy(False,string=str)
174 self.translate_legacy(str)
180 def get_signature(self):
181 if not self.signature:
183 return self.signature
185 def set_signature(self, sig):
190 # Translate a legacy credential into a new one
192 # @param String of the legacy credential
194 def translate_legacy(self, str):
195 legacy = CredentialLegacy(False,string=str)
196 self.gidCaller = legacy.get_gid_caller()
197 self.gidObject = legacy.get_gid_object()
198 lifetime = legacy.get_lifetime()
200 # Default to two years
201 self.set_lifetime(DEFAULT_CREDENTIAL_LIFETIME)
203 self.set_lifetime(int(lifetime))
204 self.lifeTime = legacy.get_lifetime()
205 self.set_privileges(legacy.get_privileges())
206 self.get_privileges().delegate_all_privileges(legacy.get_delegate())
209 # Need the issuer's private key and name
210 # @param key Keypair object containing the private key of the issuer
211 # @param gid GID of the issuing authority
213 def set_issuer_keys(self, privkey, gid):
214 self.issuer_privkey = privkey
215 self.issuer_gid = gid
219 # Set this credential's parent
220 def set_parent(self, cred):
225 # set the GID of the caller
227 # @param gid GID object of the caller
229 def set_gid_caller(self, gid):
231 # gid origin caller is the caller's gid by default
232 self.gidOriginCaller = gid
235 # get the GID of the object
237 def get_gid_caller(self):
238 if not self.gidCaller:
240 return self.gidCaller
243 # set the GID of the object
245 # @param gid GID object of the object
247 def set_gid_object(self, gid):
251 # get the GID of the object
253 def get_gid_object(self):
254 if not self.gidObject:
256 return self.gidObject
259 # set the lifetime of this credential
261 # @param lifetime lifetime of credential
262 # . if lifeTime is a datetime object, it is used for the expiration time
263 # . if lifeTime is an integer value, it is considered the number of minutes
264 # remaining before expiration
266 def set_lifetime(self, lifeTime):
267 if isinstance(lifeTime, int):
268 self.expiration = datetime.timedelta(seconds=lifeTime*60) + datetime.datetime.utcnow()
270 self.expiration = lifeTime
273 # get the lifetime of the credential (in minutes)
275 def get_lifetime(self):
276 if not self.expiration:
278 return self.expiration
284 # @param privs either a comma-separated list of privileges of a RightList object
286 def set_privileges(self, privs):
287 if isinstance(privs, str):
288 self.privileges = RightList(string = privs)
290 self.privileges = privs
294 # return the privileges as a RightList object
296 def get_privileges(self):
297 if not self.privileges:
299 return self.privileges
302 # determine whether the credential allows a particular operation to be
305 # @param op_name string specifying name of operation ("lookup", "update", etc)
307 def can_perform(self, op_name):
308 rights = self.get_privileges()
313 return rights.can_perform(op_name)
315 def append_sub(self, doc, parent, element, text):
316 ele = doc.createElement(element)
317 ele.appendChild(doc.createTextNode(text))
318 parent.appendChild(ele)
321 # Encode the attributes of the credential into an XML string
322 # This should be done immediately before signing the credential.
327 # Create the XML document
329 signed_cred = doc.createElement("signed-credential")
330 doc.appendChild(signed_cred)
332 # Fill in the <credential> bit
333 cred = doc.createElement("credential")
334 cred.setAttribute("xml:id", self.get_refid())
335 signed_cred.appendChild(cred)
336 self.append_sub(doc, cred, "type", "privilege")
337 self.append_sub(doc, cred, "serial", "8")
338 self.append_sub(doc, cred, "owner_gid", self.gidCaller.save_to_string())
339 self.append_sub(doc, cred, "owner_urn", self.gidCaller.get_urn())
340 self.append_sub(doc, cred, "target_gid", self.gidObject.save_to_string())
341 self.append_sub(doc, cred, "target_urn", self.gidObject.get_urn())
342 self.append_sub(doc, cred, "uuid", "")
343 if not self.expiration:
344 self.set_lifetime(3600)
345 self.expiration = self.expiration.replace(microsecond=0)
346 self.append_sub(doc, cred, "expires", self.expiration.isoformat())
347 privileges = doc.createElement("privileges")
348 cred.appendChild(privileges)
351 rights = self.get_privileges()
352 for right in rights.rights:
353 priv = doc.createElement("privilege")
354 self.append_sub(doc, priv, "name", right.kind)
355 self.append_sub(doc, priv, "can_delegate", str(right.delegate).lower())
356 privileges.appendChild(priv)
358 # Add the parent credential if it exists
360 sdoc = parseString(self.parent.get_xml())
361 p_cred = doc.importNode(sdoc.getElementsByTagName("credential")[0], True)
362 p = doc.createElement("parent")
363 p.appendChild(p_cred)
367 # Create the <signatures> tag
368 signatures = doc.createElement("signatures")
369 signed_cred.appendChild(signatures)
371 # Add any parent signatures
373 cur_cred = self.parent
375 sdoc = parseString(cur_cred.get_signature().get_xml())
376 ele = doc.importNode(sdoc.getElementsByTagName("Signature")[0], True)
377 signatures.appendChild(ele)
380 cur_cred = cur_cred.parent
384 # Get the finished product
385 self.xml = doc.toxml()
390 def save_to_random_tmp_file(self):
391 filename = "/tmp/cred_%d" % randint(0,999999999)
392 self.save_to_file(filename)
395 def save_to_file(self, filename, save_parents=True):
398 f = open(filename, "w")
402 def save_to_string(self, save_parents=True):
412 def set_refid(self, rid):
416 # Figure out what refids exist, and update this credential's id
417 # so that it doesn't clobber the others. Returns the refids of
420 def updateRefID(self):
422 self.set_refid('ref0')
427 next_cred = self.parent
429 refs.append(next_cred.get_refid())
431 next_cred = next_cred.parent
436 # Find a unique refid for this credential
437 rid = self.get_refid()
440 rid = "ref%d" % (val + 1)
445 # Return the set of parent credential ref ids
454 if not self.issuer_privkey or not self.issuer_gid:
456 doc = parseString(self.get_xml())
457 sigs = doc.getElementsByTagName("signatures")[0]
459 # Create the signature template to be signed
460 signature = Signature()
461 signature.set_refid(self.get_refid())
462 sdoc = parseString(signature.get_xml())
463 sig_ele = doc.importNode(sdoc.getElementsByTagName("Signature")[0], True)
464 sigs.appendChild(sig_ele)
466 self.xml = doc.toxml()
469 # Split the issuer GID into multiple certificates if it's a chain
470 chain = GID(filename=self.issuer_gid)
473 gid_files.append(chain.save_to_random_tmp_file(False))
474 if chain.get_parent():
475 chain = chain.get_parent()
480 # Call out to xmlsec1 to sign it
481 ref = 'Sig_%s' % self.get_refid()
482 filename = self.save_to_random_tmp_file()
483 signed = os.popen('/usr/bin/xmlsec1 --sign --node-id "%s" --privkey-pem %s,%s %s' \
484 % (ref, self.issuer_privkey, ",".join(gid_files), filename)).read()
487 for gid_file in gid_files:
492 # This is no longer a legacy credential
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.
510 doc = parseString(self.xml)
512 signed_cred = doc.getElementsByTagName("signed-credential")
514 # Is this a signed-cred or just a cred?
515 if len(signed_cred) > 0:
516 cred = signed_cred[0].getElementsByTagName("credential")[0]
517 signatures = signed_cred[0].getElementsByTagName("signatures")
518 if len(signatures) > 0:
519 sigs = signatures[0].getElementsByTagName("Signature")
521 cred = doc.getElementsByTagName("credential")[0]
525 self.set_refid(cred.getAttribute("xml:id"))
526 sz_expires = getTextNode(cred, "expires")
528 self.expiration = datetime.datetime.strptime(sz_expires, '%Y-%m-%dT%H:%M:%S')
529 self.lifeTime = getTextNode(cred, "expires")
530 self.gidCaller = GID(string=getTextNode(cred, "owner_gid"))
531 self.gidObject = GID(string=getTextNode(cred, "target_gid"))
535 privs = cred.getElementsByTagName("privileges")[0]
537 for priv in privs.getElementsByTagName("privilege"):
538 kind = getTextNode(priv, "name")
539 deleg = str2bool(getTextNode(priv, "can_delegate"))
540 rlist.add(Right(kind.strip(), deleg))
541 self.set_privileges(rlist)
545 parent = cred.getElementsByTagName("parent")
547 parent_doc = parent[0].getElementsByTagName("credential")[0]
548 parent_xml = parent_doc.toxml()
549 self.parent = Credential(string=parent_xml)
552 # Assign the signatures to the credentials
554 Sig = Signature(string=sig.toxml())
558 if cur_cred.get_refid() == Sig.get_refid():
559 cur_cred.set_signature(Sig)
562 cur_cred = cur_cred.parent
569 # . All of the signatures are valid and that the issuers trace back
570 # to trusted roots (performed by xmlsec1)
571 # . The XML matches the credential schema
572 # . That the issuer of the credential is the authority in the target's urn
573 # . In the case of a delegated credential, this must be true of the root
574 # . That all of the gids presented in the credential are valid
576 # -- For Delegates (credentials with parents)
577 # . The privileges must be a subset of the parent credentials
578 # . The privileges must have "can_delegate" set for each delegated privilege
579 # . The target gid must be the same between child and parents
580 # . The expiry time on the child must be no later than the parent
581 # . The signer of the child must be the owner of the parent
583 # -- Verify does *NOT*
584 # . ensure that an xmlrpc client's gid matches a credential gid, that
585 # must be done elsewhere
587 # @param trusted_certs: The certificates of trusted CA certificates
589 def verify(self, trusted_certs):
593 # Check for schema conformance
597 trusted_cert_objects = [GID(filename=f) for f in trusted_certs]
599 # Use legacy verification if this is a legacy credential
601 self.legacy.verify_chain(trusted_cert_objects)
602 if self.legacy.client_gid:
603 self.legacy.client_gid.verify_chain(trusted_cert_objects)
604 if self.legacy.object_gid:
605 self.legacy.object_gid.verify_chain(trusted_cert_objects)
608 # Verify the signatures
609 filename = self.save_to_random_tmp_file()
610 cert_args = " ".join(['--trusted-pem %s' % x for x in trusted_certs])
612 # Verify the gids of this cred and of its parents
616 cur_cred.get_gid_object().verify_chain(trusted_cert_objects)
617 cur_cred.get_gid_caller().verify_chain(trusted_cert_objects)
619 cur_cred = cur_cred.parent
624 refs.append("Sig_%s" % self.get_refid())
626 parentRefs = self.updateRefID()
627 for ref in parentRefs:
628 refs.append("Sig_%s" % ref)
631 verified = os.popen('/usr/bin/xmlsec1 --verify --node-id "%s" %s %s 2>&1' \
632 % (ref, cert_args, filename)).read()
633 if not verified.strip().startswith("OK"):
634 raise CredentialNotVerifiable("xmlsec1 error: " + verified)
638 # Verify the parents (delegation)
640 self.verify_parent(self.parent)
642 # Make sure the issuer is the target's authority
649 # Make sure the issuer of this credential is the target's authority
650 def verify_issuer(self):
651 target_authority = get_authority(self.get_gid_object().get_urn())
653 # Find the root credential's signature
658 cur_cred = cur_cred.parent
660 root_issuer = cur_cred.get_signature().get_issuer_gid().get_urn()
664 # Ensure that the signer of the root credential is the target_authority
665 target_authority = hrn_to_urn(target_authority, 'authority')
667 if root_issuer != target_authority:
668 raise CredentialNotVerifiable("issuer (%s) != authority of target (%s)" \
669 % (root_issuer, target_authority))
672 # -- For Delegates (credentials with parents) verify that:
673 # . The privileges must be a subset of the parent credentials
674 # . The privileges must have "can_delegate" set for each delegated privilege
675 # . The target gid must be the same between child and parents
676 # . The expiry time on the child must be no later than the parent
677 # . The signer of the child must be the owner of the parent
679 def verify_parent(self, parent_cred):
680 # make sure the rights given to the child are a subset of the
681 # parents rights (and check delegate bits)
682 if not parent_cred.get_privileges().is_superset(self.get_privileges()):
683 raise ChildRightsNotSubsetOfParent(
684 self.parent.get_privileges().save_to_string() + " " +
685 self.get_privileges().save_to_string())
687 # make sure my target gid is the same as the parent's
688 if not parent_cred.get_gid_object().save_to_string() == \
689 self.get_gid_object().save_to_string():
690 raise CredentialNotVerifiable("target gid not equal between parent and child")
692 # make sure my expiry time is <= my parent's
693 if not parent_cred.get_lifetime() >= self.get_lifetime():
694 raise CredentialNotVerifiable("delegated credential expires after parent")
696 # make sure my signer is the parent's caller
697 if not parent_cred.get_gid_caller().save_to_string(False) == \
698 self.get_signature().get_issuer_gid().save_to_string(False):
699 raise CredentialNotVerifiable("delegated credential not signed by parent caller")
701 if parent_cred.parent:
702 parent_cred.verify_parent(parent_cred.parent)
705 # Dump the contents of a credential to stdout in human-readable format
707 # @param dump_parents If true, also dump the parent certificates
709 def dump(self, dump_parents=False):
710 print "CREDENTIAL", self.get_subject()
712 print " privs:", self.get_privileges().save_to_string()
715 gidCaller = self.get_gid_caller()
717 gidCaller.dump(8, dump_parents)
720 gidObject = self.get_gid_object()
722 gidObject.dump(8, dump_parents)
725 if self.parent and dump_parents:
727 self.parent.dump_parents()