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
25 # . Need to implement full verification (parent signatures etc).
26 # . remove verify_chain
27 # . make delegation per privilege instead of global
28 # . make privs match between PG and PL
29 # . what about tickets? do they need to be redone to be like credentials?
30 # . Need to test delegation, xml verification
32 signature_template = \
34 <Signature xml:id="Sig_%s" xmlns="http://www.w3.org/2000/09/xmldsig#">
36 <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
37 <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
40 <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
42 <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
43 <DigestValue></DigestValue>
61 # Utility function to get the text of an XML element
63 def getTextNode(element, subele):
64 sub = element.getElementsByTagName(subele)[0]
65 if len(sub.childNodes) > 0:
66 return sub.childNodes[0].nodeValue
73 # Signature contains information about an xmlsec1 signature
74 # for a signed-credential
76 class Signature(object):
81 def __init__(self, string=None):
98 def set_refid(self, id):
101 def get_issuer_gid(self):
106 def set_issuer_gid(self, gid):
110 doc = parseString(self.xml)
111 sig = doc.getElementsByTagName("Signature")[0]
112 self.set_refid(sig.getAttribute("xml:id").strip("Sig_"))
113 keyinfo = sig.getElementsByTagName("X509Data")[0]
114 szgid = getTextNode(keyinfo, "X509Certificate")
115 szgid = "-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----" % szgid
116 self.set_issuer_gid(GID(string=szgid))
119 self.xml = signature_template % (self.get_refid(), self.get_refid())
123 # Credential is a tuple:
124 # (GIDCaller, GIDObject, Expiration (in UTC time), Privileges)
126 # These fields are encoded in one of two ways. The legacy style places
127 # it in the subjectAltName of an X509 certificate. The new credentials
128 # are placed in signed XML.
131 class Credential(object):
136 issuer_privkey = None
145 # Create a Credential object
147 # @param create If true, create a blank x509 certificate
148 # @param subject If subject!=None, create an x509 cert with the subject name
149 # @param string If string!=None, load the credential from the string
150 # @param filename If filename!=None, load the credential from the file
152 def __init__(self, create=False, subject=None, string=None, filename=None):
154 # Check if this is a legacy credential, translate it if so
155 if string or filename:
159 str = file(filename).read()
161 if str.strip().startswith("-----"):
162 self.translate_legacy(str)
168 # Translate a legacy credential into a new one
170 # @param String of the legacy credential
172 def translate_legacy(self, str):
173 legacy = CredentialLegacy(False,string=str)
174 self.gidCaller = legacy.get_gid_caller()
175 self.gidObject = legacy.get_gid_object()
176 lifetime = legacy.get_lifetime()
178 # Default to two years
179 self.set_lifetime(1051200)
181 self.set_lifetime(int(lifetime))
182 self.lifeTime = legacy.get_lifetime()
183 self.set_privileges(legacy.get_privileges())
184 self.get_privileges().delegate_all_privileges(legacy.get_delegate())
187 # Need the issuer's private key and name
188 # @param key Keypair object containing the private key of the issuer
189 # @param gid GID of the issuing authority
191 def set_issuer_keys(self, privkey, gid):
192 self.issuer_privkey = privkey
193 self.issuer_gid = gid
195 #def set_issuer(self, issuer):
198 #def set_subject(self, subject):
201 #def set_pubkey(self, pubkey):
202 # self.issuer_pubkey = pubkey
206 # Store the parent's credential in self.parent_xml
207 # Store the parent's signatures in self.signatures
208 # Update this credential's refid
209 def set_parent(self, cred):
213 doc = parseString(cred.xml)
214 signed = doc.getElementsByTagName("signed-credential")[0]
215 cred = signed.getElementsByTagName("credential")[0]
216 signatures = signed.getElementsByTagName("signatures")[0]
217 sigs = signatures.getElementsByTagName("Signature")
219 self.parent_xml = cred.toxml()
222 self.signatures.append(Signature(string=sig.toxml()))
228 # set the GID of the caller
230 # @param gid GID object of the caller
232 def set_gid_caller(self, gid):
234 # gid origin caller is the caller's gid by default
235 self.gidOriginCaller = gid
238 # get the GID of the object
240 def get_gid_caller(self):
241 if not self.gidCaller:
243 return self.gidCaller
246 # set the GID of the object
248 # @param gid GID object of the object
250 def set_gid_object(self, gid):
254 # get the GID of the object
256 def get_gid_object(self):
257 if not self.gidObject:
259 return self.gidObject
262 # set the lifetime of this credential
264 # @param lifetime lifetime of credential
265 # . if lifeTime is a datetime object, it is used for the expiration time
266 # . if lifeTime is an integer value, it is considered the number of minutes
267 # remaining before expiration
269 def set_lifetime(self, lifeTime):
270 if isinstance(lifeTime, int):
271 self.expiration = datetime.timedelta(seconds=lifeTime*60) + datetime.datetime.utcnow()
273 self.expiration = lifeTime
276 # get the lifetime of the credential (in minutes)
278 def get_lifetime(self):
279 if not self.lifeTime:
281 return self.expiration
287 # @param privs either a comma-separated list of privileges of a RightList object
289 def set_privileges(self, privs):
290 if isinstance(privs, str):
291 self.privileges = RightList(string = privs)
293 self.privileges = privs
297 # return the privileges as a RightList object
299 def get_privileges(self):
300 if not self.privileges:
302 return self.privileges
305 # determine whether the credential allows a particular operation to be
308 # @param op_name string specifying name of operation ("lookup", "update", etc)
310 def can_perform(self, op_name):
311 rights = self.get_privileges()
316 return rights.can_perform(op_name)
318 def append_sub(self, doc, parent, element, text):
319 ele = doc.createElement(element)
320 ele.appendChild(doc.createTextNode(text))
321 parent.appendChild(ele)
324 # Encode the attributes of the credential into an XML string
325 # This should be done immediately before signing the credential.
330 # Create the XML document
332 signed_cred = doc.createElement("signed-credential")
333 doc.appendChild(signed_cred)
335 # Fill in the <credential> bit
336 cred = doc.createElement("credential")
337 cred.setAttribute("xml:id", self.get_refid())
338 signed_cred.appendChild(cred)
339 self.append_sub(doc, cred, "type", "privilege")
340 self.append_sub(doc, cred, "serial", "8")
341 self.append_sub(doc, cred, "owner_gid", self.gidCaller.save_to_string())
342 self.append_sub(doc, cred, "owner_urn", self.gidCaller.get_urn())
343 self.append_sub(doc, cred, "target_gid", self.gidObject.save_to_string())
344 self.append_sub(doc, cred, "target_urn", self.gidObject.get_urn())
345 self.append_sub(doc, cred, "uuid", "")
346 if not self.expiration:
347 self.set_lifetime(3600)
348 self.expiration = self.expiration.replace(microsecond=0)
349 self.append_sub(doc, cred, "expires", self.expiration.isoformat())
350 privileges = doc.createElement("privileges")
351 cred.appendChild(privileges)
354 rights = self.get_privileges()
355 for right in rights.rights:
356 priv = doc.createElement("privilege")
357 self.append_sub(doc, priv, "name", right.kind)
358 self.append_sub(doc, priv, "can_delegate", str(right.delegate))
359 privileges.appendChild(priv)
361 # Add the parent credential if it exists
363 sdoc = parseString(self.parent_xml)
364 p_cred = doc.importNode(sdoc.getElementsByTagName("credential")[0], True)
365 p = doc.createElement("parent")
366 p.appendChild(p_cred)
370 # Create the <signatures> tag
371 signatures = doc.createElement("signatures")
372 signed_cred.appendChild(signatures)
374 # Add any parent signatures
376 for sig in self.signatures:
377 sdoc = parseString(sig.get_xml())
378 ele = doc.importNode(sdoc.getElementsByTagName("Signature")[0], True)
379 signatures.appendChild(ele)
381 # Get the finished product
382 self.xml = doc.toxml()
387 def save_to_random_tmp_file(self):
388 filename = "/tmp/cred_%d" % random.randint(0,999999999)
389 self.save_to_file(filename)
392 def save_to_file(self, filename, save_parents=True):
395 f = open(filename, "w")
399 def save_to_string(self, save_parents=True):
409 def set_refid(self, rid):
413 # Figure out what refids exist, and update this credential's id
414 # so that it doesn't clobber the others. Returns the refids of
417 def updateRefID(self):
418 if not self.parent_xml:
419 self.set_refid('ref0')
424 next_cred = Credential(string=self.parent_xml)
426 refs.append(next_cred.get_refid())
427 if next_cred.parent_xml:
428 next_cred = Credential(string=next_cred.parent_xml)
432 # Find a unique refid for this credential
433 rid = self.get_refid()
436 rid = "ref%d" % (val + 1)
441 # Return the set of parent credential ref ids
450 if not self.issuer_privkey or not self.issuer_gid:
453 doc = parseString(self.get_xml())
454 sigs = doc.getElementsByTagName("signatures")[0]
456 # Create the signature template to be signed
457 signature = Signature()
458 signature.set_refid(self.get_refid())
459 sdoc = parseString(signature.get_xml())
460 sig_ele = doc.importNode(sdoc.getElementsByTagName("Signature")[0], True)
461 sigs.appendChild(sig_ele)
463 self.xml = doc.toxml()
465 # Call out to xmlsec1 to sign it
466 ref = 'Sig_%s' % self.get_refid()
467 filename = self.save_to_random_tmp_file()
468 signed = os.popen('/usr/bin/xmlsec1 --sign --node-id "%s" --privkey-pem %s,%s %s' \
469 % (ref, self.issuer_privkey, self.issuer_gid, filename)).read()
475 def getTextNode(self, element, subele):
476 sub = element.getElementsByTagName(subele)[0]
477 if len(sub.childNodes) > 0:
478 return sub.childNodes[0].nodeValue
483 # Retrieve the attributes of the credential from the XML.
484 # This is automatically caleld by the various get_* methods of
485 # this class and should not need to be called explicitly.
488 doc = parseString(self.xml)
490 signed_cred = doc.getElementsByTagName("signed-credential")
492 # Is this a signed-cred or just a cred?
493 if len(signed_cred) > 0:
494 cred = signed_cred[0].getElementsByTagName("credential")[0]
495 signatures = signed_cred[0].getElementsByTagName("signatures")
496 if len(signatures) > 0:
497 sigs = signatures[0].getElementsByTagName("Signature")
499 cred = doc.getElementsByTagName("credential")[0]
503 self.set_refid(cred.getAttribute("xml:id"))
504 sz_expires = getTextNode(cred, "expires")
506 self.expiration = datetime.datetime.strptime(sz_expires, '%Y-%m-%dT%H:%M:%S')
507 self.lifeTime = getTextNode(cred, "expires")
508 self.gidCaller = GID(string=getTextNode(cred, "owner_gid"))
509 self.gidObject = GID(string=getTextNode(cred, "target_gid"))
510 privs = cred.getElementsByTagName("privileges")[0]
513 for priv in privs.getElementsByTagName("privilege"):
514 sz_privs += getTextNode(priv, "name")
516 delegates.append(getTextNode(priv, "can_delegate"))
520 if "false" not in delegates:
523 # Make the rights list
524 sz_privs.rstrip(", ")
525 self.privileges = RightList(string=sz_privs)
529 parent = cred.getElementsByTagName("parent")
531 self.parent_xml = getTextNode(cred, "parent")
536 self.signatures.append(Signature(string=sig.toxml()))
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 = Credential(string=self.parent_xml)
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(Credential(string=self.parent_xml))
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 refid
612 if cur_cred.parent_xml:
613 cur_cred = Credential(string=cur_cred.parent_xml)
615 root_refid = cur_cred.get_refid()
618 # Find the signature for the root credential
620 for sig in self.signatures:
621 if sig.get_refid().lower() == root_refid.lower():
622 root_issuer = sig.get_issuer_gid().get_urn()
625 # Ensure that the signer of the root credential is the target_authority
626 target_authority = hrn_to_urn(target_authority, 'authority')
628 if root_issuer != target_authority:
629 raise CredentialNotVerifiable("issuer (%s) != authority of target (%s)" \
630 % (root_issuer, target_authority))
633 # -- For Delegates (credentials with parents) verify that:
634 # . The privileges must be a subset of the parent credentials
635 # . The privileges must have "can_delegate" set for each delegated privilege
636 # . The target gid must be the same between child and parents
637 # . The expiry time on the child must be no later than the parent
638 # . The signer of the child must be the owner of the parent
640 def verify_parent(self, parent_cred):
641 # make sure the rights given to the child are a subset of the
642 # parents rights (and check delegate bits)
643 if not parent_cred.get_privileges().is_superset(self.get_privileges()):
644 raise ChildRightsNotSubsetOfParent(
645 self.parent.get_privileges().save_to_string() + " " +
646 self.get_privileges().save_to_string())
648 if parent_cred.parent_xml:
649 parent_cred.verify_parent(Credential(string=parent_cred.parent_xml))
652 # Dump the contents of a credential to stdout in human-readable format
654 # @param dump_parents If true, also dump the parent certificates
656 def dump(self, dump_parents=False):
657 print "CREDENTIAL", self.get_subject()
659 print " privs:", self.get_privileges().save_to_string()
662 gidCaller = self.get_gid_caller()
664 gidCaller.dump(8, dump_parents)
667 gidObject = self.get_gid_object()
669 gidObject.dump(8, dump_parents)
672 if self.parent_xml and dump_parents:
674 Credential(string=self.parent_xml).dump_parents()