improved error and log messages
[sfa.git] / sfa / trust / credential.py
index 6518bf8..f112a95 100644 (file)
 # Credentials are signed XML files that assign a subject gid privileges to an object gid\r
 ##\r
 \r
-### $Id$\r
-### $URL$\r
-\r
 import os\r
+from types import StringTypes\r
 import datetime\r
+from StringIO import StringIO\r
 from tempfile import mkstemp\r
 from xml.dom.minidom import Document, parseString\r
-from lxml import etree\r
-from dateutil.parser import parse\r
-from StringIO import StringIO\r
+\r
+HAVELXML = False\r
+try:\r
+    from lxml import etree\r
+    HAVELXML = True\r
+except:\r
+    pass\r
 \r
 from sfa.util.faults import *\r
 from sfa.util.sfalogging import logger\r
+from sfa.util.sfatime import utcparse\r
 from sfa.trust.certificate import Keypair\r
 from sfa.trust.credential_legacy import CredentialLegacy\r
-from sfa.trust.rights import Right, Rights\r
+from sfa.trust.rights import Right, Rights, determine_rights\r
 from sfa.trust.gid import GID\r
-from sfa.util.namespace import *\r
+from sfa.util.xrn import urn_to_hrn, hrn_authfor_hrn\r
 \r
 # 2 weeks, in seconds \r
 DEFAULT_CREDENTIAL_LIFETIME = 86400 * 14\r
@@ -265,7 +269,16 @@ class Credential(object):
     def get_subject(self):\r
         if not self.gidObject:\r
             self.decode()\r
-        return self.gidObject.get_subject()   \r
+        return self.gidObject.get_printable_subject()\r
+\r
+    def get_summary_tostring(self):\r
+        if not self.gidObject:\r
+            self.decode()\r
+        obj = self.gidObject.get_printable_subject()\r
+        caller = self.gidCaller.get_printable_subject()\r
+        exp = self.get_expiration()\r
+        # Summarize the rights too? The issuer?\r
+        return "[ Grant %s rights on %s until %s ]" % (caller, obj, exp)\r
 \r
     def get_signature(self):\r
         if not self.signature:\r
@@ -347,21 +360,26 @@ class Credential(object):
 \r
             \r
     ##\r
-    # Expiration: an absolute UTC time of expiration (as either an int or datetime)\r
+    # Expiration: an absolute UTC time of expiration (as either an int or string or datetime)\r
     # \r
     def set_expiration(self, expiration):\r
-        if isinstance(expiration, int):\r
+        if isinstance(expiration, (int, float)):\r
             self.expiration = datetime.datetime.fromtimestamp(expiration)\r
-        else:\r
+        elif isinstance (expiration, datetime.datetime):\r
             self.expiration = expiration\r
-            \r
+        elif isinstance (expiration, StringTypes):\r
+            self.expiration = utcparse (expiration)\r
+        else:\r
+            logger.error ("unexpected input type in Credential.set_expiration")\r
+\r
 \r
     ##\r
-    # get the lifetime of the credential (in datetime format)\r
+    # get the lifetime of the credential (always in datetime format)\r
 \r
     def get_expiration(self):\r
         if not self.expiration:\r
             self.decode()\r
+        # at this point self.expiration is normalized as a datetime - DON'T call utcparse again\r
         return self.expiration\r
 \r
     ##\r
@@ -417,12 +435,18 @@ class Credential(object):
         doc = Document()\r
         signed_cred = doc.createElement("signed-credential")\r
 \r
-# PG adds these. It would be nice to be consistent.\r
-# But it's kind of odd for PL to use PG schemas that talk\r
-# about tickets, and the PG CM policies.\r
-# Note the careful addition of attributes from the parent below...\r
-#        signed_cred.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")\r
-#        signed_cred.setAttribute("xsinoNamespaceSchemaLocation", "http://www.protogeni.net/resources/credential/credential.xsd")\r
+# Declare namespaces\r
+# Note that credential/policy.xsd are really the PG schemas\r
+# in a PL namespace.\r
+# Note that delegation of credentials between the 2 only really works\r
+# cause those schemas are identical.\r
+# Also note these PG schemas talk about PG tickets and CM policies.\r
+        signed_cred.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")\r
+        signed_cred.setAttribute("xsi:noNamespaceSchemaLocation", "http://www.planet-lab.org/resources/sfa/credential.xsd")\r
+        signed_cred.setAttribute("xsi:schemaLocation", "http://www.planet-lab.org/resources/sfa/ext/policy/1 http://www.planet-lab.org/resources/sfa/ext/policy/1/policy.xsd")\r
+\r
+# PG says for those last 2:\r
+#        signed_cred.setAttribute("xsi:noNamespaceSchemaLocation", "http://www.protogeni.net/resources/credential/credential.xsd")\r
 #        signed_cred.setAttribute("xsi:schemaLocation", "http://www.protogeni.net/resources/credential/ext/policy/1 http://www.protogeni.net/resources/credential/ext/policy/1/policy.xsd")\r
 \r
         doc.appendChild(signed_cred)  \r
@@ -459,13 +483,34 @@ class Credential(object):
             # If the root node is a signed-credential (it should be), then\r
             # get all its attributes and attach those to our signed_cred\r
             # node.\r
-            # Specifically, PG adds attributes for namespaces (which is reasonable),\r
+            # Specifically, PG and PLadd attributes for namespaces (which is reasonable),\r
             # and we need to include those again here or else their signature\r
             # no longer matches on the credential.\r
             # We expect three of these, but here we copy them all:\r
 #        signed_cred.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")\r
-#        signed_cred.setAttribute("xsinoNamespaceSchemaLocation", "http://www.protogeni.net/resources/credential/credential.xsd")\r
+# and from PG (PL is equivalent, as shown above):\r
+#        signed_cred.setAttribute("xsi:noNamespaceSchemaLocation", "http://www.protogeni.net/resources/credential/credential.xsd")\r
 #        signed_cred.setAttribute("xsi:schemaLocation", "http://www.protogeni.net/resources/credential/ext/policy/1 http://www.protogeni.net/resources/credential/ext/policy/1/policy.xsd")\r
+\r
+            # HOWEVER!\r
+            # PL now also declares these, with different URLs, so\r
+            # the code notices those attributes already existed with\r
+            # different values, and complains.\r
+            # This happens regularly on delegation now that PG and\r
+            # PL both declare the namespace with different URLs.\r
+            # If the content ever differs this is a problem,\r
+            # but for now it works - different URLs (values in the attributes)\r
+            # but the same actual schema, so using the PG schema\r
+            # on delegated-to-PL credentials works fine.\r
+\r
+            # Note: you could also not copy attributes\r
+            # which already exist. It appears that both PG and PL\r
+            # will actually validate a slicecred with a parent\r
+            # signed using PG namespaces and a child signed with PL\r
+            # namespaces over the whole thing. But I don't know\r
+            # if that is a bug in xmlsec1, an accident since\r
+            # the contents of the schemas are the same,\r
+            # or something else, but it seems odd. And this works.\r
             parentRoot = sdoc.documentElement\r
             if parentRoot.tagName == "signed-credential" and parentRoot.hasAttributes():\r
                 for attrIx in range(0, parentRoot.attributes.length):\r
@@ -475,9 +520,9 @@ class Credential(object):
                     # Below throws InUse exception if we forgot to clone the attribute first\r
                     oldAttr = signed_cred.setAttributeNode(attr.cloneNode(True))\r
                     if oldAttr and oldAttr.value != attr.value:\r
-                        msg = "Delegating cred from owner %s to %s over %s replaced attribute %s value %s with %s" % (self.parent.gidCaller.get_urn(), self.gidCaller.get_urn(), self.gidObject.get_urn(), oldAttr.name, oldAttr.value, attr.value)\r
-                        logger.error(msg)\r
-                        raise CredentialNotVerifiable("Can't encode new valid delegated credential: %s" % msg)\r
+                        msg = "Delegating cred from owner %s to %s over %s replaced attribute %s value '%s' with '%s'" % (self.parent.gidCaller.get_urn(), self.gidCaller.get_urn(), self.gidObject.get_urn(), oldAttr.name, oldAttr.value, attr.value)\r
+                        logger.warn(msg)\r
+                        #raise CredentialNotVerifiable("Can't encode new valid delegated credential: %s" % msg)\r
 \r
             p_cred = doc.importNode(sdoc.getElementsByTagName("credential")[0], True)\r
             p = doc.createElement("parent")\r
@@ -636,16 +681,22 @@ class Credential(object):
 \r
         # Is this a signed-cred or just a cred?\r
         if len(signed_cred) > 0:\r
-            cred = signed_cred[0].getElementsByTagName("credential")[0]\r
+            creds = signed_cred[0].getElementsByTagName("credential")\r
             signatures = signed_cred[0].getElementsByTagName("signatures")\r
             if len(signatures) > 0:\r
                 sigs = signatures[0].getElementsByTagName("Signature")\r
         else:\r
-            cred = doc.getElementsByTagName("credential")[0]\r
+            creds = doc.getElementsByTagName("credential")\r
         \r
+        if creds is None or len(creds) == 0:\r
+            # malformed cred file\r
+            raise CredentialNotVerifiable("Malformed XML: No credential tag found")\r
+\r
+        # Just take the first cred if there are more than one\r
+        cred = creds[0]\r
 \r
         self.set_refid(cred.getAttribute("xml:id"))\r
-        self.set_expiration(parse(getTextNode(cred, "expires")))\r
+        self.set_expiration(utcparse(getTextNode(cred, "expires")))\r
         self.gidCaller = GID(string=getTextNode(cred, "owner_gid"))\r
         self.gidObject = GID(string=getTextNode(cred, "target_gid"))   \r
 \r
@@ -660,7 +711,7 @@ class Credential(object):
                 # Convert * into the default privileges for the credential's type\r
                 # Each inherits the delegatability from the * above\r
                 _ , type = urn_to_hrn(self.gidObject.get_urn())\r
-                rl = rlist.determine_rights(type, self.gidObject.get_urn())\r
+                rl = determine_rights(type, self.gidObject.get_urn())\r
                 for r in rl.rights:\r
                     r.delegate = deleg\r
                     rlist.add(r)\r
@@ -702,6 +753,7 @@ class Credential(object):
     # . That the issuer of the credential is the authority in the target's urn\r
     #    . In the case of a delegated credential, this must be true of the root\r
     # . That all of the gids presented in the credential are valid\r
+    #    . Including verifying GID chains, and includ the issuer\r
     # . The credential is not expired\r
     #\r
     # -- For Delegates (credentials with parents)\r
@@ -721,15 +773,15 @@ class Credential(object):
             self.decode()\r
 \r
         # validate against RelaxNG schema\r
-        if not self.legacy:\r
+        if HAVELXML and not self.legacy:\r
             if schema and os.path.exists(schema):\r
                 tree = etree.parse(StringIO(self.xml))\r
                 schema_doc = etree.parse(schema)\r
                 xmlschema = etree.XMLSchema(schema_doc)\r
                 if not xmlschema.validate(tree):\r
                     error = xmlschema.error_log.last_error\r
-                    message = "%s (line %s)" % (error.message, error.line)\r
-                    raise CredentialNotVerifiable(message)        \r
+                    message = "%s: %s (line %s)" % (self.get_summary_tostring(), error.message, error.line)\r
+                    raise CredentialNotVerifiable(message)\r
 \r
         if trusted_certs_required and trusted_certs is None:\r
             trusted_certs = []\r
@@ -761,7 +813,7 @@ class Credential(object):
         \r
         # make sure it is not expired\r
         if self.get_expiration() < datetime.datetime.utcnow():\r
-            raise CredentialNotVerifiable("Credential expired at %s" % self.expiration.isoformat())\r
+            raise CredentialNotVerifiable("Credential %s expired at %s" % (self.get_summary_tostring(), self.expiration.isoformat()))\r
 \r
         # Verify the signatures\r
         filename = self.save_to_random_tmp_file()\r
@@ -769,7 +821,7 @@ class Credential(object):
             cert_args = " ".join(['--trusted-pem %s' % x for x in trusted_certs])\r
 \r
         # If caller explicitly passed in None that means skip cert chain validation.\r
-        # Strange and not typical\r
+        # Strange and not typical\r
         if trusted_certs is not None:\r
             # Verify the gids of this cred and of its parents\r
             for cur_cred in self.get_credential_list():\r
@@ -801,15 +853,16 @@ class Credential(object):
                     mstart = mstart + 4\r
                     mend = verified.find('\\', mstart)\r
                     msg = verified[mstart:mend]\r
-                raise CredentialNotVerifiable("xmlsec1 error verifying cred using Signature ID %s: %s %s" % (ref, msg, verified.strip()))\r
+                raise CredentialNotVerifiable("xmlsec1 error verifying cred %s using Signature ID %s: %s %s" % (self.get_summary_tostring(), ref, msg, verified.strip()))\r
         os.remove(filename)\r
 \r
         # Verify the parents (delegation)\r
         if self.parent:\r
             self.verify_parent(self.parent)\r
 \r
-        # Make sure the issuer is the target's authority\r
-        self.verify_issuer()\r
+        # Make sure the issuer is the target's authority, and is\r
+        # itself a valid GID\r
+        self.verify_issuer(trusted_cert_objects)\r
         return True\r
 \r
     ##\r
@@ -827,31 +880,61 @@ class Credential(object):
         return list\r
     \r
     ##\r
-    # Make sure the credential's target gid was signed by (or is the same) the entity that signed\r
-    # the original credential or an authority over that namespace.\r
-    def verify_issuer(self):                \r
+    # Make sure the credential's target gid (a) was signed by or (b)\r
+    # is the same as the entity that signed the original credential,\r
+    # or (c) is an authority over the target's namespace.\r
+    # Also ensure that the credential issuer / signer itself has a valid\r
+    # GID signature chain (signed by an authority with namespace rights).\r
+    def verify_issuer(self, trusted_gids):\r
         root_cred = self.get_credential_list()[-1]\r
         root_target_gid = root_cred.get_gid_object()\r
         root_cred_signer = root_cred.get_signature().get_issuer_gid()\r
 \r
+        # Case 1:\r
+        # Allow non authority to sign target and cred about target.\r
+        #\r
+        # Why do we need to allow non authorities to sign?\r
+        # If in the target gid validation step we correctly\r
+        # checked that the target is only signed by an authority,\r
+        # then this is just a special case of case 3.\r
+        # This short-circuit is the common case currently -\r
+        # and cause GID validation doesn't check 'authority',\r
+        # this allows users to generate valid slice credentials.\r
         if root_target_gid.is_signed_by_cert(root_cred_signer):\r
             # cred signer matches target signer, return success\r
             return\r
 \r
-        root_target_gid_str = root_target_gid.save_to_string()\r
-        root_cred_signer_str = root_cred_signer.save_to_string()\r
-        if root_target_gid_str == root_cred_signer_str:\r
-            # cred signer is target, return success\r
-            return\r
-\r
-        # See if it the signer is an authority over the domain of the target\r
+        # Case 2:\r
+        # Allow someone to sign credential about themeselves. Used?\r
+        # If not, remove this.\r
+        #root_target_gid_str = root_target_gid.save_to_string()\r
+        #root_cred_signer_str = root_cred_signer.save_to_string()\r
+        #if root_target_gid_str == root_cred_signer_str:\r
+        #    # cred signer is target, return success\r
+        #    return\r
+\r
+        # Case 3:\r
+\r
+        # root_cred_signer is not the target_gid\r
+        # So this is a different gid that we have not verified.\r
+        # xmlsec1 verified the cert chain on this already, but\r
+        # it hasn't verified that the gid meets the HRN namespace\r
+        # requirements.\r
+        # Below we'll ensure that it is an authority.\r
+        # But we haven't verified that it is _signed by_ an authority\r
+        # We also don't know if xmlsec1 requires that cert signers\r
+        # are marked as CAs.\r
+        root_cred_signer.verify_chain(trusted_gids)\r
+\r
+        # See if the signer is an authority over the domain of the target.\r
+        # There are multiple types of authority - accept them all here\r
         # Maybe should be (hrn, type) = urn_to_hrn(root_cred_signer.get_urn())\r
         root_cred_signer_type = root_cred_signer.get_type()\r
-        if (root_cred_signer_type == 'authority'):\r
-            #sfa_logger.debug('Cred signer is an authority')\r
+        if (root_cred_signer_type.find('authority') == 0):\r
+            #logger.debug('Cred signer is an authority')\r
             # signer is an authority, see if target is in authority's domain\r
-            hrn = root_cred_signer.get_hrn()\r
-            if root_target_gid.get_hrn().startswith(hrn):\r
+            signerhrn = root_cred_signer.get_hrn()\r
+            if hrn_authfor_hrn(signerhrn, root_target_gid.get_hrn()):\r
                 return\r
 \r
         # We've required that the credential be signed by an authority\r
@@ -876,23 +959,23 @@ class Credential(object):
         # make sure the rights given to the child are a subset of the\r
         # parents rights (and check delegate bits)\r
         if not parent_cred.get_privileges().is_superset(self.get_privileges()):\r
-            raise ChildRightsNotSubsetOfParent(("Parent cred ref %s rights " % self.parent.get_refid()) + \r
-                self.parent.get_privileges().save_to_string() + (" not superset of delegated cred ref %s rights " % self.get_refid()) +\r
+            raise ChildRightsNotSubsetOfParent(("Parent cred ref %s rights " % parent_cred.get_refid()) +\r
+                self.parent.get_privileges().save_to_string() + (" not superset of delegated cred %s ref %s rights " % (self.get_summary_tostring(), self.get_refid())) +\r
                 self.get_privileges().save_to_string())\r
 \r
         # make sure my target gid is the same as the parent's\r
         if not parent_cred.get_gid_object().save_to_string() == \\r
            self.get_gid_object().save_to_string():\r
-            raise CredentialNotVerifiable("Target gid not equal between parent and child")\r
+            raise CredentialNotVerifiable("Delegated cred %s: Target gid not equal between parent and child. Parent %s" % (self.get_summary_tostring(), parent_cred.get_summary_tostring()))\r
 \r
         # make sure my expiry time is <= my parent's\r
         if not parent_cred.get_expiration() >= self.get_expiration():\r
-            raise CredentialNotVerifiable("Delegated credential expires after parent")\r
+            raise CredentialNotVerifiable("Delegated credential %s expires after parent %s" % (self.get_summary_tostring(), parent_cred.get_summary_tostring()))\r
 \r
         # make sure my signer is the parent's caller\r
         if not parent_cred.get_gid_caller().save_to_string(False) == \\r
            self.get_signature().get_issuer_gid().save_to_string(False):\r
-            raise CredentialNotVerifiable("Delegated credential not signed by parent caller")\r
+            raise CredentialNotVerifiable("Delegated credential %s not signed by parent %s's caller" % (self.get_summary_tostring(), parent_cred.get_summary_tostring()))\r
                 \r
         # Recurse\r
         if parent_cred.parent:\r
@@ -932,7 +1015,7 @@ class Credential(object):
     # only informative\r
     def get_filename(self):\r
         return getattr(self,'filename',None)\r
\r
+\r
     ##\r
     # Dump the contents of a credential to stdout in human-readable format\r
     #\r
@@ -963,6 +1046,6 @@ class Credential(object):
 \r
         if self.parent and dump_parents:\r
             result += "\nPARENT"\r
-            result += self.parent.dump(True)\r
+            result += self.parent.dump_string(True)\r
 \r
         return result\r