2 # Implements SFA Credentials
4 # Credentials are layered on top of certificates, and are essentially a
5 # certificate that stores a tuple of parameters.
16 #import xml.dom.minidom
17 from xml.dom.minidom import Document, parseString
18 from sfa.trust.credential_legacy import CredentialLegacy
19 from sfa.trust.certificate import Certificate
20 from sfa.trust.rights import *
21 from sfa.trust.gid import *
22 from sfa.util.faults import *
23 from sfa.util.sfalogging import logger
27 # . SFA is using set_parent to do chaining, but that's no longer necessary
28 # with the new credentials. fix.
29 # . This probably requires setting up some sort of CA hierarchy.
30 # . Make sure that the creds pass xml verification (probably need some reordering)
31 # . Need to implement full verification (parent signatures etc).
32 # . remove verify_chain
33 # . make delegation per privilege instead of global
34 # . make privs match between PG and PL
35 # . what about tickets? do they need to be redone to be like credentials?
38 signature_template = \
40 <Signature xml:id="Sig_%s" xmlns="http://www.w3.org/2000/09/xmldsig#">
42 <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
43 <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
46 <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
48 <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
49 <DigestValue></DigestValue>
67 #class Signature(object):
69 #class Signed_Credential(object):
73 # Credential is a tuple:
74 # (GIDCaller, GIDObject, Expiration (in UTC time), Privileges, DelegateBit)
76 # These fields are encoded in one of two ways. The legacy style places
77 # it in the subjectAltName of an X509 certificate. The new credentials
78 # are placed in signed XML.
81 class Credential(object):
96 # Create a Credential object
98 # @param create If true, create a blank x509 certificate
99 # @param subject If subject!=None, create an x509 cert with the subject name
100 # @param string If string!=None, load the credential from the string
101 # @param filename If filename!=None, load the credential from the file
103 def __init__(self, create=False, subject=None, string=None, filename=None):
105 # Check if this is a legacy credential, translate it if so
106 if string or filename:
110 str = file(filename).read()
112 if str.strip().startswith("-----"):
113 self.translate_legacy(str)
119 # Translate a legacy credential into a new one
121 # @param String of the legacy credential
123 def translate_legacy(self, str):
124 legacy = CredentialLegacy(False,string=str)
125 self.gidCaller = legacy.get_gid_caller()
126 self.gidObject = legacy.get_gid_object()
127 lifetime = legacy.get_lifetime()
129 self.set_lifetime(3600)
131 self.set_lifetime(int(lifetime))
132 self.lifeTime = legacy.get_lifetime()
133 self.set_privileges(legacy.get_privileges())
134 self.delegate = legacy.get_delegate()
137 # Need the issuer's private key and name
138 # @param key Keypair object containing the private key of the issuer
139 # @param gid GID of the issuing authority
141 def set_issuer_keys(self, privkey, gid):
142 self.issuer_privkey = privkey
143 self.issuer_gid = gid
145 #def set_issuer(self, issuer):
148 #def set_subject(self, subject):
151 #def set_pubkey(self, pubkey):
152 # self.issuer_pubkey = pubkey
156 # Store the parent's credential in self.parent_xml
157 # Store the parent's signatures in self.signatures
158 # Update this credential's refid
159 def set_parent(self, cred):
163 doc = parseString(cred.xml)
164 signed = doc.getElementsByTagName("signed-credential")[0]
165 cred = signed.getElementsByTagName("credential")[0]
166 signatures = signed.getElementsByTagName("signatures")[0]
167 sigs = signatures.getElementsByTagName("Signature")
169 self.parent_xml = cred.toxml()
172 self.signatures.append(sig.toxml())
178 # set the GID of the caller
180 # @param gid GID object of the caller
182 def set_gid_caller(self, gid):
184 # gid origin caller is the caller's gid by default
185 self.gidOriginCaller = gid
188 # get the GID of the object
190 def get_gid_caller(self):
191 if not self.gidCaller:
193 return self.gidCaller
196 # set the GID of the object
198 # @param gid GID object of the object
200 def set_gid_object(self, gid):
204 # get the GID of the object
206 def get_gid_object(self):
207 if not self.gidObject:
209 return self.gidObject
212 # set the lifetime of this credential
214 # @param lifetime lifetime of credential
215 # . if lifeTime is a datetime object, it is used for the expiration time
216 # . if lifeTime is an integer value, it is considered the number of minutes
217 # remaining before expiration
219 def set_lifetime(self, lifeTime):
220 if isinstance(lifeTime, int):
221 self.expiration = datetime.timedelta(seconds=lifeTime*60) + datetime.datetime.utcnow()
223 self.expiration = lifeTime
226 # get the lifetime of the credential (in minutes)
228 def get_lifetime(self):
229 if not self.lifeTime:
231 return self.expiration
234 # set the delegate bit
236 # @param delegate boolean (True or False)
238 def set_delegate(self, delegate):
239 self.delegate = delegate
242 # get the delegate bit
244 def get_delegate(self):
245 if not self.delegate:
252 # @param privs either a comma-separated list of privileges of a RightList object
254 def set_privileges(self, privs):
255 if isinstance(privs, str):
256 self.privileges = RightList(string = privs)
258 self.privileges = privs
261 # return the privileges as a RightList object
263 def get_privileges(self):
264 if not self.privileges:
266 return self.privileges
269 # determine whether the credential allows a particular operation to be
272 # @param op_name string specifying name of operation ("lookup", "update", etc)
274 def can_perform(self, op_name):
275 rights = self.get_privileges()
280 return rights.can_perform(op_name)
282 def append_sub(self, doc, parent, element, text):
283 ele = doc.createElement(element)
284 ele.appendChild(doc.createTextNode(text))
285 parent.appendChild(ele)
288 # Encode the attributes of the credential into an XML string
289 # This should be done immediately before signing the credential.
294 # Create the XML document
296 signed_cred = doc.createElement("signed-credential")
297 doc.appendChild(signed_cred)
299 # Fill in the <credential> bit
300 cred = doc.createElement("credential")
301 cred.setAttribute("xml:id", self.get_refid())
302 signed_cred.appendChild(cred)
303 self.append_sub(doc, cred, "type", "privilege")
304 self.append_sub(doc, cred, "serial", "8")
305 self.append_sub(doc, cred, "owner_gid", self.gidCaller.save_to_string())
306 self.append_sub(doc, cred, "owner_urn", self.gidCaller.get_urn())
307 self.append_sub(doc, cred, "target_gid", self.gidObject.save_to_string())
308 self.append_sub(doc, cred, "target_urn", self.gidObject.get_urn())
309 self.append_sub(doc, cred, "uuid", "")
310 if not self.expiration:
311 self.set_lifetime(3600)
312 self.expiration = self.expiration.replace(microsecond=0)
313 self.append_sub(doc, cred, "expires", self.expiration.isoformat())
314 privileges = doc.createElement("privileges")
315 cred.appendChild(privileges)
318 rights = self.privileges.save_to_string().split(",")
320 priv = doc.createElement("privilege")
321 self.append_sub(doc, priv, "name", right.strip())
322 self.append_sub(doc, priv, "can_delegate", str(self.delegate))
323 privileges.appendChild(priv)
325 # Add the parent credential if it exists
327 sdoc = parseString(self.parent_xml)
328 p_cred = doc.importNode(sdoc.getElementsByTagName("credential")[0], True)
329 p = doc.createElement("parent")
330 p.appendChild(p_cred)
334 # Create the <signatures> tag
335 signatures = doc.createElement("signatures")
336 signed_cred.appendChild(signatures)
338 # Add any parent signatures
340 for sig in self.signatures:
341 sdoc = parseString(sig)
342 ele = doc.importNode(sdoc.getElementsByTagName("Signature")[0], True)
343 signatures.appendChild(ele)
345 # Get the finished product
346 self.xml = doc.toxml()
351 def save_to_random_tmp_file(self):
352 filename = "/tmp/cred_%d" % random.randint(0,999999999)
353 self.save_to_file(filename)
356 def save_to_file(self, filename, save_parents=True):
359 f = open(filename, "w")
363 def save_to_string(self, save_parents=True):
373 def set_refid(self, rid):
377 # Figure out what refids exist, and update this credential's id
378 # so that it doesn't clobber the others. Returns the refids of
381 def updateRefID(self):
382 if not self.parent_xml:
383 self.set_refid('ref0')
388 next_cred = Credential(string=self.parent_xml)
390 refs.append(next_cred.get_refid())
391 if next_cred.parent_xml:
392 next_cred = Credential(string=next_cred.parent_xml)
396 # Find a unique refid for this credential
397 rid = self.get_refid()
400 rid = "ref%d" % (val + 1)
405 # Return the set of parent credential ref ids
411 if not self.issuer_privkey or not self.issuer_gid:
417 doc = parseString(self.xml)
418 sigs = doc.getElementsByTagName("signatures")[0]
419 # Create the signature template
420 refid = self.get_refid()
421 sz_sig = signature_template % (refid,refid)
422 sdoc = parseString(sz_sig)
423 sig_ele = doc.importNode(sdoc.getElementsByTagName("Signature")[0], True)
424 sigs.appendChild(sig_ele)
426 self.xml = doc.toxml()
429 # Call out to xmlsec1 to sign it
430 ref = 'Sig_%s' % self.get_refid()
431 filename = self.save_to_random_tmp_file()
432 signed = os.popen('/usr/bin/xmlsec1 --sign --node-id "%s" --privkey-pem %s,%s %s' \
433 % (ref, self.issuer_privkey, self.issuer_gid, filename)).read()
439 def getTextNode(self, element, subele):
440 sub = element.getElementsByTagName(subele)[0]
441 if len(sub.childNodes) > 0:
442 return sub.childNodes[0].nodeValue
447 # Retrieve the attributes of the credential from the XML.
448 # This is automatically caleld by the various get_* methods of
449 # this class and should not need to be called explicitly.
452 doc = parseString(self.xml)
454 signed_cred = doc.getElementsByTagName("signed-credential")
456 # Is this a signed-cred or just a cred?
457 if len(signed_cred) > 0:
458 cred = signed_cred[0].getElementsByTagName("credential")[0]
459 signatures = signed_cred[0].getElementsByTagName("signatures")
460 if len(signatures) > 0:
461 sigs = signatures[0].getElementsByTagName("Signature")
463 cred = doc.getElementsByTagName("credential")[0]
467 self.set_refid(cred.getAttribute("xml:id"))
468 sz_expires = self.getTextNode(cred, "expires")
470 self.expiration = datetime.datetime.strptime(sz_expires, '%Y-%m-%dT%H:%M:%S')
471 self.lifeTime = self.getTextNode(cred, "expires")
472 self.gidCaller = GID(string=self.getTextNode(cred, "owner_gid"))
473 self.gidObject = GID(string=self.getTextNode(cred, "target_gid"))
474 privs = cred.getElementsByTagName("privileges")[0]
477 for priv in privs.getElementsByTagName("privilege"):
478 sz_privs += self.getTextNode(priv, "name")
480 delegates.append(self.getTextNode(priv, "can_delegate"))
484 if "false" not in delegates:
487 # Make the rights list
488 sz_privs.rstrip(", ")
489 self.privileges = RightList(string=sz_privs)
493 parent = cred.getElementsByTagName("parent")
495 self.parent_xml = self.getTextNode(cred, "parent")
500 self.signatures.append(sig.toxml())
504 # . All of the signatures are valid and that the issuers trace back
505 # to trusted roots (performed by xmlsec1)
506 # . That the issuer of the credential is the authority in the target's urn
507 # . In the case of a delegated credential, this must be true of the root
509 # -- For Delegates (credentials with parents)
510 # . The privileges must be a subset of the parent credentials
511 # . The privileges must have "can_delegate" set for each delegated privilege
512 # . The target gid must be the same between child and parents
513 # . The expiry time on the child must be no later than the parent
514 # . The signer of the child must be the owner of the parent
516 # -- Verify does *NOT*
517 # . ensure that an xmlrpc client's gid matches a credential gid, that
518 # must be done elsewhere
520 # @param trusted_certs: The certificates of trusted CA certificates
522 def verify(self, trusted_certs):
523 logger.info("verifying cert")
527 # Verify the signatures
528 filename = self.save_to_random_tmp_file()
529 cert_args = " ".join(['--trusted-pem %s' % x for x in trusted_certs])
533 refs.append("Sig_%s" % self.get_refid())
535 parentRefs = self.updateRefID()
536 for ref in parentRefs:
537 refs.append("Sig_%s" % ref)
540 logger.info('/usr/bin/xmlsec1 --verify --node-id "%s" %s %s 2>&1' \
541 % (ref, cert_args, filename))
542 verified = os.popen('/usr/bin/xmlsec1 --verify --node-id "%s" %s %s 2>&1' \
543 % (ref, cert_args, filename)).read()
544 if not verified.strip().startswith("OK"):
545 raise CredentialNotVerifiable("xmlsec1 error: " + verified)
549 # Verify the parents (delegation)
551 # self.verify_parent(Credential(string=self.parent_xml))
553 # Make sure the issuer is the target's authority
559 # Make sure the issuer of this credential is the target's authority
560 def verify_issuer(self):
561 target_authority = get_authority(self.get_gid_object().get_hrn())
563 # Find the root credential's refid
567 if cur_cred.parent_xml:
568 cur_cred = Credential(string=cur_cred.parent_xml)
570 root_refid = "Sig_%s" % cur_cred.get_refid()
573 # Find the signature for the root credential
575 for sig in self.signatures:
576 doc = parseString(sig)
577 esig = doc.getElementsByTagName("Signature")[0]
578 ref = esig.getAttribute("xml:id")
579 if ref.lower() == root_refid.lower():
580 # Found the right signature, look for the issuer
581 keyinfo = esig.getElementsByTagName("X509Data")[0]
582 root_issuer = self.getTextNode(keyinfo, "X509SubjectName")
583 root_issuer = root_issuer.strip('CN=')
585 # Ensure that the signer of the root credential is the target_authority
586 root_issuer = hrn_to_urn(root_issuer, 'authority')
587 target_authority = hrn_to_urn(target_authority, 'authority')
589 if root_issuer != target_authority:
590 raise CredentialNotVerifiable("issuer (%s) != authority of target (%s)" \
591 % (root_issuer, target_authority))
594 def verify_parent(self, parent_cred):
595 if parent_cred.parent_xml:
596 parent_cred.verify_parent(Credential(string=parent_cred.parent_xml))
599 # Verify that a chain of credentials is valid (see cert.py:verify). In
600 # addition to the checks for ordinary certificates, verification also
601 # ensures that the delegate bit was set by each parent in the chain. If
602 # a delegate bit was not set, then an exception is thrown.
604 # Each credential must be a subset of the rights of the parent.
606 def verify_chain(self, trusted_certs):
609 ## def verify_chain(self, trusted_certs = None):
610 ## # do the normal certificate verification stuff
611 ## Certificate.verify_chain(self, trusted_certs)
614 ## # make sure the parent delegated rights to the child
615 ## if not self.parent.get_delegate():
616 ## raise MissingDelegateBit(self.parent.get_subject())
618 ## # make sure the rights given to the child are a subset of the
620 ## if not self.parent.get_privileges().is_superset(self.get_privileges()):
621 ## raise ChildRightsNotSubsetOfParent(self.get_subject()
622 ## + " " + self.parent.get_privileges().save_to_string()
623 ## + " " + self.get_privileges().save_to_string())
628 # Dump the contents of a credential to stdout in human-readable format
630 # @param dump_parents If true, also dump the parent certificates
632 def dump(self, dump_parents=False):
633 print "CREDENTIAL", self.get_subject()
635 print " privs:", self.get_privileges().save_to_string()
638 gidCaller = self.get_gid_caller()
640 gidCaller.dump(8, dump_parents)
643 gidObject = self.get_gid_object()
645 gidObject.dump(8, dump_parents)
647 print " delegate:", self.get_delegate()
649 if self.parent_xml and dump_parents:
651 #self.parent.dump(dump_parents)