2 # Implements SFA Credentials
4 # Credentials are signed XML files that assign a subject gid privileges to an object gid
15 from xml.dom.minidom import Document, parseString
16 from sfa.trust.credential_legacy import CredentialLegacy
17 from sfa.trust.certificate import Certificate
18 from sfa.trust.rights import *
19 from sfa.trust.gid import *
20 from sfa.util.faults import *
21 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 test delegation, xml verification
31 # . 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>
63 # Utility function to get the text of an XML element
65 def getTextNode(element, subele):
66 sub = element.getElementsByTagName(subele)[0]
67 if len(sub.childNodes) > 0:
68 return sub.childNodes[0].nodeValue
75 # Signature contains information about an xmlsec1 signature
76 # for a signed-credential
78 class Signature(object):
83 def __init__(self, string=None):
100 def set_refid(self, id):
103 def get_issuer_gid(self):
108 def set_issuer_gid(self, gid):
112 doc = parseString(self.xml)
113 sig = doc.getElementsByTagName("Signature")[0]
114 self.set_refid(sig.getAttribute("xml:id").strip("Sig_"))
115 keyinfo = sig.getElementsByTagName("X509Data")[0]
116 szgid = getTextNode(keyinfo, "X509Certificate")
117 szgid = "-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----" % szgid
118 self.set_issuer_gid(GID(string=szgid))
121 self.xml = signature_template % (self.get_refid(), self.get_refid())
125 # Credential is a tuple:
126 # (GIDCaller, GIDObject, Expiration (in UTC time), Privileges)
128 # These fields are encoded in one of two ways. The legacy style places
129 # it in the subjectAltName of an X509 certificate. The new credentials
130 # are placed in signed XML.
133 class Credential(object):
138 issuer_privkey = None
147 # Create a Credential object
149 # @param create If true, create a blank x509 certificate
150 # @param subject If subject!=None, create an x509 cert with the subject name
151 # @param string If string!=None, load the credential from the string
152 # @param filename If filename!=None, load the credential from the file
154 def __init__(self, create=False, subject=None, string=None, filename=None):
156 # Check if this is a legacy credential, translate it if so
157 if string or filename:
161 str = file(filename).read()
163 if str.strip().startswith("-----"):
164 self.translate_legacy(str)
170 def get_signature(self):
171 if not self.signature:
173 return self.signature
175 def set_signature(self, sig):
180 # Translate a legacy credential into a new one
182 # @param String of the legacy credential
184 def translate_legacy(self, str):
185 legacy = CredentialLegacy(False,string=str)
186 self.gidCaller = legacy.get_gid_caller()
187 self.gidObject = legacy.get_gid_object()
188 lifetime = legacy.get_lifetime()
190 # Default to two years
191 self.set_lifetime(DEFAULT_CREDENTIAL_LIFETIME)
193 self.set_lifetime(int(lifetime))
194 self.lifeTime = legacy.get_lifetime()
195 self.set_privileges(legacy.get_privileges())
196 self.get_privileges().delegate_all_privileges(legacy.get_delegate())
199 # Need the issuer's private key and name
200 # @param key Keypair object containing the private key of the issuer
201 # @param gid GID of the issuing authority
203 def set_issuer_keys(self, privkey, gid):
204 self.issuer_privkey = privkey
205 self.issuer_gid = gid
209 # Set this credential's parent
210 def set_parent(self, cred):
215 # set the GID of the caller
217 # @param gid GID object of the caller
219 def set_gid_caller(self, gid):
221 # gid origin caller is the caller's gid by default
222 self.gidOriginCaller = gid
225 # get the GID of the object
227 def get_gid_caller(self):
228 if not self.gidCaller:
230 return self.gidCaller
233 # set the GID of the object
235 # @param gid GID object of the object
237 def set_gid_object(self, gid):
241 # get the GID of the object
243 def get_gid_object(self):
244 if not self.gidObject:
246 return self.gidObject
249 # set the lifetime of this credential
251 # @param lifetime lifetime of credential
252 # . if lifeTime is a datetime object, it is used for the expiration time
253 # . if lifeTime is an integer value, it is considered the number of minutes
254 # remaining before expiration
256 def set_lifetime(self, lifeTime):
257 if isinstance(lifeTime, int):
258 self.expiration = datetime.timedelta(seconds=lifeTime*60) + datetime.datetime.utcnow()
260 self.expiration = lifeTime
263 # get the lifetime of the credential (in minutes)
265 def get_lifetime(self):
266 if not self.expiration:
268 return self.expiration
274 # @param privs either a comma-separated list of privileges of a RightList object
276 def set_privileges(self, privs):
277 if isinstance(privs, str):
278 self.privileges = RightList(string = privs)
280 self.privileges = privs
284 # return the privileges as a RightList object
286 def get_privileges(self):
287 if not self.privileges:
289 return self.privileges
292 # determine whether the credential allows a particular operation to be
295 # @param op_name string specifying name of operation ("lookup", "update", etc)
297 def can_perform(self, op_name):
298 rights = self.get_privileges()
303 return rights.can_perform(op_name)
305 def append_sub(self, doc, parent, element, text):
306 ele = doc.createElement(element)
307 ele.appendChild(doc.createTextNode(text))
308 parent.appendChild(ele)
311 # Encode the attributes of the credential into an XML string
312 # This should be done immediately before signing the credential.
317 # Create the XML document
319 signed_cred = doc.createElement("signed-credential")
320 doc.appendChild(signed_cred)
322 # Fill in the <credential> bit
323 cred = doc.createElement("credential")
324 cred.setAttribute("xml:id", self.get_refid())
325 signed_cred.appendChild(cred)
326 self.append_sub(doc, cred, "type", "privilege")
327 self.append_sub(doc, cred, "serial", "8")
328 self.append_sub(doc, cred, "owner_gid", self.gidCaller.save_to_string())
329 self.append_sub(doc, cred, "owner_urn", self.gidCaller.get_urn())
330 self.append_sub(doc, cred, "target_gid", self.gidObject.save_to_string())
331 self.append_sub(doc, cred, "target_urn", self.gidObject.get_urn())
332 self.append_sub(doc, cred, "uuid", "")
333 if not self.expiration:
334 self.set_lifetime(3600)
335 self.expiration = self.expiration.replace(microsecond=0)
336 self.append_sub(doc, cred, "expires", self.expiration.isoformat())
337 privileges = doc.createElement("privileges")
338 cred.appendChild(privileges)
341 rights = self.get_privileges()
342 for right in rights.rights:
343 priv = doc.createElement("privilege")
344 self.append_sub(doc, priv, "name", right.kind)
345 self.append_sub(doc, priv, "can_delegate", str(right.delegate))
346 privileges.appendChild(priv)
348 # Add the parent credential if it exists
350 sdoc = parseString(self.parent.get_xml())
351 p_cred = doc.importNode(sdoc.getElementsByTagName("credential")[0], True)
352 p = doc.createElement("parent")
353 p.appendChild(p_cred)
357 # Create the <signatures> tag
358 signatures = doc.createElement("signatures")
359 signed_cred.appendChild(signatures)
361 # Add any parent signatures
363 cur_cred = self.parent
365 sdoc = parseString(cur_cred.get_signature().get_xml())
366 ele = doc.importNode(sdoc.getElementsByTagName("Signature")[0], True)
367 signatures.appendChild(ele)
370 cur_cred = cur_cred.parent
374 # Get the finished product
375 self.xml = doc.toxml()
380 def save_to_random_tmp_file(self):
381 filename = "/tmp/cred_%d" % random.randint(0,999999999)
382 self.save_to_file(filename)
385 def save_to_file(self, filename, save_parents=True):
388 f = open(filename, "w")
392 def save_to_string(self, save_parents=True):
402 def set_refid(self, rid):
406 # Figure out what refids exist, and update this credential's id
407 # so that it doesn't clobber the others. Returns the refids of
410 def updateRefID(self):
412 self.set_refid('ref0')
417 next_cred = self.parent
419 refs.append(next_cred.get_refid())
421 next_cred = next_cred.parent
426 # Find a unique refid for this credential
427 rid = self.get_refid()
430 rid = "ref%d" % (val + 1)
435 # Return the set of parent credential ref ids
444 if not self.issuer_privkey or not self.issuer_gid:
446 doc = parseString(self.get_xml())
447 sigs = doc.getElementsByTagName("signatures")[0]
449 # Create the signature template to be signed
450 signature = Signature()
451 signature.set_refid(self.get_refid())
452 sdoc = parseString(signature.get_xml())
453 sig_ele = doc.importNode(sdoc.getElementsByTagName("Signature")[0], True)
454 sigs.appendChild(sig_ele)
456 self.xml = doc.toxml()
458 # Call out to xmlsec1 to sign it
459 ref = 'Sig_%s' % self.get_refid()
460 filename = self.save_to_random_tmp_file()
461 signed = os.popen('/usr/bin/xmlsec1 --sign --node-id "%s" --privkey-pem %s,%s %s' \
462 % (ref, self.issuer_privkey, self.issuer_gid, filename)).read()
468 def getTextNode(self, element, subele):
469 sub = element.getElementsByTagName(subele)[0]
470 if len(sub.childNodes) > 0:
471 return sub.childNodes[0].nodeValue
476 # Retrieve the attributes of the credential from the XML.
477 # This is automatically caleld by the various get_* methods of
478 # this class and should not need to be called explicitly.
483 doc = parseString(self.xml)
485 signed_cred = doc.getElementsByTagName("signed-credential")
487 # Is this a signed-cred or just a cred?
488 if len(signed_cred) > 0:
489 cred = signed_cred[0].getElementsByTagName("credential")[0]
490 signatures = signed_cred[0].getElementsByTagName("signatures")
491 if len(signatures) > 0:
492 sigs = signatures[0].getElementsByTagName("Signature")
494 cred = doc.getElementsByTagName("credential")[0]
498 self.set_refid(cred.getAttribute("xml:id"))
499 sz_expires = getTextNode(cred, "expires")
501 self.expiration = datetime.datetime.strptime(sz_expires, '%Y-%m-%dT%H:%M:%S')
502 self.lifeTime = getTextNode(cred, "expires")
503 self.gidCaller = GID(string=getTextNode(cred, "owner_gid"))
504 self.gidObject = GID(string=getTextNode(cred, "target_gid"))
508 privs = cred.getElementsByTagName("privileges")[0]
510 for priv in privs.getElementsByTagName("privilege"):
511 kind = getTextNode(priv, "name")
512 deleg = bool(getTextNode(priv, "can_delegate"))
513 rlist.add(Right(kind.strip(), deleg))
514 self.set_privileges(rlist)
518 parent = cred.getElementsByTagName("parent")
520 self.parent = Credential(string=getTextNode(cred, "parent"))
523 # Assign the signatures to the credentials
525 Sig = Signature(string=sig.toxml())
529 if cur_cred.get_refid() == Sig.get_refid():
530 cur_cred.set_signature(Sig)
533 cur_cred = cur_cred.parent
540 # . All of the signatures are valid and that the issuers trace back
541 # to trusted roots (performed by xmlsec1)
542 # . That the issuer of the credential is the authority in the target's urn
543 # . In the case of a delegated credential, this must be true of the root
544 # . That all of the gids presented in the credential are valid
546 # -- For Delegates (credentials with parents)
547 # . The privileges must be a subset of the parent credentials
548 # . The privileges must have "can_delegate" set for each delegated privilege
549 # . The target gid must be the same between child and parents
550 # . The expiry time on the child must be no later than the parent
551 # . The signer of the child must be the owner of the parent
553 # -- Verify does *NOT*
554 # . ensure that an xmlrpc client's gid matches a credential gid, that
555 # must be done elsewhere
557 # @param trusted_certs: The certificates of trusted CA certificates
559 def verify(self, trusted_certs):
563 # Verify the signatures
564 filename = self.save_to_random_tmp_file()
565 cert_args = " ".join(['--trusted-pem %s' % x for x in trusted_certs])
567 # Verify the gids of this cred and of its parents
568 trusted_cert_objects = [GID(filename=f) for f in trusted_certs]
572 cur_cred.get_gid_object().verify_chain(trusted_cert_objects)
573 cur_cred.get_gid_caller().verify_chain(trusted_cert_objects)
575 cur_cred = cur_cred.parent
580 refs.append("Sig_%s" % self.get_refid())
582 parentRefs = self.updateRefID()
583 for ref in parentRefs:
584 refs.append("Sig_%s" % ref)
587 verified = os.popen('/usr/bin/xmlsec1 --verify --node-id "%s" %s %s 2>&1' \
588 % (ref, cert_args, filename)).read()
589 if not verified.strip().startswith("OK"):
590 raise CredentialNotVerifiable("xmlsec1 error: " + verified)
594 # Verify the parents (delegation)
596 self.verify_parent(self.parent)
598 # Make sure the issuer is the target's authority
604 # Make sure the issuer of this credential is the target's authority
605 def verify_issuer(self):
606 target_authority = get_authority(self.get_gid_object().get_urn())
608 # Find the root credential's signature
613 cur_cred = cur_cred.parent
615 root_issuer = cur_cred.get_signature().get_issuer_gid().get_urn()
619 # Ensure that the signer of the root credential is the target_authority
620 target_authority = hrn_to_urn(target_authority, 'authority')
622 if root_issuer != target_authority:
623 raise CredentialNotVerifiable("issuer (%s) != authority of target (%s)" \
624 % (root_issuer, target_authority))
627 # -- For Delegates (credentials with parents) verify that:
628 # . The privileges must be a subset of the parent credentials
629 # . The privileges must have "can_delegate" set for each delegated privilege
630 # . The target gid must be the same between child and parents
631 # . The expiry time on the child must be no later than the parent
632 # . The signer of the child must be the owner of the parent
634 def verify_parent(self, parent_cred):
635 # make sure the rights given to the child are a subset of the
636 # parents rights (and check delegate bits)
637 if not parent_cred.get_privileges().is_superset(self.get_privileges()):
638 raise ChildRightsNotSubsetOfParent(
639 self.parent.get_privileges().save_to_string() + " " +
640 self.get_privileges().save_to_string())
642 # make sure my target gid is the same as the parent's
643 if not parent_cred.get_gid_object().save_to_string() == \
644 self.get_gid_object().save_to_string():
645 raise CredentialNotVerifiable("target gid not equal between parent and child")
647 # make sure my expiry time is <= my parent's
648 if not parent_cred.get_lifetime() >= self.get_lifetime():
649 raise CredentialNotVerifiable("delegated credential expires after parent")
651 # make sure my signer is the parent's caller
652 if not parent_cred.get_gid_caller().save_to_string(False) == \
653 self.get_signature().get_issuer_gid().save_to_string(False):
654 raise CredentialNotVerifiable("delegated credential not signed by parent caller")
656 if parent_cred.parent:
657 parent_cred.verify_parent(parent_cred.parent)
660 # Dump the contents of a credential to stdout in human-readable format
662 # @param dump_parents If true, also dump the parent certificates
664 def dump(self, dump_parents=False):
665 print "CREDENTIAL", self.get_subject()
667 print " privs:", self.get_privileges().save_to_string()
670 gidCaller = self.get_gid_caller()
672 gidCaller.dump(8, dump_parents)
675 gidObject = self.get_gid_object()
677 gidObject.dump(8, dump_parents)
680 if self.parent and dump_parents:
682 self.parent.dump_parents()