security: Add a set of signature verification helpers

This commit introduces a set of security::v2::verifySignature and
security::v2::verifyDigest overloads to simplify signature verification
operations.

This commit also updates operator== of util::Digest class to
constant-time `CRYPTO_memcmp` comparison to mitigate potential timing
attacks.

Change-Id: I30c5a315b612062a96b289c4a5292dd6eb3d410f
diff --git a/src/security/detail/openssl.hpp b/src/security/detail/openssl.hpp
index d3ab592..cde9efc 100644
--- a/src/security/detail/openssl.hpp
+++ b/src/security/detail/openssl.hpp
@@ -1,6 +1,6 @@
 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
 /**
- * Copyright (c) 2013-2016 Regents of the University of California.
+ * Copyright (c) 2013-2017 Regents of the University of California.
  *
  * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
  *
@@ -32,14 +32,15 @@
 
 #endif // __APPLE__
 
-#include <openssl/rand.h>
 #include <openssl/bio.h>
-#include <openssl/evp.h>
-#include <openssl/rsa.h>
+#include <openssl/crypto.h>
 #include <openssl/ec.h>
-#include <openssl/pem.h>
-#include <openssl/hmac.h>
-#include <openssl/x509.h>
 #include <openssl/err.h>
+#include <openssl/evp.h>
+#include <openssl/hmac.h>
+#include <openssl/pem.h>
+#include <openssl/rand.h>
+#include <openssl/rsa.h>
+#include <openssl/x509.h>
 
 #endif // NDN_SECURITY_DETAIL_OPENSSL_HPP
diff --git a/src/security/security-common.hpp b/src/security/security-common.hpp
index 04d2691..b5a704d 100644
--- a/src/security/security-common.hpp
+++ b/src/security/security-common.hpp
@@ -157,6 +157,15 @@
 std::ostream&
 operator<<(std::ostream& os, AclType aclType);
 
+namespace security {
+namespace transform {
+class PublicKey;
+} // namespace transform
+namespace v2 {
+using transform::PublicKey;
+} // namespace v2
+} // namespace security
+
 } // namespace ndn
 
 #endif // NDN_SECURITY_SECURITY_COMMON_HPP
diff --git a/src/security/verification-helpers.cpp b/src/security/verification-helpers.cpp
new file mode 100644
index 0000000..f8fd3d2
--- /dev/null
+++ b/src/security/verification-helpers.cpp
@@ -0,0 +1,250 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2013-2017 Regents of the University of California.
+ *
+ * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
+ *
+ * ndn-cxx library is free software: you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free Software
+ * Foundation, either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+ * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
+ *
+ * You should have received copies of the GNU General Public License and GNU Lesser
+ * General Public License along with ndn-cxx, e.g., in COPYING.md file.  If not, see
+ * <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
+ */
+
+#include "verification-helpers.hpp"
+
+#include "data.hpp"
+#include "interest.hpp"
+#include "encoding/buffer-stream.hpp"
+#include "security/pib/key.hpp"
+#include "security/pib/key.hpp"
+#include "security/transform.hpp"
+#include "security/v2/certificate.hpp"
+#include "security/detail/openssl.hpp"
+
+namespace ndn {
+namespace security {
+
+bool
+verifySignature(const uint8_t* blob, size_t blobLen, const uint8_t* sig, size_t sigLen,
+                const v2::PublicKey& pKey)
+{
+  bool result = false;
+  try {
+    using namespace transform;
+    bufferSource(blob, blobLen) >> verifierFilter(DigestAlgorithm::SHA256, pKey, sig, sigLen)
+                                >> boolSink(result);
+  }
+  catch (const transform::Error&) {
+    return false;
+  }
+  return result;
+}
+
+bool
+verifySignature(const uint8_t* data, size_t dataLen, const uint8_t* sig, size_t sigLen,
+                const uint8_t* key, size_t keyLen)
+{
+  v2::PublicKey pKey;
+  try {
+    pKey.loadPkcs8(key, keyLen);
+  }
+  catch (const transform::Error&) {
+    return false;
+  }
+
+  return verifySignature(data, dataLen, sig, sigLen, pKey);
+}
+
+static std::tuple<bool, const uint8_t*, size_t, const uint8_t*, size_t>
+parse(const Data& data)
+{
+  try {
+    return std::make_tuple(true,
+                           data.wireEncode().value(),
+                           data.wireEncode().value_size() - data.getSignature().getValue().size(),
+                           data.getSignature().getValue().value(),
+                           data.getSignature().getValue().value_size());
+  }
+  catch (const tlv::Error&) {
+    return std::make_tuple(false, nullptr, 0, nullptr, 0);
+  }
+}
+
+static std::tuple<bool, const uint8_t*, size_t, const uint8_t*, size_t>
+parse(const Interest& interest)
+{
+  const Name& interestName = interest.getName();
+
+  if (interestName.size() < signed_interest::MIN_SIZE)
+    return std::make_tuple(false, nullptr, 0, nullptr, 0);
+
+  try {
+    const Block& nameBlock = interestName.wireEncode();
+
+    return std::make_tuple(true,
+                           nameBlock.value(), nameBlock.value_size() - interestName[signed_interest::POS_SIG_VALUE].size(),
+                           interestName[signed_interest::POS_SIG_VALUE].blockFromValue().value(),
+                           interestName[signed_interest::POS_SIG_VALUE].blockFromValue().value_size());
+  }
+  catch (const tlv::Error&) {
+    return std::make_tuple(false, nullptr, 0, nullptr, 0);
+  }
+}
+
+static bool
+verifySignature(const std::tuple<bool, const uint8_t*, size_t, const uint8_t*, size_t>& params,
+                const v2::PublicKey& pKey)
+{
+  bool isParsable = false;
+  const uint8_t* buf = nullptr;
+  size_t bufLen = 0;
+  const uint8_t* sig = nullptr;
+  size_t sigLen = 0;
+
+  std::tie(isParsable, buf, bufLen, sig, sigLen) = params;
+
+  if (isParsable)
+    return verifySignature(buf, bufLen, sig, sigLen, pKey);
+  else
+    return false;
+}
+
+static bool
+verifySignature(const std::tuple<bool, const uint8_t*, size_t, const uint8_t*, size_t>& params,
+                const uint8_t* key, size_t keyLen)
+{
+  bool isParsable = false;
+  const uint8_t* buf = nullptr;
+  size_t bufLen = 0;
+  const uint8_t* sig = nullptr;
+  size_t sigLen = 0;
+
+  std::tie(isParsable, buf, bufLen, sig, sigLen) = params;
+
+  if (isParsable)
+    return verifySignature(buf, bufLen, sig, sigLen, key, keyLen);
+  else
+    return false;
+}
+
+bool
+verifySignature(const Data& data, const v2::PublicKey& key)
+{
+  return verifySignature(parse(data), key);
+}
+
+bool
+verifySignature(const Interest& interest, const v2::PublicKey& key)
+{
+  return verifySignature(parse(interest), key);
+}
+
+bool
+verifySignature(const Data& data, const pib::Key& key)
+{
+  return verifySignature(parse(data), key.getPublicKey().buf(), key.getPublicKey().size());
+}
+
+bool
+verifySignature(const Interest& interest, const pib::Key& key)
+{
+  return verifySignature(parse(interest), key.getPublicKey().buf(), key.getPublicKey().size());
+}
+
+bool
+verifySignature(const Data& data, const uint8_t* key, size_t keyLen)
+{
+  return verifySignature(parse(data), key, keyLen);
+}
+
+bool
+verifySignature(const Interest& interest, const uint8_t* key, size_t keyLen)
+{
+  return verifySignature(parse(interest), key, keyLen);
+}
+
+bool
+verifySignature(const Data& data, const v2::Certificate& cert)
+{
+  return verifySignature(parse(data), cert.getContent().value(), cert.getContent().value_size());
+}
+
+bool
+verifySignature(const Interest& interest, const v2::Certificate& cert)
+{
+  return verifySignature(parse(interest), cert.getContent().value(), cert.getContent().value_size());
+}
+
+///////////////////////////////////////////////////////////////////////
+
+bool
+verifyDigest(const uint8_t* blob, size_t blobLen, const uint8_t* digest, size_t digestLen,
+             DigestAlgorithm algorithm)
+{
+  using namespace transform;
+
+  OBufferStream os;
+  try {
+    bufferSource(blob, blobLen) >> digestFilter(algorithm) >> streamSink(os);
+  }
+  catch (const transform::Error&) {
+    return false;
+  }
+  ConstBufferPtr result = os.buf();
+
+  if (result->size() != digestLen)
+    return false;
+
+  // constant-time buffer comparison to mitigate timing attacks
+  return CRYPTO_memcmp(result->buf(), digest, digestLen) == 0;
+}
+
+bool
+verifyDigest(const Data& data, DigestAlgorithm algorithm)
+{
+  bool isParsable = false;
+  const uint8_t* buf = nullptr;
+  size_t bufLen = 0;
+  const uint8_t* sig = nullptr;
+  size_t sigLen = 0;
+
+  std::tie(isParsable, buf, bufLen, sig, sigLen) = parse(data);
+
+  if (isParsable) {
+    return verifyDigest(buf, bufLen, sig, sigLen, algorithm);
+  }
+  else {
+    return false;
+  }
+}
+
+bool
+verifyDigest(const Interest& interest, DigestAlgorithm algorithm)
+{
+  bool isParsable = false;
+  const uint8_t* buf = nullptr;
+  size_t bufLen = 0;
+  const uint8_t* sig = nullptr;
+  size_t sigLen = 0;
+
+  std::tie(isParsable, buf, bufLen, sig, sigLen) = parse(interest);
+
+  if (isParsable) {
+    return verifyDigest(buf, bufLen, sig, sigLen, algorithm);
+  }
+  else {
+    return false;
+  }
+}
+
+} // namespace security
+} // namespace ndn
diff --git a/src/security/verification-helpers.hpp b/src/security/verification-helpers.hpp
new file mode 100644
index 0000000..8b45892
--- /dev/null
+++ b/src/security/verification-helpers.hpp
@@ -0,0 +1,144 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2013-2017 Regents of the University of California.
+ *
+ * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
+ *
+ * ndn-cxx library is free software: you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free Software
+ * Foundation, either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+ * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
+ *
+ * You should have received copies of the GNU General Public License and GNU Lesser
+ * General Public License along with ndn-cxx, e.g., in COPYING.md file.  If not, see
+ * <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
+ */
+
+#ifndef NDN_SECURITY_VERIFICATION_HELPERS_HPP
+#define NDN_SECURITY_VERIFICATION_HELPERS_HPP
+
+#include "security-common.hpp"
+
+namespace ndn {
+
+class Interest;
+class Data;
+
+namespace security {
+
+namespace pib {
+class Key;
+} // namespace pib
+
+namespace v2 {
+class Certificate;
+} // namespace v2
+
+/**
+ * @brief Verify @p blob using @p key against @p sig.
+ *
+ * This is the core function, all other verifySignature overloads are implemented in terms
+ * of this function.
+ */
+bool
+verifySignature(const uint8_t* blob, size_t blobLen, const uint8_t* sig, size_t sigLen,
+                const v2::PublicKey& pKey);
+
+/**
+ * @brief Verify @p blob using @p key against @p sig.
+ */
+bool
+verifySignature(const uint8_t* blob, size_t blobLen, const uint8_t* sig, size_t sigLen,
+                const uint8_t* key, size_t keyLen);
+
+/**
+ * @brief Verify @p data using @p key.
+ */
+bool
+verifySignature(const Data& data, const uint8_t* key, size_t keyLen);
+
+/**
+ * @brief Verify @p interest using @p key.
+ * @note This method verifies only signature of the signed interest
+ * @sa docs/specs/signed-interest.rst
+ */
+bool
+verifySignature(const Interest& interest, const uint8_t* key, size_t keyLen);
+
+/**
+ * @brief Verify @p data using @p key.
+ */
+bool
+verifySignature(const Data& data, const v2::PublicKey& key);
+
+/**
+ * @brief Verify @p interest using @p key.
+ * @note This method verifies only signature of the signed interest
+ * @sa docs/specs/signed-interest.rst
+ */
+bool
+verifySignature(const Interest& interest, const v2::PublicKey& key);
+
+/**
+ * @brief Verify @p data using @p key.
+ */
+bool
+verifySignature(const Data& data, const pib::Key& key);
+
+/**
+ * @brief Verify @p interest using @p key.
+ * @note This method verifies only signature of the signed interest
+ * @sa docs/specs/signed-interest.rst
+ */
+bool
+verifySignature(const Interest& interest, const pib::Key& key);
+
+/**
+ * @brief Verify @p data using @p cert.
+ */
+bool
+verifySignature(const Data& data, const v2::Certificate& cert);
+
+/**
+ * @brief Verify @p interest using @p cert.
+ * @note This method verifies only signature of the signed interest
+ * @sa docs/specs/signed-interest.rst
+ */
+bool
+verifySignature(const Interest& interest, const v2::Certificate& cert);
+
+//////////////////////////////////////////////////////////////////
+
+/**
+ * @brief Verify @p blob against @p digest using @p algorithm.
+ *
+ * This is the core function, all other verifyDigest overloads are implemented in terms
+ * of this function.
+ */
+bool
+verifyDigest(const uint8_t* blob, size_t blobLen, const uint8_t* digest, size_t digestLen,
+             DigestAlgorithm algorithm);
+
+/**
+ * @brief Verify @p data against digest @p algorithm.
+ */
+bool
+verifyDigest(const Data& data, DigestAlgorithm algorithm);
+
+/**
+ * @brief Verify @p interest against digest @p algorithm.
+ * @note This method verifies only signature of the signed interest
+ * @sa docs/specs/signed-interest.rst
+ */
+bool
+verifyDigest(const Interest& interest, DigestAlgorithm algorithm);
+
+} // namespace security
+} // namespace ndn
+
+#endif // NDN_SECURITY_VERIFICATION_HELPERS_HPP
diff --git a/src/util/digest.cpp b/src/util/digest.cpp
index 67fd708..68c53ce 100644
--- a/src/util/digest.cpp
+++ b/src/util/digest.cpp
@@ -1,6 +1,6 @@
 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
 /**
- * Copyright (c) 2013-2015 Regents of the University of California.
+ * Copyright (c) 2013-2017 Regents of the University of California.
  *
  * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
  *
@@ -21,6 +21,8 @@
 
 #include "digest.hpp"
 #include "string-helper.hpp"
+#include "security/detail/openssl.hpp"
+
 #include <sstream>
 
 namespace ndn {
@@ -80,7 +82,15 @@
 bool
 Digest<Hash>::operator==(Digest<Hash>& digest)
 {
-  return *computeDigest() == *digest.computeDigest();
+  const Buffer& lhs = *computeDigest();
+  const Buffer& rhs = *digest.computeDigest();
+
+  if (lhs.size() != rhs.size()) {
+    return false;
+  }
+
+  // constant-time buffer comparison to mitigate timing attacks
+  return CRYPTO_memcmp(lhs.buf(), rhs.buf(), lhs.size()) == 0;
 }
 
 template<typename Hash>
diff --git a/src/util/digest.hpp b/src/util/digest.hpp
index ce86e1d..41e45a5 100644
--- a/src/util/digest.hpp
+++ b/src/util/digest.hpp
@@ -1,6 +1,6 @@
 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
 /**
- * Copyright (c) 2013-2016 Regents of the University of California.
+ * Copyright (c) 2013-2017 Regents of the University of California.
  *
  * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
  *
@@ -31,17 +31,15 @@
 namespace util {
 
 /**
- * @brief provides a  digest calculation
+ * @brief provides a stateful digest calculation
  *
- * Take SHA256 as an example:
+ * SHA256 example:
  *
  *   Digest<CryptoPP::SHA256> digest;
  *   digest.update(buf1, size1);
  *   digest.update(buf2, size2);
  *   ...
  *   ConstBufferPtr result = digest.computeDigest();
- *
- * @sa http://redmine.named-data.net/issues/1934
  */
 template<typename Hash>
 class Digest
@@ -64,14 +62,14 @@
   Digest();
 
   /**
-   * @brief Create digest of the input stream @p is
+   * @brief Calculate digest of the input stream @p is
    * @param is input stream
    */
   explicit
   Digest(std::istream& is);
 
   /**
-   * @brief Discard the current state and start a new digest.
+   * @brief Discard the current state and start a new digest calculation.
    */
   void
   reset();
@@ -88,33 +86,23 @@
   }
 
   /**
-   * @brief Obtain the digest
-   *
-   * Note this digest is finalized once this method is invoked.
+   * @brief Finalize and return the digest based on all previously supplied inputs.
    */
   ConstBufferPtr
   computeDigest();
 
   /**
-   * @brief Check if supplied digest equal to this digest
+   * @brief Check if the supplied digest equals to this digest
    *
-   * Note that this method will invoke computeDigest().
-   * Once this method is invoked, both this digest and the supplied digest are finalized.
-   *
-   * @warning This method cannot be used in security related context
-   *          because it is vulnerable to timing attack
+   * @note This method will invoke computeDigest(), finalizing the digest.
    */
   bool
   operator==(Digest<Hash>& digest);
 
   /**
-   * @brief Check if supplied digest is not equal to this digest
+   * @brief Check if the supplied digest is not equal to this digest
    *
-   * Note that this method will invoke computeDigest().
-   * Once this method is invoked, both this digest and the supplied digest are finalized.
-   *
-   * @warning This method cannot be used in security related context
-   *          because it is vulnerable to timing attack
+   * @note This method will invoke computeDigest(), finalizing the digest.
    */
   bool
   operator!=(Digest<Hash>& digest)
@@ -123,46 +111,48 @@
   }
 
   /**
-   * @brief Add existing digest to digest calculation
+   * @brief Add existing digest to the digest calculation
    * @param src digest to combine with
    *
-   * The result of this combination is  hash (hash (...))
-   * Note that this method will invoke computeDigest().
-   * Once this method is invoked, the supplied digest is fixed.
+   * The result of this combination is `digest(digest(...))`
+   *
+   * @note This method will invoke computeDigest(), finalizing the digest.
    */
   Digest<Hash>&
   operator<<(Digest<Hash>& src);
 
   /**
-   * @brief Add string to digest calculation
+   * @brief Add string to the digest calculation
    * @param str string to put into digest
    */
   Digest<Hash>&
   operator<<(const std::string& str);
 
   /**
-   * @brief Add block to digest calculation
-   * @param block to put into digest
+   * @brief Add block to the digest calculation
+   * @param block data block to put into digest
+   * @throw Error the digest has been finalized.
    */
   Digest<Hash>&
   operator<<(const Block& block);
 
   /**
-   * @brief Add uint64_t value to digest calculation
-   * @param value uint64_t value to put into digest
+   * @brief Add uint64_t value to the digest calculation
+   * @param value the integer value to put into digest
+   * @throw Error the digest has been finalized.
    */
   Digest<Hash>&
   operator<<(uint64_t value);
 
   /**
-   * @brief Add a buffer to digest calculation
+   * @brief Add a buffer to the digest calculation
    *
-   * Update the state of the digest if it is not finalized
-   * and mark the digest as InProcess.
+   * Update the state of the digest if it has not been finalized and mark the digest as
+   * InProcess.
    *
    * @param buffer the input buffer
    * @param size the size of the input buffer.
-   * @throws Error if the digest has been finalized.
+   * @throw Error the digest has been finalized.
    */
   void
   update(const uint8_t* buffer, size_t size);
@@ -171,7 +161,7 @@
    * @brief Compute one-time digest
    * @param buffer the input buffer
    * @param size the size of the input buffer.
-   * @return digest computed according to the HashAlgorithm
+   * @return digest computed according to the `Hash` algorithm
    */
   static ConstBufferPtr
   computeDigest(const uint8_t* buffer, size_t size);
@@ -179,8 +169,7 @@
   /**
    * @brief Convert digest to std::string
    *
-   * Note that this method will invoke computeDigest().
-   * Once this method is invoked, the digest is finalized.
+   * @note This method will invoke computeDigest(), finalizing the digest.
    */
   std::string
   toString();