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
37 signature_template = \
39 <Signature xml:id="Sig_%s" xmlns="http://www.w3.org/2000/09/xmldsig#">
41 <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
42 <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
45 <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
47 <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
48 <DigestValue></DigestValue>
66 # Credential is a tuple:
67 # (GIDCaller, GIDObject, Expiration (in UTC time), Privileges, DelegateBit)
69 # These fields are encoded in one of two ways. The legacy style places
70 # it in the subjectAltName of an X509 certificate. The new credentials
71 # are placed in signed XML.
74 class Credential(object):
89 # Create a Credential object
91 # @param create If true, create a blank x509 certificate
92 # @param subject If subject!=None, create an x509 cert with the subject name
93 # @param string If string!=None, load the credential from the string
94 # @param filename If filename!=None, load the credential from the file
96 def __init__(self, create=False, subject=None, string=None, filename=None):
98 # Check if this is a legacy credential, translate it if so
99 if string or filename:
103 str = file(filename).read()
105 if str.strip().startswith("-----"):
106 self.translate_legacy(str)
112 # Translate a legacy credential into a new one
114 # @param String of the legacy credential
116 def translate_legacy(self, str):
117 legacy = CredentialLegacy(False,string=str)
118 self.gidCaller = legacy.get_gid_caller()
119 self.gidObject = legacy.get_gid_object()
120 lifetime = legacy.get_lifetime()
122 self.set_lifetime(3600)
124 self.set_lifetime(int(lifetime))
125 self.lifeTime = legacy.get_lifetime()
126 self.set_privileges(legacy.get_privileges())
127 self.delegate = legacy.get_delegate()
130 # Need the issuer's private key and name
131 # @param key Keypair object containing the private key of the issuer
132 # @param gid GID of the issuing authority
134 def set_issuer_keys(self, privkey, gid):
135 self.issuer_privkey = privkey
136 self.issuer_gid = gid
138 #def set_issuer(self, issuer):
141 #def set_subject(self, subject):
144 #def set_pubkey(self, pubkey):
145 # self.issuer_pubkey = pubkey
149 # Store the parent's credential in self.parent_xml
150 # Store the parent's signatures in self.signatures
151 # Update this credential's refid
152 def set_parent(self, cred):
156 logger.info("Setting parent for %s to %s" % (self.gidCaller.get_urn(), cred.gidCaller.get_urn()))
157 doc = parseString(cred.xml)
158 signed = doc.getElementsByTagName("signed-credential")[0]
159 cred = signed.getElementsByTagName("credential")[0]
160 signatures = signed.getElementsByTagName("signatures")[0]
161 sigs = signatures.getElementsByTagName("Signature")
163 self.parent_xml = cred.toxml()
166 self.signatures.append(sig.toxml())
172 # set the GID of the caller
174 # @param gid GID object of the caller
176 def set_gid_caller(self, gid):
178 # gid origin caller is the caller's gid by default
179 self.gidOriginCaller = gid
182 # get the GID of the object
184 def get_gid_caller(self):
185 if not self.gidCaller:
187 return self.gidCaller
190 # set the GID of the object
192 # @param gid GID object of the object
194 def set_gid_object(self, gid):
198 # get the GID of the object
200 def get_gid_object(self):
201 if not self.gidObject:
203 return self.gidObject
206 # set the lifetime of this credential
208 # @param lifetime lifetime of credential
209 # . if lifeTime is a datetime object, it is used for the expiration time
210 # . if lifeTime is an integer value, it is considered the number of minutes
211 # remaining before expiration
213 def set_lifetime(self, lifeTime):
214 if isinstance(lifeTime, int):
215 self.expiration = datetime.timedelta(seconds=lifeTime*60) + datetime.datetime.utcnow()
217 self.expiration = lifeTime
220 # get the lifetime of the credential (in minutes)
222 def get_lifetime(self):
223 if not self.lifeTime:
225 return self.expiration
228 # set the delegate bit
230 # @param delegate boolean (True or False)
232 def set_delegate(self, delegate):
233 self.delegate = delegate
236 # get the delegate bit
238 def get_delegate(self):
239 if not self.delegate:
246 # @param privs either a comma-separated list of privileges of a RightList object
248 def set_privileges(self, privs):
249 if isinstance(privs, str):
250 self.privileges = RightList(string = privs)
252 self.privileges = privs
255 # return the privileges as a RightList object
257 def get_privileges(self):
258 if not self.privileges:
260 return self.privileges
263 # determine whether the credential allows a particular operation to be
266 # @param op_name string specifying name of operation ("lookup", "update", etc)
268 def can_perform(self, op_name):
269 rights = self.get_privileges()
274 return rights.can_perform(op_name)
276 def append_sub(self, doc, parent, element, text):
277 ele = doc.createElement(element)
278 ele.appendChild(doc.createTextNode(text))
279 parent.appendChild(ele)
282 # Encode the attributes of the credential into an XML string
283 # This should be done immediately before signing the credential.
288 # Create the XML document
290 signed_cred = doc.createElement("signed-credential")
291 doc.appendChild(signed_cred)
293 # Fill in the <credential> bit
294 cred = doc.createElement("credential")
295 cred.setAttribute("xml:id", self.get_refid())
296 signed_cred.appendChild(cred)
297 self.append_sub(doc, cred, "type", "privilege")
298 self.append_sub(doc, cred, "serial", "8")
299 self.append_sub(doc, cred, "owner_gid", self.gidCaller.save_to_string())
300 self.append_sub(doc, cred, "owner_urn", self.gidCaller.get_urn())
301 self.append_sub(doc, cred, "target_gid", self.gidObject.save_to_string())
302 self.append_sub(doc, cred, "target_urn", self.gidObject.get_urn())
303 self.append_sub(doc, cred, "uuid", "")
304 if not self.expiration:
305 self.set_lifetime(3600)
306 self.expiration = self.expiration.replace(microsecond=0)
307 self.append_sub(doc, cred, "expires", self.expiration.isoformat())
308 privileges = doc.createElement("privileges")
309 cred.appendChild(privileges)
312 rights = self.privileges.save_to_string().split(",")
314 priv = doc.createElement("privilege")
315 self.append_sub(doc, priv, "name", right.strip())
316 self.append_sub(doc, priv, "can_delegate", str(self.delegate))
317 privileges.appendChild(priv)
319 # Add the parent credential if it exists
321 sdoc = parseString(self.parent_xml)
322 p_cred = doc.importNode(sdoc.getElementsByTagName("credential")[0], True)
323 p = doc.createElement("parent")
324 p.appendChild(p_cred)
328 # Create the <signatures> tag
329 signatures = doc.createElement("signatures")
330 signed_cred.appendChild(signatures)
332 # Add any parent signatures
334 for sig in self.signatures:
335 sdoc = parseString(sig)
336 ele = doc.importNode(sdoc.getElementsByTagName("Signature")[0], True)
337 signatures.appendChild(ele)
339 # Get the finished product
340 self.xml = doc.toxml()
341 #print doc.toprettyxml()
345 def save_to_random_tmp_file(self):
346 filename = "/tmp/cred_%d" % random.randint(0,999999999)
347 self.save_to_file(filename)
350 def save_to_file(self, filename, save_parents=True):
353 f = open(filename, "w")
357 def save_to_string(self, save_parents=True):
367 def set_refid(self, rid):
371 # Figure out what refids exist, and update this credential's id
372 # so that it doesn't clobber the others. Returns the refids of
375 def updateRefID(self):
376 if not self.parent_xml:
377 self.set_refid('ref0')
382 next_xml = self.parent_xml
384 logger.info("instance--")
387 doc = parseString(next_xml)
388 cred = doc.getElementsByTagName("credential")[0]
389 refid = cred.getAttribute("xml:id")
390 logger.info("Found refid %s" % refid)
391 assert(refid not in refs)
394 parent = doc.getElementsByTagName("parent")
396 next_xml = parent[0].getElementsByTagName("credential")[0].toxml()
400 # Find a unique refid for this credential
401 rid = self.get_refid()
404 rid = "ref%d" % (val + 1)
409 # Return the set of parent credential ref ids
415 if not self.issuer_privkey or not self.issuer_gid:
421 doc = parseString(self.xml)
422 sigs = doc.getElementsByTagName("signatures")[0]
423 # Create the signature template
424 refid = self.get_refid()
425 sz_sig = signature_template % (refid,refid)
426 sdoc = parseString(sz_sig)
427 sig_ele = doc.importNode(sdoc.getElementsByTagName("Signature")[0], True)
428 sigs.appendChild(sig_ele)
430 self.xml = doc.toxml()
433 # Call out to xmlsec1 to sign it
434 ref = 'Sig_%s' % self.get_refid()
435 filename = self.save_to_random_tmp_file()
436 signed = os.popen('/usr/bin/xmlsec1 --sign --node-id "%s" --privkey-pem %s,%s %s' \
437 % (ref, self.issuer_privkey, self.issuer_gid, filename)).read()
443 def getTextNode(self, element, subele):
444 sub = element.getElementsByTagName(subele)[0]
445 if len(sub.childNodes) > 0:
446 return sub.childNodes[0].nodeValue
451 # Retrieve the attributes of the credential from the XML.
452 # This is automatically caleld by the various get_* methods of
453 # this class and should not need to be called explicitly.
456 doc = parseString(self.xml)
457 signed_cred = doc.getElementsByTagName("signed-credential")[0]
458 cred = signed_cred.getElementsByTagName("credential")[0]
459 signatures = signed_cred.getElementsByTagName("signatures")[0]
460 sigs = signatures.getElementsByTagName("Signature")
463 self.max_refid = int(cred.getAttribute("xml:id")[3:])
464 sz_expires = self.getTextNode(cred, "expires")
466 self.expiration = datetime.datetime.strptime(sz_expires, '%Y-%m-%dT%H:%M:%S')
467 self.lifeTime = self.getTextNode(cred, "expires")
468 self.gidCaller = GID(string=self.getTextNode(cred, "owner_gid"))
469 self.gidObject = GID(string=self.getTextNode(cred, "target_gid"))
470 privs = cred.getElementsByTagName("privileges")[0]
473 for priv in privs.getElementsByTagName("privilege"):
474 sz_privs += self.getTextNode(priv, "name")
476 delegates.append(self.getTextNode(priv, "can_delegate"))
480 if "false" not in delegates:
483 # Make the rights list
484 sz_privs.rstrip(", ")
485 self.privileges = RightList(string=sz_privs)
489 parent = cred.getElementsByTagName("parent")
491 self.parent_xml = self.getTextNode(cred, "parent")
496 self.signatures.append(sig.toxml())
499 # For a simple credential (no delegation) verify..
500 # . That the signature is valid for the credential's xml:id
501 # . That the signer's pub key matches the pub key of the target (object)
502 # . That the target/owner urns match those in the gids
504 # @param trusted_certs: The certificates of trusted CA certificates
506 def verify(self, trusted_certs):
510 # Verify the sigatures
511 filename = self.save_to_random_tmp_file()
512 cert_args = " ".join(['--trusted-pem %s' % x for x in trusted_certs])
514 ref = "Sig_%s" % self.get_refid()
515 verified = os.popen('/usr/bin/xmlsec1 --verify --node-id "%s" %s %s 2>&1' \
516 % (ref, cert_args, filename)).read()
518 if not verified.strip().startswith("OK"):
519 raise CredentialNotVerifiable("xmlsec1 error: " + verified)
524 # Verify that a chain of credentials is valid (see cert.py:verify). In
525 # addition to the checks for ordinary certificates, verification also
526 # ensures that the delegate bit was set by each parent in the chain. If
527 # a delegate bit was not set, then an exception is thrown.
529 # Each credential must be a subset of the rights of the parent.
531 def verify_chain(self, trusted_certs):
534 ## def verify_chain(self, trusted_certs = None):
535 ## # do the normal certificate verification stuff
536 ## Certificate.verify_chain(self, trusted_certs)
539 ## # make sure the parent delegated rights to the child
540 ## if not self.parent.get_delegate():
541 ## raise MissingDelegateBit(self.parent.get_subject())
543 ## # make sure the rights given to the child are a subset of the
545 ## if not self.parent.get_privileges().is_superset(self.get_privileges()):
546 ## raise ChildRightsNotSubsetOfParent(self.get_subject()
547 ## + " " + self.parent.get_privileges().save_to_string()
548 ## + " " + self.get_privileges().save_to_string())
553 # Dump the contents of a credential to stdout in human-readable format
555 # @param dump_parents If true, also dump the parent certificates
557 def dump(self, dump_parents=False):
558 print "CREDENTIAL", self.get_subject()
560 print " privs:", self.get_privileges().save_to_string()
563 gidCaller = self.get_gid_caller()
565 gidCaller.dump(8, dump_parents)
568 gidObject = self.get_gid_object()
570 gidObject.dump(8, dump_parents)
572 print " delegate:", self.get_delegate()
574 if self.parent_xml and dump_parents:
576 #self.parent.dump(dump_parents)