security: Include timestamp and nonce in signed interest and provide timestamp checking in ValidatorConf

Change-Id: I0adebd5c06b2d8d35ba13c5c03828b03334b7cec
Refs: #1642
diff --git a/src/security/conf/filter.hpp b/src/security/conf/filter.hpp
index fb2c15d..8d0601c 100644
--- a/src/security/conf/filter.hpp
+++ b/src/security/conf/filter.hpp
@@ -28,6 +28,7 @@
 #include "../../data.hpp"
 #include "../../interest.hpp"
 #include "../../util/regex.hpp"
+#include "../security-common.hpp"
 #include <boost/algorithm/string.hpp>
 
 #include "common.hpp"
@@ -36,19 +37,42 @@
 namespace security {
 namespace conf {
 
+/**
+ * @brief Filter is one of the classes used by ValidatorConfig.
+ *
+ * The ValidatorConfig class consists of a set of rules.
+ * The Filter class is a part of a rule and is used to match packet.
+ * Matched packets will be checked against the checkers defined in the rule.
+ */
+
 class Filter
 {
 public:
+
   virtual
   ~Filter()
   {
   }
 
-  virtual bool
-  match(const Data& data) = 0;
+  bool
+  match(const Data& data)
+  {
+    return matchName(data.getName());
+  }
 
+  bool
+  match(const Interest& interest)
+  {
+    if (interest.getName().size() < signed_interest::MIN_LENGTH)
+      return false;
+
+    Name unsignedName = interest.getName().getPrefix(-signed_interest::MIN_LENGTH);
+    return matchName(unsignedName);
+  }
+
+protected:
   virtual bool
-  match(const Interest& interest) = 0;
+  matchName(const Name& name) = 0;
 };
 
 class RelationNameFilter : public Filter
@@ -72,25 +96,9 @@
   {
   }
 
+protected:
   virtual bool
-  match(const Data& data)
-  {
-    return match(data.getName());
-  }
-
-  virtual bool
-  match(const Interest& interest)
-  {
-    if (interest.getName().size() < 2)
-      return false;
-
-    Name signedName = interest.getName().getPrefix(-2);
-    return match(signedName);
-  }
-
-private:
-  bool
-  match(const Name& name)
+  matchName(const Name& name)
   {
     switch (m_relation)
       {
@@ -99,7 +107,7 @@
       case RELATION_IS_PREFIX_OF:
         return m_name.isPrefixOf(name);
       case RELATION_IS_STRICT_PREFIX_OF:
-        return (m_name.isPrefixOf(name) && m_name != name);
+        return (m_name.isPrefixOf(name) && m_name.size() < name.size());
       default:
         return false;
       }
@@ -124,20 +132,11 @@
   {
   }
 
+protected:
   virtual bool
-  match(const Data& data)
+  matchName(const Name& name)
   {
-    return m_regex.match(data.getName());
-  }
-
-  virtual bool
-  match(const Interest& interest)
-  {
-    if (interest.getName().size() < 2)
-      return false;
-
-    Name signedName = interest.getName().getPrefix(-2);
-    return m_regex.match(signedName);
+    return m_regex.match(name);
   }
 
 private:
diff --git a/src/security/conf/key-locator-checker.hpp b/src/security/conf/key-locator-checker.hpp
index 21ff8b6..52cf888 100644
--- a/src/security/conf/key-locator-checker.hpp
+++ b/src/security/conf/key-locator-checker.hpp
@@ -27,6 +27,7 @@
 #include "../../common.hpp"
 #include "../../data.hpp"
 #include "../../interest.hpp"
+#include "../security-common.hpp"
 #include <boost/algorithm/string.hpp>
 
 #include "common.hpp"
@@ -37,6 +38,15 @@
 
 class KeyLocatorCheckerFactory;
 
+/**
+ * @brief KeyLocatorChecker is one of the classes used by ValidatorConfig.
+ *
+ * The ValidatorConfig class consists of a set of rules.
+ * The KeyLocatorChecker class is part of a rule and is used to check if the KeyLocator field of a
+ * packet satisfy the requirements.
+ */
+
+
 class KeyLocatorChecker
 {
 public:
@@ -65,13 +75,13 @@
         const KeyLocator& keyLocator,
         std::string& failInfo)
   {
-    if (interest.getName().size() < 2)
+    if (interest.getName().size() < signed_interest::MIN_LENGTH)
       {
         failInfo = "No Signature";
         return false;
       }
 
-    Name signedName = interest.getName().getPrefix(-2);
+    Name signedName = interest.getName().getPrefix(-signed_interest::MIN_LENGTH);
     return check(signedName, keyLocator, failInfo);
   }
 
diff --git a/src/security/key-chain.cpp b/src/security/key-chain.cpp
index 240bab6..22a25b3 100644
--- a/src/security/key-chain.cpp
+++ b/src/security/key-chain.cpp
@@ -41,6 +41,7 @@
 KeyChain::KeyChain()
   : m_pib(0)
   , m_tpm(0)
+  , m_lastTimestamp(time::toUnixTimestamp(time::system_clock::now()))
 {
 
   ConfigFile config;
@@ -102,6 +103,7 @@
                    const std::string& tpmName)
   : m_pib(0)
   , m_tpm(0)
+  , m_lastTimestamp(time::toUnixTimestamp(time::system_clock::now()))
 {
   if (pibName == "sqlite3")
     m_pib = new SecPublicInfoSqlite3;
diff --git a/src/security/key-chain.hpp b/src/security/key-chain.hpp
index 191eeda..043f437 100644
--- a/src/security/key-chain.hpp
+++ b/src/security/key-chain.hpp
@@ -32,6 +32,7 @@
 
 #include "../interest.hpp"
 #include "../util/crypto.hpp"
+#include "../util/random.hpp"
 
 
 namespace ndn {
@@ -680,6 +681,7 @@
 private:
   SecPublicInfo* m_pib;
   SecTpm* m_tpm;
+  time::milliseconds m_lastTimestamp;
 };
 
 template<class T>
@@ -687,6 +689,7 @@
 KeyChain::KeyChain(T)
   : m_pib(new typename T::Pib)
   , m_tpm(new typename T::Tpm)
+  , m_lastTimestamp(time::toUnixTimestamp(time::system_clock::now()))
 {
 }
 
@@ -917,15 +920,24 @@
 KeyChain::signPacketWrapper(Interest& interest, const SignatureSha256WithRsa& signature,
                             const Name& keyName, DigestAlgorithm digestAlgorithm)
 {
+  time::milliseconds timestamp = time::toUnixTimestamp(time::system_clock::now());
+  if (timestamp <= m_lastTimestamp)
+    {
+      timestamp = m_lastTimestamp + time::milliseconds(1);
+    }
+
   Name signedName = interest.getName();
-  signedName.append(signature.getInfo());
+  signedName
+    .append(name::Component::fromNumber(timestamp.count()))        // timestamp
+    .append(name::Component::fromNumber(random::generateWord64())) // nonce
+    .append(signature.getInfo());                                  // signatureInfo
 
   Block sigValue = m_tpm->signInTpm(signedName.wireEncode().value(),
                                     signedName.wireEncode().value_size(),
                                     keyName,
                                     digestAlgorithm);
   sigValue.encode();
-  signedName.append(sigValue);
+  signedName.append(sigValue);                                     // signatureValue
   interest.setName(signedName);
 }
 
diff --git a/src/security/security-common.hpp b/src/security/security-common.hpp
index 072ea74..f795863 100644
--- a/src/security/security-common.hpp
+++ b/src/security/security-common.hpp
@@ -24,6 +24,19 @@
 
 namespace ndn {
 
+namespace signed_interest{
+
+enum {
+  POS_SIG_VALUE = -1,
+  POS_SIG_INFO = -2,
+  POS_RANDOM_VAL = -3,
+  POS_TIMESTAMP = -4,
+
+  MIN_LENGTH = 4
+};
+
+} // namespace signed_interest
+
 enum KeyType {
   KEY_TYPE_RSA,
   KEY_TYPE_ECDSA,
@@ -59,6 +72,6 @@
   ACL_TYPE_PRIVATE
 };
 
-}
+} // namespace ndn
 
 #endif
diff --git a/src/security/validator-config.cpp b/src/security/validator-config.cpp
index a0a35d8..4589d82 100644
--- a/src/security/validator-config.cpp
+++ b/src/security/validator-config.cpp
@@ -32,14 +32,23 @@
 namespace ndn {
 
 const shared_ptr<CertificateCache> ValidatorConfig::DEFAULT_CERTIFICATE_CACHE;
+const time::milliseconds ValidatorConfig::DEFAULT_GRACE_INTERVAL(3000);
+const time::system_clock::Duration ValidatorConfig::DEFAULT_KEY_TIMESTAMP_TTL = time::hours(1);
 
 ValidatorConfig::ValidatorConfig(Face& face,
                                  const shared_ptr<CertificateCache>& certificateCache,
-                                 const int stepLimit)
+                                 const time::milliseconds& graceInterval,
+                                 const size_t stepLimit,
+                                 const size_t maxTrackedKeys,
+                                 const time::system_clock::Duration& keyTimestampTtl)
   : Validator(face)
   , m_shouldValidate(true)
   , m_stepLimit(stepLimit)
   , m_certificateCache(certificateCache)
+  , m_graceInterval(graceInterval < time::milliseconds::zero() ?
+                    DEFAULT_GRACE_INTERVAL : graceInterval)
+  , m_maxTrackedKeys(maxTrackedKeys)
+  , m_keyTimestampTtl(keyTimestampTtl)
 {
   if (!static_cast<bool>(m_certificateCache))
     m_certificateCache = make_shared<CertificateCacheTtl>(ref(m_face.getIoService()));
@@ -469,33 +478,172 @@
   if (!m_shouldValidate)
     return onValidated(interest.shared_from_this());
 
-  bool isMatched = false;
-  int8_t checkResult = -1;
+  // If interestName has less than 4 name components,
+  // it is definitely not a signed interest.
+  if (interest.getName().size() < signed_interest::MIN_LENGTH)
+    return onValidationFailed(interest.shared_from_this(),
+                              "Interest is not signed: " + interest.getName().toUri());
 
-  for (InterestRuleList::iterator it = m_interestRules.begin();
-       it != m_interestRules.end(); it++)
-    {
-      if ((*it)->match(interest))
-        {
-          isMatched = true;
-          checkResult = (*it)->check(interest, onValidated, onValidationFailed);
-          break;
-        }
-    }
-
-  if (!isMatched)
-    return onValidationFailed(interest.shared_from_this(), "No rule matched!");
-
-  if (checkResult == 0)
+  try
     {
       const Name& interestName = interest.getName();
-      Name signedName = interestName.getPrefix(-2);
-      Signature signature(interestName[-2].blockFromValue(),
-                          interestName[-1].blockFromValue());
+      Signature signature(interestName[signed_interest::POS_SIG_INFO].blockFromValue(),
+                          interestName[signed_interest::POS_SIG_VALUE].blockFromValue());
 
-      checkSignature(interest, signature, nSteps,
-                     onValidated, onValidationFailed, nextSteps);
+      if (signature.getType() != Signature::Sha256WithRsa)
+        return onValidationFailed(interest.shared_from_this(),
+                                  "Require SignatureSha256WithRsa");
+
+      SignatureSha256WithRsa sig(signature);
+
+      const KeyLocator& keyLocator = sig.getKeyLocator();
+
+      if (keyLocator.getType() != KeyLocator::KeyLocator_Name)
+        return onValidationFailed(interest.shared_from_this(),
+                                  "Key Locator is not a name");
+
+      Name keyName = IdentityCertificate::certificateNameToPublicKeyName(keyLocator.getName());
+
+      bool isMatched = false;
+      int8_t checkResult = -1;
+
+      for (InterestRuleList::iterator it = m_interestRules.begin();
+           it != m_interestRules.end(); it++)
+        {
+          if ((*it)->match(interest))
+            {
+              isMatched = true;
+              checkResult = (*it)->check(interest,
+                                         bind(&ValidatorConfig::checkTimestamp, this, _1,
+                                              keyName, onValidated, onValidationFailed),
+                                         onValidationFailed);
+              break;
+            }
+        }
+
+      if (!isMatched)
+        return onValidationFailed(interest.shared_from_this(), "No rule matched!");
+
+      if (checkResult == 0)
+        {
+          checkSignature<Interest, OnInterestValidated, OnInterestValidationFailed>
+            (interest, signature, nSteps,
+             bind(&ValidatorConfig::checkTimestamp, this, _1,
+                  keyName, onValidated, onValidationFailed),
+             onValidationFailed,
+             nextSteps);
+        }
     }
+  catch (Signature::Error& e)
+    {
+      return onValidationFailed(interest.shared_from_this(),
+                                "No valid signature");
+    }
+  catch (Tlv::Error& e)
+    {
+      return onValidationFailed(interest.shared_from_this(),
+                                "Cannot decode signature");
+    }
+  catch (KeyLocator::Error& e)
+    {
+      return onValidationFailed(interest.shared_from_this(),
+                                "No valid KeyLocator");
+    }
+  catch (IdentityCertificate::Error& e)
+    {
+      return onValidationFailed(interest.shared_from_this(),
+                                "Cannot determine the signing key");
+    }
+}
+
+void
+ValidatorConfig::checkTimestamp(const shared_ptr<const Interest>& interest,
+                                const Name& keyName,
+                                const OnInterestValidated& onValidated,
+                                const OnInterestValidationFailed& onValidationFailed)
+{
+  const Name& interestName = interest->getName();
+  time::system_clock::TimePoint interestTime;
+
+  try
+    {
+      interestTime =
+        time::fromUnixTimestamp(
+          time::milliseconds(interestName.get(-signed_interest::MIN_LENGTH).toNumber()));
+    }
+  catch (Tlv::Error& e)
+    {
+      return onValidationFailed(interest,
+                                "Cannot decode signature related TLVs");
+    }
+
+  time::system_clock::TimePoint currentTime = time::system_clock::now();
+
+  LastTimestampMap::iterator timestampIt = m_lastTimestamp.find(keyName);
+  if (timestampIt == m_lastTimestamp.end())
+    {
+      if (!(currentTime - m_graceInterval <= interestTime &&
+            interestTime <= currentTime + m_graceInterval))
+        return onValidationFailed(interest,
+                                  "The command is not in grace interval: " +
+                                  interest->getName().toUri());
+    }
+  else
+    {
+      if (interestTime <= timestampIt->second)
+        return onValidationFailed(interest,
+                                  "The command is outdated: " +
+                                  interest->getName().toUri());
+    }
+
+  //Update timestamp
+  if (timestampIt == m_lastTimestamp.end())
+    {
+      cleanOldKeys();
+      m_lastTimestamp[keyName] = interestTime;
+    }
+  else
+    {
+      timestampIt->second = interestTime;
+    }
+
+  return onValidated(interest);
+}
+
+void
+ValidatorConfig::cleanOldKeys()
+{
+  if (m_lastTimestamp.size() < m_maxTrackedKeys)
+    return;
+
+  LastTimestampMap::iterator timestampIt = m_lastTimestamp.begin();
+  LastTimestampMap::iterator end = m_lastTimestamp.end();
+
+  time::system_clock::TimePoint now = time::system_clock::now();
+  LastTimestampMap::iterator oldestKeyIt = m_lastTimestamp.begin();
+  time::system_clock::TimePoint oldestTimestamp = oldestKeyIt->second;
+
+  while (timestampIt != end)
+    {
+      if (now - timestampIt->second > m_keyTimestampTtl)
+        {
+          LastTimestampMap::iterator toDelete = timestampIt;
+          timestampIt++;
+          m_lastTimestamp.erase(toDelete);
+          continue;
+        }
+
+      if (timestampIt->second < oldestTimestamp)
+        {
+          oldestTimestamp = timestampIt->second;
+          oldestKeyIt = timestampIt;
+        }
+
+      timestampIt++;
+    }
+
+  if (m_lastTimestamp.size() >= m_maxTrackedKeys)
+    m_lastTimestamp.erase(oldestKeyIt);
 }
 
 void
diff --git a/src/security/validator-config.hpp b/src/security/validator-config.hpp
index f768efc..f5882d6 100644
--- a/src/security/validator-config.hpp
+++ b/src/security/validator-config.hpp
@@ -46,11 +46,16 @@
   };
 
   static const shared_ptr<CertificateCache> DEFAULT_CERTIFICATE_CACHE;
+  static const time::milliseconds DEFAULT_GRACE_INTERVAL;
+  static const time::system_clock::Duration DEFAULT_KEY_TIMESTAMP_TTL;
 
   explicit
   ValidatorConfig(Face& face,
                   const shared_ptr<CertificateCache>& certificateCache = DEFAULT_CERTIFICATE_CACHE,
-                  const int stepLimit = 10);
+                  const time::milliseconds& graceInterval = DEFAULT_GRACE_INTERVAL,
+                  const size_t stepLimit = 10,
+                  const size_t maxTrackedKeys = 1000,
+                  const time::system_clock::Duration& keyTimestampTtl = DEFAULT_KEY_TIMESTAMP_TTL);
 
   virtual
   ~ValidatorConfig()
@@ -96,11 +101,17 @@
   void
   checkSignature(const Packet& packet,
                  const Signature& signature,
-                 int nSteps,
+                 size_t nSteps,
                  const OnValidated& onValidated,
                  const OnFailed& onValidationFailed,
                  std::vector<shared_ptr<ValidationRequest> >& nextSteps);
 
+  void
+  checkTimestamp(const shared_ptr<const Interest>& interest,
+                 const Name& keyName,
+                 const OnInterestValidated& onValidated,
+                 const OnInterestValidationFailed& onValidationFailed);
+
   template<class Packet, class OnValidated, class OnFailed>
   void
   onCertValidated(const shared_ptr<const Data>& signCertificate,
@@ -132,6 +143,17 @@
   void
   refreshAnchors();
 
+  void
+  cleanOldKeys();
+
+#ifdef NDN_CXX_HAVE_TESTS
+  size_t
+  getTimestampMapSize()
+  {
+    return m_lastTimestamp.size();
+  }
+#endif
+
 
 private:
 
@@ -220,7 +242,7 @@
    */
   bool m_shouldValidate;
 
-  int m_stepLimit;
+  size_t m_stepLimit;
   shared_ptr<CertificateCache> m_certificateCache;
 
   InterestRuleList m_interestRules;
@@ -230,6 +252,11 @@
   TrustAnchorContainer m_staticContainer;
   DynamicContainers m_dynamicContainers;
 
+  time::milliseconds m_graceInterval;
+  size_t m_maxTrackedKeys;
+  typedef std::map<Name, time::system_clock::TimePoint> LastTimestampMap;
+  LastTimestampMap m_lastTimestamp;
+  const time::system_clock::Duration& m_keyTimestampTtl;
 };
 
 inline void
@@ -261,7 +288,7 @@
 void
 ValidatorConfig::checkSignature(const Packet& packet,
                                 const Signature& signature,
-                                int nSteps,
+                                size_t nSteps,
                                 const OnValidated& onValidated,
                                 const OnFailed& onValidationFailed,
                                 std::vector<shared_ptr<ValidationRequest> >& nextSteps)
diff --git a/src/util/command-interest-generator.hpp b/src/util/command-interest-generator.hpp
index 9d69228..8f97b7b 100644
--- a/src/util/command-interest-generator.hpp
+++ b/src/util/command-interest-generator.hpp
@@ -65,44 +65,16 @@
 CommandInterestGenerator::generate(Interest& interest,
                                    const Name& certificateName /*= Name()*/)
 {
-  time::milliseconds timestamp = time::toUnixTimestamp(time::system_clock::now());
-  while (timestamp <= m_lastTimestamp)
-    {
-      timestamp += time::milliseconds(1);
-    }
-
-  Name commandInterestName = interest.getName();
-  commandInterestName
-    .append(name::Component::fromNumber(timestamp.count()))
-    .append(name::Component::fromNumber(random::generateWord64()));
-  interest.setName(commandInterestName);
-
   if (certificateName.empty())
     m_keyChain.sign(interest);
   else
     m_keyChain.sign(interest, certificateName);
-
-  m_lastTimestamp = timestamp;
 }
 
 inline void
 CommandInterestGenerator::generateWithIdentity(Interest& interest, const Name& identity)
 {
-  time::milliseconds timestamp = time::toUnixTimestamp(time::system_clock::now());
-  while (timestamp <= m_lastTimestamp)
-    {
-      timestamp += time::milliseconds(1);
-    }
-
-  Name commandInterestName = interest.getName();
-  commandInterestName
-    .append(name::Component::fromNumber(timestamp.count()))
-    .append(name::Component::fromNumber(random::generateWord64()));
-  interest.setName(commandInterestName);
-
   m_keyChain.signByIdentity(interest, identity);
-
-  m_lastTimestamp = timestamp;
 }
 
 
diff --git a/tests/integrated/test-validator-config.cpp b/tests/integrated/test-validator-config.cpp
index 800fc2a..eb3f4bf 100644
--- a/tests/integrated/test-validator-config.cpp
+++ b/tests/integrated/test-validator-config.cpp
@@ -662,11 +662,11 @@
   boost::filesystem::remove(CERT_PATH);
 }
 
-BOOST_AUTO_TEST_CASE(FixedSingerChecker)
+BOOST_AUTO_TEST_CASE(FixedSignerChecker)
 {
   KeyChain keyChain;
 
-  Name identity("/TestValidatorConfig/FixedSingerChecker");
+  Name identity("/TestValidatorConfig/FixedSignerChecker");
 
   Name identity1 = identity;
   identity1.append("1").appendVersion();
@@ -689,18 +689,18 @@
   shared_ptr<Data> data2 = make_shared<Data>(dataName2);
   BOOST_CHECK_NO_THROW(keyChain.signByIdentity(*data2, identity2));
 
-  Name interestName("/TestValidatorConfig/FixedSingerChecker/fakeSigInfo/fakeSigValue");
+  Name interestName("/TestValidatorConfig/FixedSignerChecker/fakeSigInfo/fakeSigValue");
   shared_ptr<Interest> interest = make_shared<Interest>(interestName);
 
   const std::string CONFIG =
     "rule\n"
     "{\n"
-    "  id \"FixedSingerChecker Data Rule\"\n"
+    "  id \"FixedSignerChecker Data Rule\"\n"
     "  for data\n"
     "  filter"
     "  {\n"
     "    type name\n"
-    "    name /TestValidatorConfig/FixedSingerChecker\n"
+    "    name /TestValidatorConfig/FixedSignerChecker\n"
     "    relation is-strict-prefix-of\n"
     "  }\n"
     "  checker\n"
@@ -716,12 +716,12 @@
     "}\n"
     "rule\n"
     "{\n"
-    "  id \"FixedSingerChecker Interest Rule\"\n"
+    "  id \"FixedSignerChecker Interest Rule\"\n"
     "  for interest\n"
     "  filter"
     "  {\n"
     "    type name\n"
-    "    name /TestValidatorConfig/FixedSingerChecker\n"
+    "    name /TestValidatorConfig/FixedSignerChecker\n"
     "    relation is-strict-prefix-of\n"
     "  }\n"
     "  checker\n"
@@ -816,7 +816,7 @@
                                          RegisterPrefixSuccessCallback(),
                                          bind(&FacesFixture::onRegFailed, this));
 
-  Name interestName1("/localhost/nrd/register/option/timestamp/nonce");
+  Name interestName1("/localhost/nrd/register/option");
   shared_ptr<Interest> interest1 = make_shared<Interest>(interestName1);
   BOOST_CHECK_NO_THROW(keyChain.signByIdentity(*interest1, nld));
 
@@ -824,7 +824,7 @@
   shared_ptr<Interest> interest2 = make_shared<Interest>(interestName2);
   BOOST_CHECK_NO_THROW(keyChain.signByIdentity(*interest2, nld));
 
-  Name interestName3("/localhost/nrd/register/option/timestamp/nonce");
+  Name interestName3("/localhost/nrd/register/option");
   shared_ptr<Interest> interest3 = make_shared<Interest>(interestName3);
   BOOST_CHECK_NO_THROW(keyChain.signByIdentity(*interest3, root));
 
@@ -839,7 +839,7 @@
     "  filter\n"
     "  {\n"
     "    type name\n"
-    "    regex ^<localhost><nrd>[<register><unregister><advertise><withdraw>]<>{3}$\n"
+    "    regex ^<localhost><nrd>[<register><unregister><advertise><withdraw>]<>$\n"
     "  }\n"
     "  checker\n"
     "  {\n"
@@ -927,7 +927,7 @@
     "  filter\n"
     "  {\n"
     "    type name\n"
-    "    regex ^<localhost><nrd>[<register><unregister><advertise><withdraw>]<>{3}$\n"
+    "    regex ^<localhost><nrd>[<register><unregister><advertise><withdraw>]<>$\n"
     "  }\n"
     "  checker\n"
     "  {\n"
@@ -1018,7 +1018,8 @@
 {
   DirTestFixture()
     : m_scheduler(m_face.getIoService())
-    , m_validator(m_face, ValidatorConfig::DEFAULT_CERTIFICATE_CACHE, 0)
+    , m_validator(m_face, ValidatorConfig::DEFAULT_CERTIFICATE_CACHE,
+                  ValidatorConfig::DEFAULT_GRACE_INTERVAL, 0)
   {
     m_certDirPath = (boost::filesystem::current_path() / std::string("test-cert-dir"));
     boost::filesystem::create_directory(m_certDirPath);
@@ -1162,6 +1163,387 @@
 }
 
 
+BOOST_AUTO_TEST_CASE(SignedInterestTest)
+{
+  KeyChain keyChain;
+
+  Name identity("/TestValidatorConfig/SignedInterestTest");
+
+  Name identity1 = identity;
+  identity1.appendVersion();
+  BOOST_REQUIRE_NO_THROW(keyChain.createIdentity(identity1));
+  Name certName1 = keyChain.getDefaultCertificateNameForIdentity(identity1);
+  shared_ptr<IdentityCertificate> idCert1 = keyChain.getCertificate(certName1);
+  io::save(*idCert1, "trust-anchor-9.cert");
+
+  Name interestName("/TestValidatorConfig/SignedInterestTest");
+  Name interestName1 = interestName;
+  interestName1.append("1");
+  shared_ptr<Interest> interest1 = make_shared<Interest>(interestName1);
+  Name interestName2 = interestName;
+  interestName2.append("2");
+  shared_ptr<Interest> interest2 = make_shared<Interest>(interestName2);
+
+  BOOST_CHECK_NO_THROW(keyChain.signByIdentity(*interest1, identity1));
+  usleep(10000);
+  BOOST_CHECK_NO_THROW(keyChain.signByIdentity(*interest2, identity1));
+
+  const std::string CONFIG =
+    "rule\n"
+    "{\n"
+    "  id \"FixedSignerChecker Interest Rule\"\n"
+    "  for interest\n"
+    "  filter"
+    "  {\n"
+    "    type name\n"
+    "    name /TestValidatorConfig/SignedInterestTest\n"
+    "    relation is-strict-prefix-of\n"
+    "  }\n"
+    "  checker\n"
+    "  {\n"
+    "    type fixed-signer\n"
+    "    sig-type rsa-sha256\n"
+    "    signer\n"
+    "    {\n"
+    "      type file\n"
+    "      file-name \"trust-anchor-9.cert\"\n"
+    "    }\n"
+    "  }\n"
+    "}\n";
+  const boost::filesystem::path CONFIG_PATH =
+    (boost::filesystem::current_path() / std::string("unit-test-nfd.conf"));
+
+
+  Face face;
+  ValidatorConfig validator(face);
+  validator.load(CONFIG, CONFIG_PATH.native());
+
+  validator.validate(*interest1,
+                     bind(&onValidated2, _1),
+                     bind(&onValidationFailed2, _1, _2));
+
+  validator.validate(*interest2,
+                     bind(&onValidated2, _1),
+                     bind(&onValidationFailed2, _1, _2));
+
+  validator.validate(*interest1,
+                     bind(&onIntentionalFailureValidated2, _1),
+                     bind(&onIntentionalFailureInvalidated2, _1, _2));
+
+
+  keyChain.deleteIdentity(identity1);
+
+  const boost::filesystem::path CERT_PATH =
+    (boost::filesystem::current_path() / std::string("trust-anchor-9.cert"));
+  boost::filesystem::remove(CERT_PATH);
+}
+
+
+BOOST_AUTO_TEST_CASE(MaxKeyTest)
+{
+
+  KeyChain keyChain;
+
+  Name identity("/TestValidatorConfig/MaxKeyTest");
+
+  Name identity1 = identity;
+  identity1.append("Key1");
+  BOOST_REQUIRE_NO_THROW(keyChain.createIdentity(identity1));
+  Name certName1 = keyChain.getDefaultCertificateNameForIdentity(identity1);
+  shared_ptr<IdentityCertificate> idCert1 = keyChain.getCertificate(certName1);
+  io::save(*idCert1, "trust-anchor-10-1.cert");
+
+  Name identity2 = identity;
+  identity2.append("Key2");
+  BOOST_REQUIRE_NO_THROW(keyChain.createIdentity(identity2));
+  Name certName2 = keyChain.getDefaultCertificateNameForIdentity(identity2);
+  shared_ptr<IdentityCertificate> idCert2 = keyChain.getCertificate(certName2);
+  io::save(*idCert2, "trust-anchor-10-2.cert");
+
+  Name identity3 = identity;
+  identity3.append("Key3");
+  BOOST_REQUIRE_NO_THROW(keyChain.createIdentity(identity3));
+  Name certName3 = keyChain.getDefaultCertificateNameForIdentity(identity3);
+  shared_ptr<IdentityCertificate> idCert3 = keyChain.getCertificate(certName3);
+  io::save(*idCert3, "trust-anchor-10-3.cert");
+
+
+  Name interestName("/TestValidatorConfig/MaxKeyTest");
+  Name interestName1 = interestName;
+  interestName1.append("1");
+  shared_ptr<Interest> interest1 = make_shared<Interest>(interestName1);
+  Name interestName2 = interestName;
+  interestName2.append("2");
+  shared_ptr<Interest> interest2 = make_shared<Interest>(interestName2);
+  Name interestName3 = interestName;
+  interestName3.append("3");
+  shared_ptr<Interest> interest3 = make_shared<Interest>(interestName3);
+
+  BOOST_CHECK_NO_THROW(keyChain.signByIdentity(*interest1, identity1));
+  usleep(10000);
+  BOOST_CHECK_NO_THROW(keyChain.signByIdentity(*interest2, identity2));
+  usleep(10000);
+  BOOST_CHECK_NO_THROW(keyChain.signByIdentity(*interest3, identity3));
+
+  const std::string CONFIG =
+    "rule\n"
+    "{\n"
+    "  id \"FixedSignerChecker Interest Rule\"\n"
+    "  for interest\n"
+    "  filter"
+    "  {\n"
+    "    type name\n"
+    "    name /TestValidatorConfig/MaxKeyTest\n"
+    "    relation is-strict-prefix-of\n"
+    "  }\n"
+    "  checker\n"
+    "  {\n"
+    "    type fixed-signer\n"
+    "    sig-type rsa-sha256\n"
+    "    signer\n"
+    "    {\n"
+    "      type file\n"
+    "      file-name \"trust-anchor-10-1.cert\"\n"
+    "    }\n"
+    "    signer\n"
+    "    {\n"
+    "      type file\n"
+    "      file-name \"trust-anchor-10-2.cert\"\n"
+    "    }\n"
+    "    signer\n"
+    "    {\n"
+    "      type file\n"
+    "      file-name \"trust-anchor-10-3.cert\"\n"
+    "    }\n"
+    "  }\n"
+    "}\n";
+  const boost::filesystem::path CONFIG_PATH =
+    (boost::filesystem::current_path() / std::string("unit-test-nfd.conf"));
+
+
+  Face face;
+  ValidatorConfig validator(face,
+                            ValidatorConfig::DEFAULT_CERTIFICATE_CACHE,
+                            ValidatorConfig::DEFAULT_GRACE_INTERVAL,
+                            10,
+                            2,                 // Two keys can be tracked
+                            time::seconds(1)); // TTL is set to 1 sec
+  validator.load(CONFIG, CONFIG_PATH.native());
+
+  validator.validate(*interest1,
+                     bind(&onValidated2, _1),
+                     bind(&onValidationFailed2, _1, _2));
+
+  validator.validate(*interest2,
+                     bind(&onValidated2, _1),
+                     bind(&onValidationFailed2, _1, _2));
+
+  validator.validate(*interest1,
+                     bind(&onIntentionalFailureValidated2, _1),
+                     bind(&onIntentionalFailureInvalidated2, _1, _2));
+
+  validator.validate(*interest3,
+                     bind(&onValidated2, _1),
+                     bind(&onValidationFailed2, _1, _2));
+
+  // Should succeed because identity1's key has been cleaned up due to space limit.
+  validator.validate(*interest1,
+                     bind(&onValidated2, _1),
+                     bind(&onValidationFailed2, _1, _2));
+
+
+  keyChain.deleteIdentity(identity1);
+  keyChain.deleteIdentity(identity2);
+  keyChain.deleteIdentity(identity3);
+
+  const boost::filesystem::path CERT_PATH1 =
+    (boost::filesystem::current_path() / std::string("trust-anchor-10-1.cert"));
+  boost::filesystem::remove(CERT_PATH1);
+
+  const boost::filesystem::path CERT_PATH2 =
+    (boost::filesystem::current_path() / std::string("trust-anchor-10-2.cert"));
+  boost::filesystem::remove(CERT_PATH2);
+
+  const boost::filesystem::path CERT_PATH3 =
+    (boost::filesystem::current_path() / std::string("trust-anchor-10-3.cert"));
+  boost::filesystem::remove(CERT_PATH3);
+}
+
+BOOST_AUTO_TEST_CASE(MaxKeyTest2)
+{
+
+  KeyChain keyChain;
+
+  Name identity("/TestValidatorConfig/MaxKeyTest");
+
+  Name identity1 = identity;
+  identity1.append("Key1");
+  BOOST_REQUIRE_NO_THROW(keyChain.createIdentity(identity1));
+  Name certName1 = keyChain.getDefaultCertificateNameForIdentity(identity1);
+  shared_ptr<IdentityCertificate> idCert1 = keyChain.getCertificate(certName1);
+  io::save(*idCert1, "trust-anchor-10-1.cert");
+
+  Name identity2 = identity;
+  identity2.append("Key2");
+  BOOST_REQUIRE_NO_THROW(keyChain.createIdentity(identity2));
+  Name certName2 = keyChain.getDefaultCertificateNameForIdentity(identity2);
+  shared_ptr<IdentityCertificate> idCert2 = keyChain.getCertificate(certName2);
+  io::save(*idCert2, "trust-anchor-10-2.cert");
+
+  Name identity3 = identity;
+  identity3.append("Key3");
+  BOOST_REQUIRE_NO_THROW(keyChain.createIdentity(identity3));
+  Name certName3 = keyChain.getDefaultCertificateNameForIdentity(identity3);
+  shared_ptr<IdentityCertificate> idCert3 = keyChain.getCertificate(certName3);
+  io::save(*idCert3, "trust-anchor-10-3.cert");
+
+  Name identity4 = identity;
+  identity4.append("Key4");
+  BOOST_REQUIRE_NO_THROW(keyChain.createIdentity(identity4));
+  Name certName4 = keyChain.getDefaultCertificateNameForIdentity(identity4);
+  shared_ptr<IdentityCertificate> idCert4 = keyChain.getCertificate(certName4);
+  io::save(*idCert4, "trust-anchor-10-4.cert");
+
+
+  Name interestName("/TestValidatorConfig/MaxKeyTest");
+  Name interestName1 = interestName;
+  interestName1.append("1");
+  shared_ptr<Interest> interest1 = make_shared<Interest>(interestName1);
+  Name interestName2 = interestName;
+  interestName2.append("2");
+  shared_ptr<Interest> interest2 = make_shared<Interest>(interestName2);
+  Name interestName3 = interestName;
+  interestName3.append("3");
+  shared_ptr<Interest> interest3 = make_shared<Interest>(interestName3);
+  Name interestName4 = interestName;
+  interestName4.append("4");
+  shared_ptr<Interest> interest4 = make_shared<Interest>(interestName4);
+
+
+  BOOST_CHECK_NO_THROW(keyChain.signByIdentity(*interest1, identity1));
+  usleep(10000);
+  BOOST_CHECK_NO_THROW(keyChain.signByIdentity(*interest2, identity2));
+  usleep(10000);
+  BOOST_CHECK_NO_THROW(keyChain.signByIdentity(*interest3, identity3));
+  usleep(10000);
+  BOOST_CHECK_NO_THROW(keyChain.signByIdentity(*interest4, identity4));
+
+  const std::string CONFIG =
+    "rule\n"
+    "{\n"
+    "  id \"FixedSignerChecker Interest Rule\"\n"
+    "  for interest\n"
+    "  filter"
+    "  {\n"
+    "    type name\n"
+    "    name /TestValidatorConfig/MaxKeyTest\n"
+    "    relation is-strict-prefix-of\n"
+    "  }\n"
+    "  checker\n"
+    "  {\n"
+    "    type fixed-signer\n"
+    "    sig-type rsa-sha256\n"
+    "    signer\n"
+    "    {\n"
+    "      type file\n"
+    "      file-name \"trust-anchor-10-1.cert\"\n"
+    "    }\n"
+    "    signer\n"
+    "    {\n"
+    "      type file\n"
+    "      file-name \"trust-anchor-10-2.cert\"\n"
+    "    }\n"
+    "    signer\n"
+    "    {\n"
+    "      type file\n"
+    "      file-name \"trust-anchor-10-3.cert\"\n"
+    "    }\n"
+    "    signer\n"
+    "    {\n"
+    "      type file\n"
+    "      file-name \"trust-anchor-10-4.cert\"\n"
+    "    }\n"
+    "  }\n"
+    "}\n";
+  const boost::filesystem::path CONFIG_PATH =
+    (boost::filesystem::current_path() / std::string("unit-test-nfd.conf"));
+
+
+  Face face;
+  ValidatorConfig validator(face,
+                            ValidatorConfig::DEFAULT_CERTIFICATE_CACHE,
+                            ValidatorConfig::DEFAULT_GRACE_INTERVAL,
+                            10,
+                            3,                 // Two keys can be tracked
+                            time::seconds(1)); // TTL is set to 1 sec
+  validator.load(CONFIG, CONFIG_PATH.native());
+
+  validator.validate(*interest1,
+                     bind(&onValidated2, _1),
+                     bind(&onValidationFailed2, _1, _2));
+
+  validator.validate(*interest2,
+                     bind(&onValidated2, _1),
+                     bind(&onValidationFailed2, _1, _2));
+
+  validator.validate(*interest3,
+                     bind(&onValidated2, _1),
+                     bind(&onValidationFailed2, _1, _2));
+
+  validator.validate(*interest1,
+                     bind(&onIntentionalFailureValidated2, _1),
+                     bind(&onIntentionalFailureInvalidated2, _1, _2));
+
+  validator.validate(*interest2,
+                     bind(&onIntentionalFailureValidated2, _1),
+                     bind(&onIntentionalFailureInvalidated2, _1, _2));
+
+  validator.validate(*interest3,
+                     bind(&onIntentionalFailureValidated2, _1),
+                     bind(&onIntentionalFailureInvalidated2, _1, _2));
+
+  sleep(2);
+
+  validator.validate(*interest4,
+                     bind(&onValidated2, _1),
+                     bind(&onValidationFailed2, _1, _2));
+
+  // Should succeed because identity1 and identity2's key has been cleaned up due to ttl limit.
+  validator.validate(*interest1,
+                     bind(&onValidated2, _1),
+                     bind(&onValidationFailed2, _1, _2));
+
+  validator.validate(*interest2,
+                     bind(&onValidated2, _1),
+                     bind(&onValidationFailed2, _1, _2));
+
+  validator.validate(*interest3,
+                     bind(&onValidated2, _1),
+                     bind(&onValidationFailed2, _1, _2));
+
+
+  keyChain.deleteIdentity(identity1);
+  keyChain.deleteIdentity(identity2);
+  keyChain.deleteIdentity(identity3);
+  keyChain.deleteIdentity(identity4);
+
+  const boost::filesystem::path CERT_PATH1 =
+    (boost::filesystem::current_path() / std::string("trust-anchor-10-1.cert"));
+  boost::filesystem::remove(CERT_PATH1);
+
+  const boost::filesystem::path CERT_PATH2 =
+    (boost::filesystem::current_path() / std::string("trust-anchor-10-2.cert"));
+  boost::filesystem::remove(CERT_PATH2);
+
+  const boost::filesystem::path CERT_PATH3 =
+    (boost::filesystem::current_path() / std::string("trust-anchor-10-3.cert"));
+  boost::filesystem::remove(CERT_PATH3);
+
+  const boost::filesystem::path CERT_PATH4 =
+    (boost::filesystem::current_path() / std::string("trust-anchor-10-4.cert"));
+  boost::filesystem::remove(CERT_PATH4);
+}
+
 
 BOOST_AUTO_TEST_SUITE_END()
 
diff --git a/tests/unit-tests/security/test-signed-interest.cpp b/tests/unit-tests/security/test-signed-interest.cpp
index 8d675fc..7c3084e 100644
--- a/tests/unit-tests/security/test-signed-interest.cpp
+++ b/tests/unit-tests/security/test-signed-interest.cpp
@@ -22,9 +22,6 @@
 #include "security/key-chain.hpp"
 #include "security/validator.hpp"
 
-#include "util/command-interest-generator.hpp"
-#include "util/command-interest-validator.hpp"
-
 #include "boost-test.hpp"
 
 using namespace std;
@@ -32,7 +29,7 @@
 
 BOOST_AUTO_TEST_SUITE(SecurityTestSignedInterest)
 
-BOOST_AUTO_TEST_CASE(SignedInterest)
+BOOST_AUTO_TEST_CASE(SignVerifyInterest)
 {
   BOOST_REQUIRE_NO_THROW(KeyChain("sqlite3", "file"));
   KeyChain keyChain("sqlite3", "file");
@@ -46,6 +43,25 @@
   Interest interest("/TestSignedInterest/SignVerify/Interest1");
   BOOST_CHECK_NO_THROW(keyChain.signByIdentity(interest, identityName));
 
+  usleep(100000);
+
+  Interest interest11("/TestSignedInterest/SignVerify/Interest1");
+  BOOST_CHECK_NO_THROW(keyChain.signByIdentity(interest11, identityName));
+
+  time::system_clock::TimePoint timestamp1 =
+    time::fromUnixTimestamp(
+      time::milliseconds(interest.getName().get(signed_interest::POS_TIMESTAMP).toNumber()));
+
+  time::system_clock::TimePoint timestamp2 =
+    time::fromUnixTimestamp(
+      time::milliseconds(interest11.getName().get(signed_interest::POS_TIMESTAMP).toNumber()));
+
+  BOOST_CHECK_LT(time::milliseconds(100), (timestamp2 - timestamp1));
+
+  uint64_t nonce1 = interest.getName().get(signed_interest::POS_RANDOM_VAL).toNumber();
+  uint64_t nonce2 = interest11.getName().get(signed_interest::POS_RANDOM_VAL).toNumber();
+  BOOST_CHECK_NE(nonce1, nonce2);
+
   Block interestBlock(interest.wireEncode().wire(), interest.wireEncode().size());
 
   Interest interest2;
@@ -61,133 +77,6 @@
   keyChain.deleteIdentity(identityName);
 }
 
-class CommandInterestFixture
-{
-public:
-  CommandInterestFixture()
-    : m_validity(false)
-  {
-  }
-
-  void
-  validated(const shared_ptr<const Interest>& interest)
-  {
-    m_validity = true;
-  }
-
-  void
-  validationFailed(const shared_ptr<const Interest>& interest, const string& failureInfo)
-  {
-    m_validity = false;
-  }
-
-  void
-  reset()
-  {
-    m_validity = false;
-  }
-
-  bool m_validity;
-};
-
-BOOST_FIXTURE_TEST_CASE(CommandInterest, CommandInterestFixture)
-{
-  KeyChain keyChain;
-  Name identity("/TestCommandInterest/Validation");
-  identity.appendVersion();
-
-  Name certName;
-  BOOST_REQUIRE_NO_THROW(certName = keyChain.createIdentity(identity));
-
-  CommandInterestGenerator generator;
-  CommandInterestValidator validator;
-
-  validator.addInterestRule("^<TestCommandInterest><Validation>",
-                            *keyChain.getCertificate(certName));
-
-  //Test a legitimate command
-  shared_ptr<Interest> commandInterest1 =
-    make_shared<Interest>("/TestCommandInterest/Validation/Command1");
-  generator.generateWithIdentity(*commandInterest1, identity);
-  validator.validate(*commandInterest1,
-                     bind(&CommandInterestFixture::validated, this, _1),
-                     bind(&CommandInterestFixture::validationFailed, this, _1, _2));
-
-  BOOST_CHECK_EQUAL(m_validity, true);
-
-  //Test an outdated command
-  reset();
-  shared_ptr<Interest> commandInterest2 =
-    make_shared<Interest>("/TestCommandInterest/Validation/Command2");
-  time::milliseconds timestamp = time::toUnixTimestamp(time::system_clock::now());
-  timestamp -= time::seconds(5);
-
-  Name commandName = commandInterest2->getName();
-  commandName
-    .appendNumber(timestamp.count())
-    .appendNumber(random::generateWord64());
-  commandInterest2->setName(commandName);
-
-  keyChain.signByIdentity(*commandInterest2, identity);
-  validator.validate(*commandInterest2,
-                     bind(&CommandInterestFixture::validated, this, _1),
-                     bind(&CommandInterestFixture::validationFailed, this, _1, _2));
-
-  BOOST_CHECK_EQUAL(m_validity, false);
-
-  //Test an unauthorized command
-  Name identity2("/TestCommandInterest/Validation2");
-  Name certName2;
-  BOOST_REQUIRE_NO_THROW(certName2 = keyChain.createIdentity(identity2));
-
-  shared_ptr<Interest> commandInterest3 =
-    make_shared<Interest>("/TestCommandInterest/Validation/Command3");
-  generator.generateWithIdentity(*commandInterest3, identity2);
-  validator.validate(*commandInterest3,
-                     bind(&CommandInterestFixture::validated, this, _1),
-                     bind(&CommandInterestFixture::validationFailed, this, _1, _2));
-
-  BOOST_CHECK_EQUAL(m_validity, false);
-
-  //Test another unauthorized command
-  shared_ptr<Interest> commandInterest4 =
-    make_shared<Interest>("/TestCommandInterest/Validation2/Command");
-  generator.generateWithIdentity(*commandInterest4, identity);
-  validator.validate(*commandInterest4,
-                     bind(&CommandInterestFixture::validated, this, _1),
-                     bind(&CommandInterestFixture::validationFailed, this, _1, _2));
-
-  BOOST_CHECK_EQUAL(m_validity, false);
-
-  BOOST_CHECK_NO_THROW(keyChain.deleteIdentity(identity));
-  BOOST_CHECK_NO_THROW(keyChain.deleteIdentity(identity2));
-}
-
-BOOST_FIXTURE_TEST_CASE(Exemption, CommandInterestFixture)
-{
-  KeyChain keyChain;
-  Name identity("/TestCommandInterest/AnyKey");
-
-  Name certName;
-  BOOST_REQUIRE_NO_THROW(certName = keyChain.createIdentity(identity));
-
-  CommandInterestGenerator generator;
-  CommandInterestValidator validator;
-
-  validator.addInterestBypassRule("^<TestCommandInterest><Exemption>");
-
-  //Test a legitimate command
-  shared_ptr<Interest> commandInterest1 =
-    make_shared<Interest>("/TestCommandInterest/Exemption/Command1");
-  generator.generateWithIdentity(*commandInterest1, identity);
-  validator.validate(*commandInterest1,
-                     bind(&CommandInterestFixture::validated, this, _1),
-                     bind(&CommandInterestFixture::validationFailed, this, _1, _2));
-
-  BOOST_CHECK_EQUAL(m_validity, true);
-
-  BOOST_CHECK_NO_THROW(keyChain.deleteIdentity(identity));
-}
 
 
 
diff --git a/tests/unit-tests/util/test-command-interest.cpp b/tests/unit-tests/util/test-command-interest.cpp
new file mode 100644
index 0000000..d7f3f6c
--- /dev/null
+++ b/tests/unit-tests/util/test-command-interest.cpp
@@ -0,0 +1,165 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2013-2014 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 "util/command-interest-generator.hpp"
+#include "util/command-interest-validator.hpp"
+
+#include "boost-test.hpp"
+
+namespace ndn {
+
+BOOST_AUTO_TEST_SUITE(SecurityTestCommandInterest)
+
+class CommandInterestFixture
+{
+public:
+  CommandInterestFixture()
+    : m_validity(false)
+  {
+  }
+
+  void
+  validated(const shared_ptr<const Interest>& interest)
+  {
+    m_validity = true;
+  }
+
+  void
+  validationFailed(const shared_ptr<const Interest>& interest, const std::string& failureInfo)
+  {
+    m_validity = false;
+  }
+
+  void
+  reset()
+  {
+    m_validity = false;
+  }
+
+  bool m_validity;
+};
+
+BOOST_FIXTURE_TEST_CASE(CommandInterest, CommandInterestFixture)
+{
+  KeyChain keyChain;
+  Name identity("/TestCommandInterest/Validation");
+  identity.appendVersion();
+
+  Name certName;
+  BOOST_REQUIRE_NO_THROW(certName = keyChain.createIdentity(identity));
+
+  CommandInterestGenerator generator;
+  CommandInterestValidator validator;
+
+  validator.addInterestRule("^<TestCommandInterest><Validation>",
+                            *keyChain.getCertificate(certName));
+
+  //Test a legitimate command
+  shared_ptr<Interest> commandInterest1 =
+    make_shared<Interest>("/TestCommandInterest/Validation/Command1");
+  generator.generateWithIdentity(*commandInterest1, identity);
+  validator.validate(*commandInterest1,
+                     bind(&CommandInterestFixture::validated, this, _1),
+                     bind(&CommandInterestFixture::validationFailed, this, _1, _2));
+
+  BOOST_CHECK_EQUAL(m_validity, true);
+
+  //Test an outdated command
+  reset();
+  shared_ptr<Interest> commandInterest2 =
+    make_shared<Interest>("/TestCommandInterest/Validation/Command2");
+  keyChain.signByIdentity(*commandInterest2, identity);
+
+  sleep(1);
+
+  shared_ptr<Interest> commandInterest21 =
+    make_shared<Interest>("/TestCommandInterest/Validation/Command3");
+  keyChain.signByIdentity(*commandInterest21, identity);
+
+  reset();
+  validator.validate(*commandInterest21,
+                     bind(&CommandInterestFixture::validated, this, _1),
+                     bind(&CommandInterestFixture::validationFailed, this, _1, _2));
+  BOOST_CHECK_EQUAL(m_validity, true);
+
+  reset();
+  validator.validate(*commandInterest2,
+                     bind(&CommandInterestFixture::validated, this, _1),
+                     bind(&CommandInterestFixture::validationFailed, this, _1, _2));
+  BOOST_CHECK_EQUAL(m_validity, false);
+
+  //Test an unauthorized command
+  Name identity2("/TestCommandInterest/Validation2");
+  Name certName2;
+  BOOST_REQUIRE_NO_THROW(certName2 = keyChain.createIdentity(identity2));
+
+  shared_ptr<Interest> commandInterest3 =
+    make_shared<Interest>("/TestCommandInterest/Validation/Command3");
+  generator.generateWithIdentity(*commandInterest3, identity2);
+  validator.validate(*commandInterest3,
+                     bind(&CommandInterestFixture::validated, this, _1),
+                     bind(&CommandInterestFixture::validationFailed, this, _1, _2));
+
+  BOOST_CHECK_EQUAL(m_validity, false);
+
+  //Test another unauthorized command
+  shared_ptr<Interest> commandInterest4 =
+    make_shared<Interest>("/TestCommandInterest/Validation2/Command");
+  generator.generateWithIdentity(*commandInterest4, identity);
+  validator.validate(*commandInterest4,
+                     bind(&CommandInterestFixture::validated, this, _1),
+                     bind(&CommandInterestFixture::validationFailed, this, _1, _2));
+
+  BOOST_CHECK_EQUAL(m_validity, false);
+
+  BOOST_CHECK_NO_THROW(keyChain.deleteIdentity(identity));
+  BOOST_CHECK_NO_THROW(keyChain.deleteIdentity(identity2));
+}
+
+BOOST_FIXTURE_TEST_CASE(Exemption, CommandInterestFixture)
+{
+  KeyChain keyChain;
+  Name identity("/TestCommandInterest/AnyKey");
+
+  Name certName;
+  BOOST_REQUIRE_NO_THROW(certName = keyChain.createIdentity(identity));
+
+  CommandInterestGenerator generator;
+  CommandInterestValidator validator;
+
+  validator.addInterestBypassRule("^<TestCommandInterest><Exemption>");
+
+  //Test a legitimate command
+  shared_ptr<Interest> commandInterest1 =
+    make_shared<Interest>("/TestCommandInterest/Exemption/Command1");
+  generator.generateWithIdentity(*commandInterest1, identity);
+  validator.validate(*commandInterest1,
+                     bind(&CommandInterestFixture::validated, this, _1),
+                     bind(&CommandInterestFixture::validationFailed, this, _1, _2));
+
+  BOOST_CHECK_EQUAL(m_validity, true);
+
+  BOOST_CHECK_NO_THROW(keyChain.deleteIdentity(identity));
+}
+
+BOOST_AUTO_TEST_SUITE_END()
+
+}