security: Handle certificate decoding error in validation process

Change-Id: I6365db2d9fd58c4dd5d7e1f840cc85253381e03c
Refs: #2212
diff --git a/src/security/certificate.cpp b/src/security/certificate.cpp
index 3af9bf9..67c440b 100644
--- a/src/security/certificate.cpp
+++ b/src/security/certificate.cpp
@@ -30,9 +30,15 @@
 #include "cryptopp.hpp"
 #include "../encoding/cryptopp/asn_ext.hpp"
 #include "../encoding/buffer-stream.hpp"
+#include "../util/concepts.hpp"
 
 namespace ndn {
 
+BOOST_CONCEPT_ASSERT((WireEncodable<Certificate>));
+BOOST_CONCEPT_ASSERT((WireDecodable<Certificate>));
+static_assert(std::is_base_of<tlv::Error, Certificate::Error>::value,
+              "Certificate::Error must inherit from tlv::Error");
+
 Certificate::Certificate()
   : m_notBefore(time::system_clock::TimePoint::max())
   , m_notAfter(time::system_clock::TimePoint::min())
@@ -46,9 +52,21 @@
   decode();
 }
 
+Certificate::Certificate(const Block& block)
+  : Data(block)
+{
+  decode();
+}
+
 Certificate::~Certificate()
 {
-  //TODO:
+}
+
+void
+Certificate::wireDecode(const Block& wire)
+{
+  Data::wireDecode(wire);
+  decode();
 }
 
 bool
@@ -177,66 +195,71 @@
 {
   using namespace CryptoPP;
 
-  OBufferStream os;
-  StringSource source(getContent().value(), getContent().value_size(), true);
+  try {
+    OBufferStream os;
+    StringSource source(getContent().value(), getContent().value_size(), true);
 
-  // idCert ::= SEQUENCE {
-  //     validity            Validity,
-  //     subject             Name,
-  //     subjectPubKeyInfo   SubjectPublicKeyInfo,
-  //     extension           Extensions OPTIONAL   }
-  BERSequenceDecoder idCert(source);
-  {
-    // Validity ::= SEQUENCE {
-    //       notBefore           Time,
-    //       notAfter            Time   }
-    BERSequenceDecoder validity(idCert);
+    // idCert ::= SEQUENCE {
+    //     validity            Validity,
+    //     subject             Name,
+    //     subjectPubKeyInfo   SubjectPublicKeyInfo,
+    //     extension           Extensions OPTIONAL   }
+    BERSequenceDecoder idCert(source);
     {
-      BERDecodeTime(validity, m_notBefore);
-      BERDecodeTime(validity, m_notAfter);
-    }
-    validity.MessageEnd();
-
-    // Name ::= CHOICE {
-    //     RDNSequence   }
-    //
-    // RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
-    m_subjectDescriptionList.clear();
-    BERSequenceDecoder name(idCert);
-    {
-      while (!name.EndReached())
-        {
-          m_subjectDescriptionList.push_back(CertificateSubjectDescription(name));
-        }
-    }
-    name.MessageEnd();
-
-    // SubjectPublicKeyInfo ::= SEQUENCE {
-    //     algorithm           AlgorithmIdentifier
-    //     keybits             BIT STRING   }
-    m_key.decode(idCert);
-
-    // Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension
-    //
-    // Extension ::= SEQUENCE {
-    //        extnID      OBJECT IDENTIFIER,
-    //        critical    BOOLEAN DEFAULT FALSE,
-    //        extnValue   OCTET STRING  }
-    m_extensionList.clear();
-    if (!idCert.EndReached())
+      // Validity ::= SEQUENCE {
+      //       notBefore           Time,
+      //       notAfter            Time   }
+      BERSequenceDecoder validity(idCert);
       {
-        BERSequenceDecoder extensions(idCert);
-        {
-          while (!extensions.EndReached())
-            {
-              m_extensionList.push_back(CertificateExtension(extensions));
-            }
-        }
-        extensions.MessageEnd();
+        BERDecodeTime(validity, m_notBefore);
+        BERDecodeTime(validity, m_notAfter);
       }
-  }
+      validity.MessageEnd();
 
-  idCert.MessageEnd();
+      // Name ::= CHOICE {
+      //     RDNSequence   }
+      //
+      // RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
+      m_subjectDescriptionList.clear();
+      BERSequenceDecoder name(idCert);
+      {
+        while (!name.EndReached())
+          {
+            m_subjectDescriptionList.push_back(CertificateSubjectDescription(name));
+          }
+      }
+      name.MessageEnd();
+
+      // SubjectPublicKeyInfo ::= SEQUENCE {
+      //     algorithm           AlgorithmIdentifier
+      //     keybits             BIT STRING   }
+      m_key.decode(idCert);
+
+      // Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension
+      //
+      // Extension ::= SEQUENCE {
+      //        extnID      OBJECT IDENTIFIER,
+      //        critical    BOOLEAN DEFAULT FALSE,
+      //        extnValue   OCTET STRING  }
+      m_extensionList.clear();
+      if (!idCert.EndReached())
+        {
+          BERSequenceDecoder extensions(idCert);
+          {
+            while (!extensions.EndReached())
+              {
+                m_extensionList.push_back(CertificateExtension(extensions));
+              }
+          }
+          extensions.MessageEnd();
+        }
+    }
+
+    idCert.MessageEnd();
+  }
+  catch (CryptoPP::BERDecodeErr&) {
+    throw Error("Certificate Decoding Error");
+  }
 }
 
 void
@@ -320,4 +343,12 @@
 
 }
 
+std::ostream&
+operator<<(std::ostream& os, const Certificate& cert)
+{
+  cert.printCertificate(os);
+  return os;
+}
+
+
 } // namespace ndn
diff --git a/src/security/certificate.hpp b/src/security/certificate.hpp
index eff2bbc..c0fe8e0 100644
--- a/src/security/certificate.hpp
+++ b/src/security/certificate.hpp
@@ -37,12 +37,12 @@
 class Certificate : public Data
 {
 public:
-  class Error : public std::runtime_error
+  class Error : public Data::Error
   {
   public:
     explicit
     Error(const std::string& what)
-      : std::runtime_error(what)
+      : Data::Error(what)
     {
     }
   };
@@ -51,34 +51,38 @@
   typedef std::vector<CertificateExtension> ExtensionList;
 
   /**
-   * The default constructor.
+   * @brief The default constructor.
    */
   Certificate();
 
   /**
-   * Create a Certificate from the content in the data packet.
+   * @brief Create a Certificate from the content in the data packet.
    * @param data The data packet with the content to decode.
    */
   explicit
   Certificate(const Data& data);
 
   /**
-   * The virtual destructor.
+   * @brief Create a Certificate from the a block
+   * @param block The raw block of the certificate
    */
+  explicit
+  Certificate(const Block& block);
+
   virtual
   ~Certificate();
 
-  inline void
+  void
   wireDecode(const Block& wire);
 
   /**
-   * encode certificate info into content
+   * @brief encode certificate info into content
    */
   void
   encode();
 
   /**
-   * Add a subject description.
+   * @brief Add a subject description.
    * @param description The description to be added.
    */
   void
@@ -100,7 +104,7 @@
   }
 
   /**
-   * Add a certificate extension.
+   * @brief Add a certificate extension.
    * @param extension the extension to be added
    */
   void
@@ -176,14 +180,14 @@
   }
 
   /**
-   * Check if the certificate is valid.
+   * @brief Check if the certificate is valid.
    * @return True if the current time is earlier than notBefore.
    */
   bool
   isTooEarly();
 
   /**
-   * Check if the certificate is valid.
+   * @brief Check if the certificate is valid.
    * @return True if the current time is later than notAfter.
    */
   bool
@@ -204,21 +208,8 @@
   ExtensionList m_extensionList;
 };
 
-inline void
-Certificate::wireDecode(const Block& wire)
-{
-  Data::wireDecode(wire);
-  decode();
-}
-
-
-inline std::ostream&
-operator<<(std::ostream& os, const Certificate& cert)
-{
-  cert.printCertificate(os);
-  return os;
-}
-
+std::ostream&
+operator<<(std::ostream& os, const Certificate& cert);
 } // namespace ndn
 
-#endif //NDN_SECURITY_CERTIFICATE_HPP
+#endif // NDN_SECURITY_CERTIFICATE_HPP
diff --git a/src/security/identity-certificate.cpp b/src/security/identity-certificate.cpp
index 685fa29..7ec06f9 100644
--- a/src/security/identity-certificate.cpp
+++ b/src/security/identity-certificate.cpp
@@ -24,11 +24,47 @@
 #include "common.hpp"
 
 #include "identity-certificate.hpp"
+#include "../util/concepts.hpp"
 
 namespace ndn {
 
 using std::string;
 
+BOOST_CONCEPT_ASSERT((WireEncodable<IdentityCertificate>));
+BOOST_CONCEPT_ASSERT((WireDecodable<IdentityCertificate>));
+static_assert(std::is_base_of<Certificate::Error, IdentityCertificate::Error>::value,
+              "IdentityCertificate::Error must inherit from Certificate::Error");
+
+IdentityCertificate::IdentityCertificate()
+{
+}
+
+IdentityCertificate::IdentityCertificate(const Data& data)
+  : Certificate(data)
+{
+  setPublicKeyName();
+}
+
+IdentityCertificate::IdentityCertificate(const Block& block)
+  : Certificate(block)
+{
+  setPublicKeyName();
+}
+
+void
+IdentityCertificate::wireDecode(const Block& wire)
+{
+  Certificate::wireDecode(wire);
+  setPublicKeyName();
+}
+
+void
+IdentityCertificate::setName(const Name& name)
+{
+  Certificate::setName(name);
+  setPublicKeyName();
+}
+
 bool
 IdentityCertificate::isCorrectName(const Name& name)
 {
diff --git a/src/security/identity-certificate.hpp b/src/security/identity-certificate.hpp
index 90ad3c5..b416080 100644
--- a/src/security/identity-certificate.hpp
+++ b/src/security/identity-certificate.hpp
@@ -32,33 +32,34 @@
 class IdentityCertificate : public Certificate
 {
 public:
-  class Error : public std::runtime_error
+  class Error : public Certificate::Error
   {
   public:
     explicit
     Error(const std::string& what)
-      : std::runtime_error(what)
+      : Certificate::Error(what)
     {
     }
   };
 
   /**
-   * The default constructor.
+   * @brief The default constructor.
    */
   IdentityCertificate();
 
   /**
-   * Create an IdentityCertificate from the content in the data packet.
+   * @brief Create an IdentityCertificate from the content in the data packet.
    * @param data The data packet with the content to decode.
    */
   explicit
   IdentityCertificate(const Data& data);
 
   /**
-   * The virtual destructor.
+   * @brief Create an IdentityCertificate from a block.
+   * @param block The raw block of the certificate.
    */
-  virtual
-  ~IdentityCertificate();
+  explicit
+  IdentityCertificate(const Block& block);
 
   void
   wireDecode(const Block& wire);
@@ -67,13 +68,16 @@
   setName(const Name& name);
 
   const Name&
-  getPublicKeyName() const;
+  getPublicKeyName() const
+  {
+    return m_publicKeyName;
+  }
 
   static bool
   isIdentityCertificate(const Certificate& certificate);
 
   /**
-   * Get the public key name from the full certificate name.
+   * @brief Get the public key name from the full certificate name.
    * @param certificateName The full certificate name.
    * @return The related public key name.
    */
@@ -91,43 +95,6 @@
   Name m_publicKeyName;
 };
 
-inline
-IdentityCertificate::IdentityCertificate()
-{
-}
-
-inline
-IdentityCertificate::IdentityCertificate(const Data& data)
-  : Certificate(data)
-{
-  setPublicKeyName();
-}
-
-inline
-IdentityCertificate::~IdentityCertificate()
-{
-}
-
-inline void
-IdentityCertificate::wireDecode(const Block& wire)
-{
-  Certificate::wireDecode(wire);
-  setPublicKeyName();
-}
-
-inline void
-IdentityCertificate::setName(const Name& name)
-{
-  Certificate::setName(name);
-  setPublicKeyName();
-}
-
-inline const Name&
-IdentityCertificate::getPublicKeyName() const
-{
-  return m_publicKeyName;
-}
-
 } // namespace ndn
 
-#endif //NDN_SECURITY_IDENTITY_CERTIFICATE_HPP
+#endif // NDN_SECURITY_IDENTITY_CERTIFICATE_HPP
diff --git a/src/security/validator-config.cpp b/src/security/validator-config.cpp
index b55cf69..149c5dc 100644
--- a/src/security/validator-config.cpp
+++ b/src/security/validator-config.cpp
@@ -593,16 +593,17 @@
       return onValidationFailed(interest.shared_from_this(),
                                 "No valid KeyLocator");
     }
-  catch (tlv::Error& e)
-    {
-      return onValidationFailed(interest.shared_from_this(),
-                                "Cannot decode signature");
-    }
   catch (IdentityCertificate::Error& e)
     {
       return onValidationFailed(interest.shared_from_this(),
                                 "Cannot determine the signing key");
     }
+
+  catch (tlv::Error& e)
+    {
+      return onValidationFailed(interest.shared_from_this(),
+                                "Cannot decode signature");
+    }
 }
 
 void
@@ -831,8 +832,20 @@
                                  const OnValidated& onValidated,
                                  const OnFailed& onValidationFailed)
 {
-  shared_ptr<IdentityCertificate> certificate =
-    make_shared<IdentityCertificate>(*signCertificate);
+  if (signCertificate->getContentType() != tlv::ContentType_Key)
+    return onValidationFailed(packet,
+                              "Cannot retrieve signer's cert: " +
+                              signCertificate->getName().toUri());
+
+  shared_ptr<IdentityCertificate> certificate;
+  try {
+    certificate = make_shared<IdentityCertificate>(*signCertificate);
+  }
+  catch (tlv::Error&) {
+    return onValidationFailed(packet,
+                              "Cannot decode signer's cert: " +
+                              signCertificate->getName().toUri());
+  }
 
   if (!certificate->isTooLate() && !certificate->isTooEarly())
     {
diff --git a/src/util/io.hpp b/src/util/io.hpp
index 4c7caf9..f49d712 100644
--- a/src/util/io.hpp
+++ b/src/util/io.hpp
@@ -88,6 +88,10 @@
       object->wireDecode(Block(os.buf()));
       return object;
     }
+  catch (TypeError& e)
+    {
+      return shared_ptr<T>();
+    }
   catch (CryptoPP::Exception& e)
     {
       return shared_ptr<T>();
@@ -96,10 +100,6 @@
     {
       return shared_ptr<T>();
     }
-  catch (TypeError& e)
-    {
-      return shared_ptr<T>();
-    }
 }
 
 template<typename T>
@@ -146,6 +146,10 @@
         }
       return;
     }
+  catch (TypeError& e)
+    {
+      throw Error(e.what());
+    }
   catch (CryptoPP::Exception& e)
     {
       throw Error(e.what());
@@ -154,10 +158,6 @@
     {
       throw Error(e.what());
     }
-  catch (TypeError& e)
-    {
-      throw Error(e.what());
-    }
 }
 
 template<typename T>
diff --git a/tests/unit-tests/security/test-encode-decode-certificate.cpp b/tests/unit-tests/security/test-encode-decode-certificate.cpp
index 9948c01..27f5c8d 100644
--- a/tests/unit-tests/security/test-encode-decode-certificate.cpp
+++ b/tests/unit-tests/security/test-encode-decode-certificate.cpp
@@ -339,6 +339,42 @@
   BOOST_CHECK_EQUAL(RSA_CERT_INFO, rsaCertInfo);
 }
 
+const uint8_t WRONG_CERT[] = { // first byte is wrong and an error will be thrown out
+0x31, 0x82, 0x01, 0x63, 0x30, 0x22, 0x18, 0x0f, 0x32, 0x30, 0x31, 0x33, 0x31, 0x31, 0x30,
+0x31, 0x31, 0x37, 0x31, 0x31, 0x32, 0x32, 0x5a, 0x18, 0x0f, 0x32, 0x30, 0x31, 0x34, 0x31,
+0x31, 0x30, 0x31, 0x31, 0x37, 0x31, 0x31, 0x32, 0x32, 0x5a, 0x30, 0x19, 0x30, 0x17, 0x06,
+0x03, 0x55, 0x04, 0x29, 0x13, 0x10, 0x4e, 0x44, 0x4e, 0x20, 0x54, 0x65, 0x73, 0x74, 0x62,
+0x65, 0x64, 0x20, 0x52, 0x6f, 0x6f, 0x74, 0x30, 0x82, 0x01, 0x20, 0x30, 0x0d, 0x06, 0x09,
+0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0d,
+0x00, 0x30, 0x82, 0x01, 0x08, 0x02, 0x82, 0x01, 0x01, 0x00, 0xd3, 0xac, 0x7e, 0x7a, 0x5c,
+0x33, 0x58, 0x21, 0xda, 0xe0, 0x8d, 0xdb, 0xca, 0xb6, 0x02, 0x30, 0x02, 0x15, 0xc5, 0x0a,
+0x51, 0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7c, 0x54, 0x22, 0xfe, 0x72, 0x72, 0x04, 0xc3, 0x2c, 0xc0, 0x14, 0x0b,
+0xa9, 0x40, 0x7e, 0x46, 0xa1, 0x75, 0x16, 0x1a, 0x27, 0x9e, 0xf2, 0x82, 0x96, 0xc0, 0x7d,
+0xaf, 0x18, 0x75, 0xfb, 0xbb, 0xab, 0x16, 0x66, 0xc0, 0xa9, 0xd7, 0x93, 0x4c, 0x48, 0x6d,
+0xce, 0x0b, 0x88, 0xd4, 0x21, 0x93, 0x84, 0x89, 0x55, 0x05, 0xd5, 0x02, 0x01, 0x11
+};
+
+BOOST_AUTO_TEST_CASE(DecodeError)
+{
+  ndn::Data data("/tmp");
+  data.setContent(WRONG_CERT, sizeof(WRONG_CERT));
+
+  BOOST_CHECK_THROW(ndn::Certificate certificate(data), Certificate::Error);
+}
+
+
 BOOST_AUTO_TEST_SUITE_END()
 
 } // namespace ndn