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 self.set_lifetime(3600)
180 self.set_lifetime(int(lifetime))
181 self.lifeTime = legacy.get_lifetime()
182 self.set_privileges(legacy.get_privileges())
183 self.get_privileges().delegate_all_privileges(legacy.get_delegate())
186 # Need the issuer's private key and name
187 # @param key Keypair object containing the private key of the issuer
188 # @param gid GID of the issuing authority
190 def set_issuer_keys(self, privkey, gid):
191 self.issuer_privkey = privkey
192 self.issuer_gid = gid
194 #def set_issuer(self, issuer):
197 #def set_subject(self, subject):
200 #def set_pubkey(self, pubkey):
201 # self.issuer_pubkey = pubkey
205 # Store the parent's credential in self.parent_xml
206 # Store the parent's signatures in self.signatures
207 # Update this credential's refid
208 def set_parent(self, cred):
212 doc = parseString(cred.xml)
213 signed = doc.getElementsByTagName("signed-credential")[0]
214 cred = signed.getElementsByTagName("credential")[0]
215 signatures = signed.getElementsByTagName("signatures")[0]
216 sigs = signatures.getElementsByTagName("Signature")
218 self.parent_xml = cred.toxml()
221 self.signatures.append(Signature(string=sig.toxml()))
227 # set the GID of the caller
229 # @param gid GID object of the caller
231 def set_gid_caller(self, gid):
233 # gid origin caller is the caller's gid by default
234 self.gidOriginCaller = gid
237 # get the GID of the object
239 def get_gid_caller(self):
240 if not self.gidCaller:
242 return self.gidCaller
245 # set the GID of the object
247 # @param gid GID object of the object
249 def set_gid_object(self, gid):
253 # get the GID of the object
255 def get_gid_object(self):
256 if not self.gidObject:
258 return self.gidObject
261 # set the lifetime of this credential
263 # @param lifetime lifetime of credential
264 # . if lifeTime is a datetime object, it is used for the expiration time
265 # . if lifeTime is an integer value, it is considered the number of minutes
266 # remaining before expiration
268 def set_lifetime(self, lifeTime):
269 if isinstance(lifeTime, int):
270 self.expiration = datetime.timedelta(seconds=lifeTime*60) + datetime.datetime.utcnow()
272 self.expiration = lifeTime
275 # get the lifetime of the credential (in minutes)
277 def get_lifetime(self):
278 if not self.lifeTime:
280 return self.expiration
286 # @param privs either a comma-separated list of privileges of a RightList object
288 def set_privileges(self, privs):
289 if isinstance(privs, str):
290 self.privileges = RightList(string = privs)
292 self.privileges = privs
296 # return the privileges as a RightList object
298 def get_privileges(self):
299 if not self.privileges:
301 return self.privileges
304 # determine whether the credential allows a particular operation to be
307 # @param op_name string specifying name of operation ("lookup", "update", etc)
309 def can_perform(self, op_name):
310 rights = self.get_privileges()
315 return rights.can_perform(op_name)
317 def append_sub(self, doc, parent, element, text):
318 ele = doc.createElement(element)
319 ele.appendChild(doc.createTextNode(text))
320 parent.appendChild(ele)
323 # Encode the attributes of the credential into an XML string
324 # This should be done immediately before signing the credential.
329 # Create the XML document
331 signed_cred = doc.createElement("signed-credential")
332 doc.appendChild(signed_cred)
334 # Fill in the <credential> bit
335 cred = doc.createElement("credential")
336 cred.setAttribute("xml:id", self.get_refid())
337 signed_cred.appendChild(cred)
338 self.append_sub(doc, cred, "type", "privilege")
339 self.append_sub(doc, cred, "serial", "8")
340 self.append_sub(doc, cred, "owner_gid", self.gidCaller.save_to_string())
341 self.append_sub(doc, cred, "owner_urn", self.gidCaller.get_urn())
342 self.append_sub(doc, cred, "target_gid", self.gidObject.save_to_string())
343 self.append_sub(doc, cred, "target_urn", self.gidObject.get_urn())
344 self.append_sub(doc, cred, "uuid", "")
345 if not self.expiration:
346 self.set_lifetime(3600)
347 self.expiration = self.expiration.replace(microsecond=0)
348 self.append_sub(doc, cred, "expires", self.expiration.isoformat())
349 privileges = doc.createElement("privileges")
350 cred.appendChild(privileges)
353 rights = self.get_privileges()
354 for right in rights.rights:
355 priv = doc.createElement("privilege")
356 self.append_sub(doc, priv, "name", right.kind)
357 self.append_sub(doc, priv, "can_delegate", str(right.delegate))
358 privileges.appendChild(priv)
360 # Add the parent credential if it exists
362 sdoc = parseString(self.parent_xml)
363 p_cred = doc.importNode(sdoc.getElementsByTagName("credential")[0], True)
364 p = doc.createElement("parent")
365 p.appendChild(p_cred)
369 # Create the <signatures> tag
370 signatures = doc.createElement("signatures")
371 signed_cred.appendChild(signatures)
373 # Add any parent signatures
375 for sig in self.signatures:
376 sdoc = parseString(sig.get_xml())
377 ele = doc.importNode(sdoc.getElementsByTagName("Signature")[0], True)
378 signatures.appendChild(ele)
380 # Get the finished product
381 self.xml = doc.toxml()
386 def save_to_random_tmp_file(self):
387 filename = "/tmp/cred_%d" % random.randint(0,999999999)
388 self.save_to_file(filename)
391 def save_to_file(self, filename, save_parents=True):
394 f = open(filename, "w")
398 def save_to_string(self, save_parents=True):
408 def set_refid(self, rid):
412 # Figure out what refids exist, and update this credential's id
413 # so that it doesn't clobber the others. Returns the refids of
416 def updateRefID(self):
417 if not self.parent_xml:
418 self.set_refid('ref0')
423 next_cred = Credential(string=self.parent_xml)
425 refs.append(next_cred.get_refid())
426 if next_cred.parent_xml:
427 next_cred = Credential(string=next_cred.parent_xml)
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:
452 doc = parseString(self.get_xml())
453 sigs = doc.getElementsByTagName("signatures")[0]
455 # Create the signature template to be signed
456 signature = Signature()
457 signature.set_refid(self.get_refid())
458 sdoc = parseString(signature.get_xml())
459 sig_ele = doc.importNode(sdoc.getElementsByTagName("Signature")[0], True)
460 sigs.appendChild(sig_ele)
462 self.xml = doc.toxml()
464 # Call out to xmlsec1 to sign it
465 ref = 'Sig_%s' % self.get_refid()
466 filename = self.save_to_random_tmp_file()
467 signed = os.popen('/usr/bin/xmlsec1 --sign --node-id "%s" --privkey-pem %s,%s %s' \
468 % (ref, self.issuer_privkey, self.issuer_gid, filename)).read()
474 def getTextNode(self, element, subele):
475 sub = element.getElementsByTagName(subele)[0]
476 if len(sub.childNodes) > 0:
477 return sub.childNodes[0].nodeValue
482 # Retrieve the attributes of the credential from the XML.
483 # This is automatically caleld by the various get_* methods of
484 # this class and should not need to be called explicitly.
487 doc = parseString(self.xml)
489 signed_cred = doc.getElementsByTagName("signed-credential")
491 # Is this a signed-cred or just a cred?
492 if len(signed_cred) > 0:
493 cred = signed_cred[0].getElementsByTagName("credential")[0]
494 signatures = signed_cred[0].getElementsByTagName("signatures")
495 if len(signatures) > 0:
496 sigs = signatures[0].getElementsByTagName("Signature")
498 cred = doc.getElementsByTagName("credential")[0]
502 self.set_refid(cred.getAttribute("xml:id"))
503 sz_expires = getTextNode(cred, "expires")
505 self.expiration = datetime.datetime.strptime(sz_expires, '%Y-%m-%dT%H:%M:%S')
506 self.lifeTime = getTextNode(cred, "expires")
507 self.gidCaller = GID(string=getTextNode(cred, "owner_gid"))
508 self.gidObject = GID(string=getTextNode(cred, "target_gid"))
509 privs = cred.getElementsByTagName("privileges")[0]
512 for priv in privs.getElementsByTagName("privilege"):
513 sz_privs += getTextNode(priv, "name")
515 delegates.append(getTextNode(priv, "can_delegate"))
519 if "false" not in delegates:
522 # Make the rights list
523 sz_privs.rstrip(", ")
524 self.privileges = RightList(string=sz_privs)
528 parent = cred.getElementsByTagName("parent")
530 self.parent_xml = getTextNode(cred, "parent")
535 self.signatures.append(Signature(string=sig.toxml()))
539 # . All of the signatures are valid and that the issuers trace back
540 # to trusted roots (performed by xmlsec1)
541 # . That the issuer of the credential is the authority in the target's urn
542 # . In the case of a delegated credential, this must be true of the root
544 # -- For Delegates (credentials with parents)
545 # . The privileges must be a subset of the parent credentials
546 # . The privileges must have "can_delegate" set for each delegated privilege
547 # . The target gid must be the same between child and parents
548 # . The expiry time on the child must be no later than the parent
549 # . The signer of the child must be the owner of the parent
551 # -- Verify does *NOT*
552 # . ensure that an xmlrpc client's gid matches a credential gid, that
553 # must be done elsewhere
555 # @param trusted_certs: The certificates of trusted CA certificates
557 def verify(self, trusted_certs):
561 # Verify the signatures
562 filename = self.save_to_random_tmp_file()
563 cert_args = " ".join(['--trusted-pem %s' % x for x in trusted_certs])
567 refs.append("Sig_%s" % self.get_refid())
569 parentRefs = self.updateRefID()
570 for ref in parentRefs:
571 refs.append("Sig_%s" % ref)
574 verified = os.popen('/usr/bin/xmlsec1 --verify --node-id "%s" %s %s 2>&1' \
575 % (ref, cert_args, filename)).read()
576 if not verified.strip().startswith("OK"):
577 raise CredentialNotVerifiable("xmlsec1 error: " + verified)
581 # Verify the parents (delegation)
583 self.verify_parent(Credential(string=self.parent_xml))
585 # Make sure the issuer is the target's authority
591 # Make sure the issuer of this credential is the target's authority
592 # Security hole: Because PL GID's use hrns in the CN instead of urns,
593 # the type is not checked, only the authority name.
594 def verify_issuer(self):
595 target_authority = get_authority(self.get_gid_object().get_hrn())
597 # Find the root credential's refid
601 if cur_cred.parent_xml:
602 cur_cred = Credential(string=cur_cred.parent_xml)
604 root_refid = cur_cred.get_refid()
607 # Find the signature for the root credential
609 for sig in self.signatures:
610 if sig.get_refid().lower() == root_refid.lower():
611 root_issuer = sig.get_issuer_gid().get_urn()
613 # Ensure that the signer of the root credential is the target_authority
614 target_authority = hrn_to_urn(target_authority, 'authority')
616 if root_issuer != target_authority:
617 raise CredentialNotVerifiable("issuer (%s) != authority of target (%s)" \
618 % (root_issuer, target_authority))
621 # -- For Delegates (credentials with parents) verify that:
622 # . The privileges must be a subset of the parent credentials
623 # . The privileges must have "can_delegate" set for each delegated privilege
624 # . The target gid must be the same between child and parents
625 # . The expiry time on the child must be no later than the parent
626 # . The signer of the child must be the owner of the parent
628 def verify_parent(self, parent_cred):
629 # make sure the rights given to the child are a subset of the
630 # parents rights (and check delegate bits)
631 if not parent_cred.get_privileges().is_superset(self.get_privileges()):
632 raise ChildRightsNotSubsetOfParent(
633 self.parent.get_privileges().save_to_string() + " " +
634 self.get_privileges().save_to_string())
636 if parent_cred.parent_xml:
637 parent_cred.verify_parent(Credential(string=parent_cred.parent_xml))
640 # Verify that a chain of credentials is valid (see cert.py:verify). In
641 # addition to the checks for ordinary certificates, verification also
642 # ensures that the delegate bit was set by each parent in the chain. If
643 # a delegate bit was not set, then an exception is thrown.
645 # Each credential must be a subset of the rights of the parent.
647 ## def verify_chain(self, trusted_certs = None):
648 ## # do the normal certificate verification stuff
649 ## Certificate.verify_chain(self, trusted_certs)
652 ## # make sure the parent delegated rights to the child
653 ## if not self.parent.get_delegate():
654 ## raise MissingDelegateBit(self.parent.get_subject())
656 ## # make sure the rights given to the child are a subset of the
658 ## if not self.parent.get_privileges().is_superset(self.get_privileges()):
659 ## raise ChildRightsNotSubsetOfParent(self.get_subject()
660 ## + " " + self.parent.get_privileges().save_to_string()
661 ## + " " + self.get_privileges().save_to_string())
666 # Dump the contents of a credential to stdout in human-readable format
668 # @param dump_parents If true, also dump the parent certificates
670 def dump(self, dump_parents=False):
671 print "CREDENTIAL", self.get_subject()
673 print " privs:", self.get_privileges().save_to_string()
676 gidCaller = self.get_gid_caller()
678 gidCaller.dump(8, dump_parents)
681 gidObject = self.get_gid_object()
683 gidObject.dump(8, dump_parents)
685 print " delegate:", self.get_delegate()
687 if self.parent_xml and dump_parents:
689 #self.parent.dump(dump_parents)