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
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):
216 # set the GID of the caller
218 # @param gid GID object of the caller
220 def set_gid_caller(self, gid):
222 # gid origin caller is the caller's gid by default
223 self.gidOriginCaller = gid
226 # get the GID of the object
228 def get_gid_caller(self):
229 if not self.gidCaller:
231 return self.gidCaller
234 # set the GID of the object
236 # @param gid GID object of the object
238 def set_gid_object(self, gid):
242 # get the GID of the object
244 def get_gid_object(self):
245 if not self.gidObject:
247 return self.gidObject
250 # set the lifetime of this credential
252 # @param lifetime lifetime of credential
253 # . if lifeTime is a datetime object, it is used for the expiration time
254 # . if lifeTime is an integer value, it is considered the number of minutes
255 # remaining before expiration
257 def set_lifetime(self, lifeTime):
258 if isinstance(lifeTime, int):
259 self.expiration = datetime.timedelta(seconds=lifeTime*60) + datetime.datetime.utcnow()
261 self.expiration = lifeTime
264 # get the lifetime of the credential (in minutes)
266 def get_lifetime(self):
267 if not self.lifeTime:
269 return self.expiration
275 # @param privs either a comma-separated list of privileges of a RightList object
277 def set_privileges(self, privs):
278 if isinstance(privs, str):
279 self.privileges = RightList(string = privs)
281 self.privileges = privs
285 # return the privileges as a RightList object
287 def get_privileges(self):
288 if not self.privileges:
290 return self.privileges
293 # determine whether the credential allows a particular operation to be
296 # @param op_name string specifying name of operation ("lookup", "update", etc)
298 def can_perform(self, op_name):
299 rights = self.get_privileges()
304 return rights.can_perform(op_name)
306 def append_sub(self, doc, parent, element, text):
307 ele = doc.createElement(element)
308 ele.appendChild(doc.createTextNode(text))
309 parent.appendChild(ele)
312 # Encode the attributes of the credential into an XML string
313 # This should be done immediately before signing the credential.
318 # Create the XML document
320 signed_cred = doc.createElement("signed-credential")
321 doc.appendChild(signed_cred)
323 # Fill in the <credential> bit
324 cred = doc.createElement("credential")
325 cred.setAttribute("xml:id", self.get_refid())
326 signed_cred.appendChild(cred)
327 self.append_sub(doc, cred, "type", "privilege")
328 self.append_sub(doc, cred, "serial", "8")
329 self.append_sub(doc, cred, "owner_gid", self.gidCaller.save_to_string())
330 self.append_sub(doc, cred, "owner_urn", self.gidCaller.get_urn())
331 self.append_sub(doc, cred, "target_gid", self.gidObject.save_to_string())
332 self.append_sub(doc, cred, "target_urn", self.gidObject.get_urn())
333 self.append_sub(doc, cred, "uuid", "")
334 if not self.expiration:
335 self.set_lifetime(3600)
336 self.expiration = self.expiration.replace(microsecond=0)
337 self.append_sub(doc, cred, "expires", self.expiration.isoformat())
338 privileges = doc.createElement("privileges")
339 cred.appendChild(privileges)
342 rights = self.get_privileges()
343 for right in rights.rights:
344 priv = doc.createElement("privilege")
345 self.append_sub(doc, priv, "name", right.kind)
346 self.append_sub(doc, priv, "can_delegate", str(right.delegate))
347 privileges.appendChild(priv)
349 # Add the parent credential if it exists
351 sdoc = parseString(self.parent.get_xml())
352 p_cred = doc.importNode(sdoc.getElementsByTagName("credential")[0], True)
353 p = doc.createElement("parent")
354 p.appendChild(p_cred)
358 # Create the <signatures> tag
359 signatures = doc.createElement("signatures")
360 signed_cred.appendChild(signatures)
362 # Add any parent signatures
364 cur_cred = self.parent
366 sdoc = parseString(cur_cred.get_signature().get_xml())
367 ele = doc.importNode(sdoc.getElementsByTagName("Signature")[0], True)
368 signatures.appendChild(ele)
371 cur_cred = cur_cred.parent
375 # Get the finished product
376 self.xml = doc.toxml()
381 def save_to_random_tmp_file(self):
382 filename = "/tmp/cred_%d" % random.randint(0,999999999)
383 self.save_to_file(filename)
386 def save_to_file(self, filename, save_parents=True):
389 f = open(filename, "w")
393 def save_to_string(self, save_parents=True):
403 def set_refid(self, rid):
407 # Figure out what refids exist, and update this credential's id
408 # so that it doesn't clobber the others. Returns the refids of
411 def updateRefID(self):
413 self.set_refid('ref0')
418 next_cred = self.parent
420 refs.append(next_cred.get_refid())
422 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:
447 doc = parseString(self.get_xml())
448 sigs = doc.getElementsByTagName("signatures")[0]
450 # Create the signature template to be signed
451 signature = Signature()
452 signature.set_refid(self.get_refid())
453 sdoc = parseString(signature.get_xml())
454 sig_ele = doc.importNode(sdoc.getElementsByTagName("Signature")[0], True)
455 sigs.appendChild(sig_ele)
457 self.xml = doc.toxml()
459 # Call out to xmlsec1 to sign it
460 ref = 'Sig_%s' % self.get_refid()
461 filename = self.save_to_random_tmp_file()
462 signed = os.popen('/usr/bin/xmlsec1 --sign --node-id "%s" --privkey-pem %s,%s %s' \
463 % (ref, self.issuer_privkey, self.issuer_gid, filename)).read()
469 def getTextNode(self, element, subele):
470 sub = element.getElementsByTagName(subele)[0]
471 if len(sub.childNodes) > 0:
472 return sub.childNodes[0].nodeValue
477 # Retrieve the attributes of the credential from the XML.
478 # This is automatically caleld by the various get_* methods of
479 # this class and should not need to be called explicitly.
482 doc = parseString(self.xml)
484 signed_cred = doc.getElementsByTagName("signed-credential")
486 # Is this a signed-cred or just a cred?
487 if len(signed_cred) > 0:
488 cred = signed_cred[0].getElementsByTagName("credential")[0]
489 signatures = signed_cred[0].getElementsByTagName("signatures")
490 if len(signatures) > 0:
491 sigs = signatures[0].getElementsByTagName("Signature")
493 cred = doc.getElementsByTagName("credential")[0]
497 self.set_refid(cred.getAttribute("xml:id"))
498 sz_expires = getTextNode(cred, "expires")
500 self.expiration = datetime.datetime.strptime(sz_expires, '%Y-%m-%dT%H:%M:%S')
501 self.lifeTime = getTextNode(cred, "expires")
502 self.gidCaller = GID(string=getTextNode(cred, "owner_gid"))
503 self.gidObject = GID(string=getTextNode(cred, "target_gid"))
504 privs = cred.getElementsByTagName("privileges")[0]
507 for priv in privs.getElementsByTagName("privilege"):
508 sz_privs += getTextNode(priv, "name")
510 delegates.append(getTextNode(priv, "can_delegate"))
514 if "false" not in delegates:
517 # Make the rights list
518 sz_privs.rstrip(", ")
519 self.privileges = RightList(string=sz_privs)
523 parent = cred.getElementsByTagName("parent")
525 self.parent = Credential(string=getTextNode(cred, "parent"))
528 # Assign the signatures to the credentials
530 Sig = Signature(string=sig.toxml())
534 if cur_cred.get_refid() == Sig.get_refid():
535 cur_cred.set_signature(Sig)
538 cur_cred = cur_cred.parent
545 # . All of the signatures are valid and that the issuers trace back
546 # to trusted roots (performed by xmlsec1)
547 # . That the issuer of the credential is the authority in the target's urn
548 # . In the case of a delegated credential, this must be true of the root
549 # . That all of the gids presented in the credential are valid
551 # -- For Delegates (credentials with parents)
552 # . The privileges must be a subset of the parent credentials
553 # . The privileges must have "can_delegate" set for each delegated privilege
554 # . The target gid must be the same between child and parents
555 # . The expiry time on the child must be no later than the parent
556 # . The signer of the child must be the owner of the parent
558 # -- Verify does *NOT*
559 # . ensure that an xmlrpc client's gid matches a credential gid, that
560 # must be done elsewhere
562 # @param trusted_certs: The certificates of trusted CA certificates
564 def verify(self, trusted_certs):
568 # Verify the signatures
569 filename = self.save_to_random_tmp_file()
570 cert_args = " ".join(['--trusted-pem %s' % x for x in trusted_certs])
572 # Verify the gids of this cred and of its parents
573 trusted_cert_objects = [GID(filename=f) for f in trusted_certs]
577 cur_cred.get_gid_object().verify_chain(trusted_cert_objects)
578 cur_cred.get_gid_caller().verify_chain(trusted_cert_objects)
580 cur_cred = cur_cred.parent
585 refs.append("Sig_%s" % self.get_refid())
587 parentRefs = self.updateRefID()
588 for ref in parentRefs:
589 refs.append("Sig_%s" % ref)
592 verified = os.popen('/usr/bin/xmlsec1 --verify --node-id "%s" %s %s 2>&1' \
593 % (ref, cert_args, filename)).read()
594 if not verified.strip().startswith("OK"):
595 raise CredentialNotVerifiable("xmlsec1 error: " + verified)
599 # Verify the parents (delegation)
601 self.verify_parent(self.parent)
603 # Make sure the issuer is the target's authority
609 # Make sure the issuer of this credential is the target's authority
610 def verify_issuer(self):
611 target_authority = get_authority(self.get_gid_object().get_urn())
613 # Find the root credential's signature
618 cur_cred = cur_cred.parent
620 root_issuer = cur_cred.get_signature().get_issuer_gid().get_urn()
624 # Ensure that the signer of the root credential is the target_authority
625 target_authority = hrn_to_urn(target_authority, 'authority')
627 if root_issuer != target_authority:
628 raise CredentialNotVerifiable("issuer (%s) != authority of target (%s)" \
629 % (root_issuer, target_authority))
632 # -- For Delegates (credentials with parents) verify that:
633 # . The privileges must be a subset of the parent credentials
634 # . The privileges must have "can_delegate" set for each delegated privilege
635 # . The target gid must be the same between child and parents
636 # . The expiry time on the child must be no later than the parent
637 # . The signer of the child must be the owner of the parent
639 def verify_parent(self, parent_cred):
640 # make sure the rights given to the child are a subset of the
641 # parents rights (and check delegate bits)
642 if not parent_cred.get_privileges().is_superset(self.get_privileges()):
643 raise ChildRightsNotSubsetOfParent(
644 self.parent.get_privileges().save_to_string() + " " +
645 self.get_privileges().save_to_string())
647 # make sure my target gid is the same as the parent's
648 if not parent_cred.get_gid_object().save_to_string() == \
649 self.get_gid_object().save_to_string():
650 raise CredentialNotVerifiable("target gid not equal between parent and child")
652 # make sure my expiry time is <= my parent's
653 if not parent_cred.get_lifetime() >= self.get_lifetime():
654 raise CredentialNotVerifiable("delegated credential expires after parent")
656 # make sure my signer is the parent's caller
657 if not parent_cred.get_gid_caller().save_to_string(False) == \
658 self.get_signature().get_issuer_gid().save_to_string(False):
659 raise CredentialNotVerifiable("delegated credential not signed by parent caller")
661 if parent_cred.parent:
662 parent_cred.verify_parent(parent_cred.parent)
665 # Dump the contents of a credential to stdout in human-readable format
667 # @param dump_parents If true, also dump the parent certificates
669 def dump(self, dump_parents=False):
670 print "CREDENTIAL", self.get_subject()
672 print " privs:", self.get_privileges().save_to_string()
675 gidCaller = self.get_gid_caller()
677 gidCaller.dump(8, dump_parents)
680 gidObject = self.get_gid_object()
682 gidObject.dump(8, dump_parents)
685 if self.parent and dump_parents:
687 self.parent.dump_parents()