security: refactor CertificateStore class

Refs: #5075

Change-Id: I8ab92012b3acf405503ab33c9320463accc682a9
diff --git a/src/conf-file-processor.cpp b/src/conf-file-processor.cpp
index dc422f5..b893bf8 100644
--- a/src/conf-file-processor.cpp
+++ b/src/conf-file-processor.cpp
@@ -1,6 +1,6 @@
 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
 /**
- * Copyright (c) 2014-2019,  The University of Memphis,
+ * Copyright (c) 2014-2020,  The University of Memphis,
  *                           Regents of the University of California,
  *                           Arizona Board of Regents.
  *
@@ -152,6 +152,12 @@
   }
   ret = load(inputFile);
   inputFile.close();
+
+  if (ret) {
+    m_confParam.buildRouterAndSyncUserPrefix();
+    m_confParam.writeLog();
+  }
+
   return ret;
 }
 
@@ -656,12 +662,8 @@
         std::cerr << "Error: Cannot load cert-to-publish: " << file << "!" << std::endl;
         return false;
       }
-
-      m_confParam.getCertStore().insert(*idCert);
-      m_confParam.getValidator().loadAnchor("Authoritative-Certificate",
-                                            ndn::security::v2::Certificate(*idCert));
-      m_confParam.getPrefixUpdateValidator().loadAnchor("Authoritative-Certificate",
-                                                        ndn::security::v2::Certificate(*idCert));
+      m_confParam.addCertPath(certfilePath.string());
+      m_confParam.loadCertToValidator(*idCert);
     }
   }
 
diff --git a/src/conf-parameter.cpp b/src/conf-parameter.cpp
index 4938a8e..51e4303 100644
--- a/src/conf-parameter.cpp
+++ b/src/conf-parameter.cpp
@@ -1,6 +1,6 @@
 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
 /**
- * Copyright (c) 2014-2019,  The University of Memphis,
+ * Copyright (c) 2014-2020,  The University of Memphis,
  *                           Regents of the University of California
  *
  * This file is part of NLSR (Named-data Link State Routing).
@@ -16,9 +16,6 @@
  *
  * You should have received a copy of the GNU General Public License along with
  * NLSR, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
- *
- * \author A K M Mahmudul Hoque <ahoque1@memphis.edu>
- *
  **/
 
 #include "conf-parameter.hpp"
@@ -28,8 +25,10 @@
 
 INIT_LOGGER(ConfParameter);
 
+using namespace ndn::time_literals;
+
 // To be changed when breaking changes are made to sync
-const uint64_t ConfParameter::SYNC_VERSION = 7;
+const uint64_t ConfParameter::SYNC_VERSION = 8;
 
 static std::unique_ptr<ndn::security::v2::CertificateFetcherDirectFetch>
 makeCertificateFetcher(ndn::Face& face)
@@ -39,7 +38,8 @@
   return fetcher;
 }
 
-ConfParameter::ConfParameter(ndn::Face& face, const std::string& confFileName)
+ConfParameter::ConfParameter(ndn::Face& face, ndn::KeyChain& keyChain,
+                             const std::string& confFileName)
   : m_confFileName(confFileName)
   , m_lsaRefreshTime(LSA_REFRESH_TIME_DEFAULT)
   , m_adjLsaBuildInterval(ADJ_LSA_BUILD_INTERVAL_DEFAULT)
@@ -59,6 +59,7 @@
   , m_npl()
   , m_validator(makeCertificateFetcher(face))
   , m_prefixUpdateValidator(std::make_unique<ndn::security::v2::CertificateFetcherDirectFetch>(face))
+  , m_keyChain(keyChain)
 {
 }
 
@@ -111,4 +112,78 @@
   m_lsaPrefix.append("LSA");
 }
 
+void
+ConfParameter::loadCertToValidator(const ndn::security::v2::Certificate& cert)
+{
+  NLSR_LOG_TRACE("Loading Certificate Name: " << cert.getName());
+  m_validator.loadAnchor("Authoritative-Certificate", ndn::security::v2::Certificate(cert));
+  m_prefixUpdateValidator.loadAnchor("Authoritative-Certificate", ndn::security::v2::Certificate(cert));
+}
+
+shared_ptr<ndn::security::v2::Certificate>
+ConfParameter::initializeKey()
+{
+  NLSR_LOG_DEBUG("Initializing Key ...");
+
+  ndn::Name nlsrInstanceName(m_routerPrefix);
+  nlsrInstanceName.append("nlsr");
+
+  try {
+    m_keyChain.deleteIdentity(m_keyChain.getPib().getIdentity(nlsrInstanceName));
+  }
+  catch (const std::exception& e) {
+    NLSR_LOG_WARN(e.what());
+  }
+
+  ndn::security::Identity nlsrInstanceIdentity;
+  try {
+    nlsrInstanceIdentity = m_keyChain.createIdentity(nlsrInstanceName);
+  }
+  catch (const std::exception& e) {
+    NLSR_LOG_ERROR(e.what());
+    NLSR_LOG_ERROR("Unable to create identity, NLSR will run without security!");
+    NLSR_LOG_ERROR("Can be ignored if running in non-production environments.");
+    return nullptr;
+  }
+  auto certificate = std::make_shared<ndn::security::v2::Certificate>();
+  auto nlsrInstanceKey = nlsrInstanceIdentity.getDefaultKey();
+  ndn::Name certificateName = nlsrInstanceKey.getName();
+  certificateName.append("NA");
+  certificateName.appendVersion();
+
+  certificate->setName(certificateName);
+
+  // set metainfo
+  certificate->setContentType(ndn::tlv::ContentType_Key);
+  certificate->setFreshnessPeriod(365_days);
+
+  // set content
+  certificate->setContent(nlsrInstanceKey.getPublicKey().data(),
+                          nlsrInstanceKey.getPublicKey().size());
+
+  // set signature-info
+  ndn::SignatureInfo signatureInfo;
+  signatureInfo.setValidityPeriod(ndn::security::ValidityPeriod(ndn::time::system_clock::TimePoint(),
+                                                                ndn::time::system_clock::now()
+                                                                + 365_days));
+
+  try {
+    m_keyChain.sign(*certificate,
+                    ndn::security::SigningInfo(m_keyChain.getPib().getIdentity(m_routerPrefix))
+                                               .setSignatureInfo(signatureInfo));
+  }
+  catch (const std::exception& e) {
+    NLSR_LOG_ERROR("Router's " << e.what() << ", NLSR is running without security. " <<
+                   "If security is enabled in the configuration, NLSR will not converge.");
+
+  }
+
+  m_signingInfo = ndn::security::SigningInfo(ndn::security::SigningInfo::SIGNER_TYPE_ID,
+                                             nlsrInstanceName);
+
+  loadCertToValidator(*certificate);
+
+  return certificate;
+}
+
 } // namespace nlsr
diff --git a/src/conf-parameter.hpp b/src/conf-parameter.hpp
index 7848676..702c4f5 100644
--- a/src/conf-parameter.hpp
+++ b/src/conf-parameter.hpp
@@ -1,6 +1,6 @@
 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
 /**
- * Copyright (c) 2014-2019,  The University of Memphis,
+ * Copyright (c) 2014-2020,  The University of Memphis,
  *                           Regents of the University of California,
  *                           Arizona Board of Regents.
  *
@@ -27,9 +27,7 @@
 #include "test-access-control.hpp"
 #include "adjacency-list.hpp"
 #include "name-prefix-list.hpp"
-#include "security/certificate-store.hpp"
 
-#include <iostream>
 #include <boost/cstdint.hpp>
 #include <ndn-cxx/face.hpp>
 #include <ndn-cxx/security/validator-config.hpp>
@@ -132,7 +130,8 @@
 {
 
 public:
-  ConfParameter(ndn::Face& face, const std::string& confFileName = "nlsr.conf");
+  ConfParameter(ndn::Face& face,  ndn::KeyChain& keyChain,
+                const std::string& confFileName = "nlsr.conf");
 
   const std::string&
   getConfFileName()
@@ -455,12 +454,36 @@
     return m_prefixUpdateValidator;
   }
 
-  security::CertificateStore&
-  getCertStore()
+  const ndn::security::SigningInfo&
+  getSigningInfo() const
   {
-    return m_certStore;
+    return m_signingInfo;
   }
 
+  void
+  addCertPath(const std::string& certPath)
+  {
+    m_certs.insert(certPath);
+  }
+
+  const std::unordered_set<std::string>&
+  getIdCerts() const
+  {
+    return m_certs;
+  }
+
+  const ndn::KeyChain&
+  getKeyChain() const
+  {
+    return m_keyChain;
+  }
+
+  shared_ptr<ndn::security::v2::Certificate>
+  initializeKey();
+
+  void
+  loadCertToValidator(const ndn::security::v2::Certificate& cert);
+
   /*! \brief Dump the current state of all attributes to the log.
    */
   void
@@ -515,7 +538,9 @@
   NamePrefixList m_npl;
   ndn::security::ValidatorConfig m_validator;
   ndn::security::ValidatorConfig m_prefixUpdateValidator;
-  security::CertificateStore m_certStore;
+  ndn::security::SigningInfo m_signingInfo;
+  std::unordered_set<std::string> m_certs;
+  ndn::KeyChain& m_keyChain;
 };
 
 } // namespace nlsr
diff --git a/src/hello-protocol.cpp b/src/hello-protocol.cpp
index 3d67771..050def4 100644
--- a/src/hello-protocol.cpp
+++ b/src/hello-protocol.cpp
@@ -1,6 +1,6 @@
 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
 /*
- * Copyright (c) 2014-2019,  The University of Memphis,
+ * Copyright (c) 2014-2020,  The University of Memphis,
  *                           Regents of the University of California
  *
  * This file is part of NLSR (Named-data Link State Routing).
@@ -32,13 +32,12 @@
 const std::string HelloProtocol::NLSR_COMPONENT = "nlsr";
 
 HelloProtocol::HelloProtocol(ndn::Face& face, ndn::KeyChain& keyChain,
-                             ndn::security::SigningInfo& signingInfo,
                              ConfParameter& confParam, RoutingTable& routingTable,
                              Lsdb& lsdb)
   : m_face(face)
   , m_scheduler(m_face.getIoService())
   , m_keyChain(keyChain)
-  , m_signingInfo(signingInfo)
+  , m_signingInfo(confParam.getSigningInfo())
   , m_confParam(confParam)
   , m_routingTable(routingTable)
   , m_lsdb(lsdb)
diff --git a/src/hello-protocol.hpp b/src/hello-protocol.hpp
index 3ba4ee7..16d0f91 100644
--- a/src/hello-protocol.hpp
+++ b/src/hello-protocol.hpp
@@ -1,6 +1,6 @@
 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
 /**
- * Copyright (c) 2014-2019,  The University of Memphis,
+ * Copyright (c) 2014-2020,  The University of Memphis,
  *                           Regents of the University of California,
  *                           Arizona Board of Regents.
  *
@@ -41,9 +41,8 @@
 class HelloProtocol
 {
 public:
-  HelloProtocol(ndn::Face& face, ndn::KeyChain& keyChain,
-                ndn::security::SigningInfo& signingInfo,
-                ConfParameter& confParam, RoutingTable& routingTable, Lsdb& lsdb);
+  HelloProtocol(ndn::Face& face, ndn::KeyChain& keyChain, ConfParameter& confParam,
+                RoutingTable& routingTable, Lsdb& lsdb);
 
   /*! \brief Sends a Hello Interest packet.
    *
@@ -160,7 +159,7 @@
   ndn::Face& m_face;
   ndn::Scheduler m_scheduler;
   ndn::security::v2::KeyChain& m_keyChain;
-  ndn::security::SigningInfo& m_signingInfo;
+  const ndn::security::SigningInfo& m_signingInfo;
   ConfParameter& m_confParam;
   RoutingTable& m_routingTable;
   Lsdb& m_lsdb;
diff --git a/src/lsdb.cpp b/src/lsdb.cpp
index d5ddd12..fe0464e 100644
--- a/src/lsdb.cpp
+++ b/src/lsdb.cpp
@@ -1,6 +1,6 @@
 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
 /*
- * Copyright (c) 2014-2019,  The University of Memphis,
+ * Copyright (c) 2014-2020,  The University of Memphis,
  *                           Regents of the University of California,
  *                           Arizona Board of Regents.
  *
@@ -36,12 +36,10 @@
 const ndn::time::steady_clock::TimePoint Lsdb::DEFAULT_LSA_RETRIEVAL_DEADLINE =
   ndn::time::steady_clock::TimePoint::min();
 
-Lsdb::Lsdb(ndn::Face& face, ndn::KeyChain& keyChain,
-           ndn::security::SigningInfo& signingInfo, ConfParameter& confParam,
+Lsdb::Lsdb(ndn::Face& face, ndn::KeyChain& keyChain, ConfParameter& confParam,
            NamePrefixTable& namePrefixTable, RoutingTable& routingTable)
   : m_face(face)
   , m_scheduler(face.getIoService())
-  , m_signingInfo(signingInfo)
   , m_confParam(confParam)
   , m_namePrefixTable(namePrefixTable)
   , m_routingTable(routingTable)
@@ -108,8 +106,14 @@
 void
 Lsdb::afterFetchLsa(const ndn::ConstBufferPtr& bufferPtr, const ndn::Name& interestName)
 {
-  std::shared_ptr<ndn::Data> data = std::make_shared<ndn::Data>(ndn::Name(interestName));
-  data->setContent(ndn::Block(bufferPtr));
+  auto data = std::make_shared<ndn::Data>(ndn::Name(interestName));
+  try {
+    data->setContent(ndn::Block(bufferPtr));
+  }
+  catch (const std::exception& e) {
+    NDN_LOG_ERROR("LSA content not recognized: " << e.what());
+    return;
+  }
 
   NLSR_LOG_DEBUG("Received data for LSA(name): " << data->getName());
 
@@ -1083,7 +1087,7 @@
       std::string content = nameLsa->serialize();
       m_segmentPublisher.publish(interest.getName(), interest.getName(),
                                  ndn::encoding::makeStringBlock(ndn::tlv::Content, content),
-                                 m_lsaRefreshTime, m_signingInfo);
+                                 m_lsaRefreshTime, m_confParam.getSigningInfo());
 
       lsaIncrementSignal(Statistics::PacketType::SENT_NAME_LSA_DATA);
     }
@@ -1119,7 +1123,7 @@
       std::string content = adjLsa->serialize();
       m_segmentPublisher.publish(interest.getName(), interest.getName(),
                                  ndn::encoding::makeStringBlock(ndn::tlv::Content, content),
-                                 m_lsaRefreshTime, m_signingInfo);
+                                 m_lsaRefreshTime, m_confParam.getSigningInfo());
 
       lsaIncrementSignal(Statistics::PacketType::SENT_ADJ_LSA_DATA);
     }
@@ -1155,7 +1159,7 @@
       std::string content = corLsa->serialize();
       m_segmentPublisher.publish(interest.getName(), interest.getName(),
                                  ndn::encoding::makeStringBlock(ndn::tlv::Content, content),
-                                 m_lsaRefreshTime, m_signingInfo);
+                                 m_lsaRefreshTime, m_confParam.getSigningInfo());
 
       lsaIncrementSignal(Statistics::PacketType::SENT_COORD_LSA_DATA);
     }
diff --git a/src/lsdb.hpp b/src/lsdb.hpp
index 718ee55..dee7ce2 100644
--- a/src/lsdb.hpp
+++ b/src/lsdb.hpp
@@ -1,6 +1,6 @@
 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
 /*
- * Copyright (c) 2014-2019,  The University of Memphis,
+ * Copyright (c) 2014-2020,  The University of Memphis,
  *                           Regents of the University of California,
  *                           Arizona Board of Regents.
  *
@@ -46,8 +46,7 @@
 class Lsdb
 {
 public:
-  Lsdb(ndn::Face& face, ndn::KeyChain& keyChain,
-       ndn::security::SigningInfo& signingInfo, ConfParameter& confParam,
+  Lsdb(ndn::Face& face, ndn::KeyChain& keyChain, ConfParameter& confParam,
        NamePrefixTable& namePrefixTable, RoutingTable& routingTable);
 
   ~Lsdb();
@@ -360,6 +359,12 @@
   void
   afterFetchLsa(const ndn::ConstBufferPtr& data, const ndn::Name& interestName);
 
+  void
+  emitSegmentValidatedSignal(const ndn::Data& data)
+  {
+    afterSegmentValidatedSignal(data);
+  }
+
 private:
   ndn::time::system_clock::TimePoint
   getLsaExpirationTimePoint();
@@ -373,7 +378,6 @@
 private:
   ndn::Face& m_face;
   ndn::Scheduler m_scheduler;
-  ndn::security::SigningInfo& m_signingInfo;
 
   ConfParameter& m_confParam;
   NamePrefixTable& m_namePrefixTable;
diff --git a/src/main.cpp b/src/main.cpp
index d109582..16d9c2a 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -1,6 +1,6 @@
 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
 /*
- * Copyright (c) 2014-2019,  The University of Memphis,
+ * Copyright (c) 2014-2020,  The University of Memphis,
  *                           Regents of the University of California,
  *                           Arizona Board of Regents.
  *
@@ -20,6 +20,7 @@
  **/
 
 #include "conf-file-processor.hpp"
+#include "security/certificate-store.hpp"
 #include "nlsr.hpp"
 #include "version.hpp"
 
@@ -87,19 +88,25 @@
   ndn::Face face(ioService);
   ndn::KeyChain keyChain;
 
-  nlsr::ConfParameter confParam(face, configFileName);
+  nlsr::ConfParameter confParam(face, keyChain, configFileName);
   nlsr::ConfFileProcessor configProcessor(confParam);
 
   if (!configProcessor.processConfFile()) {
     std::cerr << "Error in configuration file processing" << std::endl;
     return 2;
   }
-
-  confParam.buildRouterAndSyncUserPrefix();
-  confParam.writeLog();
+  // Since confParam is already populated, key is initialized here before
+  // and independent of the NLSR class
+  auto certificate = confParam.initializeKey();
 
   nlsr::Nlsr nlsr(face, keyChain, confParam);
 
+  nlsr::security::CertificateStore certStore(face, confParam, nlsr.getLsdb());
+
+  if (certificate) {
+    certStore.insert(*certificate);
+  }
+
   try {
     face.processEvents();
   }
diff --git a/src/nlsr.cpp b/src/nlsr.cpp
index 3094e32..73a1ac5 100644
--- a/src/nlsr.cpp
+++ b/src/nlsr.cpp
@@ -1,6 +1,6 @@
 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
 /*
- * Copyright (c) 2014-2019,  The University of Memphis,
+ * Copyright (c) 2014-2020,  The University of Memphis,
  *                           Regents of the University of California,
  *                           Arizona Board of Regents.
  *
@@ -50,10 +50,8 @@
   , m_fib(m_face, m_scheduler, m_adjacencyList, m_confParam, m_keyChain)
   , m_routingTable(m_scheduler, m_fib, m_lsdb, m_namePrefixTable, m_confParam)
   , m_namePrefixTable(m_fib, m_routingTable, m_routingTable.afterRoutingChange)
-  , m_lsdb(m_face, m_keyChain, m_signingInfo, m_confParam, m_namePrefixTable, m_routingTable)
-  , m_helloProtocol(m_face, m_keyChain, m_signingInfo, confParam, m_routingTable, m_lsdb)
-  , m_afterSegmentValidatedConnection(m_lsdb.afterSegmentValidatedSignal.connect(
-                                      std::bind(&Nlsr::afterFetcherSignalEmitted, this, _1)))
+  , m_lsdb(m_face, m_keyChain, m_confParam, m_namePrefixTable, m_routingTable)
+  , m_helloProtocol(m_face, m_keyChain, confParam, m_routingTable, m_lsdb)
   , m_onNewLsaConnection(m_lsdb.getSync().onNewLsa->connect(
       [this] (const ndn::Name& updateName, uint64_t sequenceNumber,
               const ndn::Name& originRouter) {
@@ -73,7 +71,6 @@
       }))
   , m_dispatcher(m_face, m_keyChain)
   , m_datasetHandler(m_dispatcher, m_lsdb, m_routingTable)
-  , m_certStore(m_confParam.getCertStore())
   , m_controller(m_face, m_keyChain)
   , m_faceDatasetController(m_face, m_keyChain)
   , m_prefixUpdateProcessor(m_dispatcher,
@@ -97,22 +94,19 @@
 
   setStrategies();
 
-  initializeKey();
-
-  NLSR_LOG_DEBUG("Default NLSR identity: " << m_signingInfo.getSignerName());
+  NLSR_LOG_DEBUG("Default NLSR identity: " << m_confParam.getSigningInfo().getSignerName());
 
   // Can be moved to HelloProtocol and Lsdb ctor if initializeKey is set
   // earlier in the Nlsr constructor so as to set m_signingInfo
   setInfoInterestFilter();
   setLsaInterestFilter();
 
-  // add top-level prefixes: router and localhost prefix
+  // Add top-level prefixes: router and localhost prefix
   addDispatcherTopPrefix(ndn::Name(m_confParam.getRouterPrefix()).append("nlsr"));
   addDispatcherTopPrefix(LOCALHOST_PREFIX);
 
   enableIncomingFaceIdIndication();
 
-  registerKeyPrefix();
   registerLocalhostPrefix();
   registerRouterPrefix();
 
@@ -184,7 +178,7 @@
                            std::bind(&HelloProtocol::processInterest, &m_helloProtocol, _1, _2),
                            std::bind(&Nlsr::onRegistrationSuccess, this, _1),
                            std::bind(&Nlsr::registrationFailed, this, _1),
-                           m_signingInfo, ndn::nfd::ROUTE_FLAG_CAPTURE);
+                           m_confParam.getSigningInfo(), ndn::nfd::ROUTE_FLAG_CAPTURE);
 }
 
 void
@@ -198,7 +192,7 @@
                            std::bind(&Lsdb::processInterest, &m_lsdb, _1, _2),
                            std::bind(&Nlsr::onRegistrationSuccess, this, _1),
                            std::bind(&Nlsr::registrationFailed, this, _1),
-                           m_signingInfo, ndn::nfd::ROUTE_FLAG_CAPTURE);
+                           m_confParam.getSigningInfo(), ndn::nfd::ROUTE_FLAG_CAPTURE);
 }
 
 void
@@ -206,7 +200,7 @@
 {
   try {
     // false since we want to have control over the registration process
-    m_dispatcher.addTopPrefix(topPrefix, false, m_signingInfo);
+    m_dispatcher.addTopPrefix(topPrefix, false, m_confParam.getSigningInfo());
   }
   catch (const std::exception& e) {
     NLSR_LOG_ERROR("Error setting top-level prefix in dispatcher: " << e.what() << "\n");
@@ -221,58 +215,6 @@
 }
 
 void
-Nlsr::loadCertToPublish(const ndn::security::v2::Certificate& certificate)
-{
-  NLSR_LOG_TRACE("Loading cert to publish.");
-  m_certStore.insert(certificate);
-  m_validator.loadAnchor("Authoritative-Certificate",
-                          ndn::security::v2::Certificate(certificate));
-  m_prefixUpdateProcessor.getValidator().
-                          loadAnchor("Authoritative-Certificate",
-                                      ndn::security::v2::Certificate(certificate));
-}
-
-void
-Nlsr::afterFetcherSignalEmitted(const ndn::Data& lsaSegment)
-{
-  ndn::Name keyName = lsaSegment.getSignature().getKeyLocator().getName();
-  if (getCertificate(keyName) == nullptr) {
-    NLSR_LOG_TRACE("Publishing certificate for: " << keyName);
-    publishCertFromCache(keyName);
-  }
-  else {
-    NLSR_LOG_TRACE("Certificate is already in the store: " << keyName);
-  }
-}
-
-void
-Nlsr::publishCertFromCache(const ndn::Name& keyName)
-{
-  const ndn::security::v2::Certificate* cert = m_validator.getUnverifiedCertCache()
-                                                          .find(keyName);
-
-  if (cert != nullptr) {
-    m_certStore.insert(*cert);
-    NLSR_LOG_TRACE(*cert);
-    ndn::Name certName = ndn::security::v2::extractKeyNameFromCertName(cert->getName());
-    NLSR_LOG_TRACE("Setting interest filter for: " << certName);
-    m_face.setInterestFilter(ndn::InterestFilter(certName).allowLoopback(false),
-                             std::bind(&Nlsr::onKeyInterest, this, _1, _2),
-                             std::bind(&Nlsr::onKeyPrefixRegSuccess, this, _1),
-                             std::bind(&Nlsr::registrationFailed, this, _1),
-                             m_signingInfo, ndn::nfd::ROUTE_FLAG_CAPTURE);
-
-    if (!cert->getKeyName().equals(cert->getSignature().getKeyLocator().getName())) {
-      publishCertFromCache(cert->getSignature().getKeyLocator().getName());
-    }
-  }
-  else {
-    // Happens for root cert
-    NLSR_LOG_TRACE("Cert for " << keyName << " was not found in the Validator's cache. ");
-  }
-}
-
-void
 Nlsr::initialize()
 {
   // Logging start
@@ -295,115 +237,6 @@
 }
 
 void
-Nlsr::initializeKey()
-{
-  NLSR_LOG_DEBUG("Initializing Key ...");
-
-  ndn::Name nlsrInstanceName = m_confParam.getRouterPrefix();
-  nlsrInstanceName.append("nlsr");
-
-  try {
-    m_keyChain.deleteIdentity(m_keyChain.getPib().getIdentity(nlsrInstanceName));
-  }
-  catch (const std::exception& e) {
-    NLSR_LOG_WARN(e.what());
-  }
-
-  ndn::security::Identity nlsrInstanceIdentity;
-  try {
-    nlsrInstanceIdentity = m_keyChain.createIdentity(nlsrInstanceName);
-  }
-  catch (const std::exception& e) {
-    NLSR_LOG_ERROR(e.what());
-    NLSR_LOG_ERROR("Unable to create identity, NLSR will run without security!");
-    NLSR_LOG_ERROR("Can be ignored if running in non-production environments.");
-    return;
-  }
-  auto nlsrInstanceKey = nlsrInstanceIdentity.getDefaultKey();
-
-  ndn::security::v2::Certificate certificate;
-
-  ndn::Name certificateName = nlsrInstanceKey.getName();
-  certificateName.append("NA");
-  certificateName.appendVersion();
-  certificate.setName(certificateName);
-
-  // set metainfo
-  certificate.setContentType(ndn::tlv::ContentType_Key);
-  certificate.setFreshnessPeriod(ndn::time::days(365));
-
-  // set content
-  certificate.setContent(nlsrInstanceKey.getPublicKey().data(), nlsrInstanceKey.getPublicKey().size());
-
-  // set signature-info
-  ndn::SignatureInfo signatureInfo;
-  signatureInfo.setValidityPeriod(ndn::security::ValidityPeriod(ndn::time::system_clock::TimePoint(),
-                                                                ndn::time::system_clock::now()
-                                                                + ndn::time::days(365)));
-  try {
-    m_keyChain.sign(certificate,
-                    ndn::security::SigningInfo(m_keyChain.getPib().getIdentity(m_confParam.getRouterPrefix()))
-                                               .setSignatureInfo(signatureInfo));
-  }
-  catch (const std::exception& e) {
-    NLSR_LOG_ERROR("Router's " << e.what() << "NLSR is running without security." <<
-                   " If security is enabled NLSR will not converge.");
-  }
-
-  m_signingInfo = ndn::security::SigningInfo(ndn::security::SigningInfo::SIGNER_TYPE_ID,
-                                             nlsrInstanceName);
-
-  loadCertToPublish(certificate);
-}
-
-void
-Nlsr::registerKeyPrefix()
-{
-  // Start listening for the interest of this router's NLSR certificate
-  ndn::Name nlsrKeyPrefix = m_confParam.getRouterPrefix();
-  nlsrKeyPrefix.append("nlsr");
-  nlsrKeyPrefix.append("KEY");
-
-  m_face.setInterestFilter(ndn::InterestFilter(nlsrKeyPrefix).allowLoopback(false),
-                           std::bind(&Nlsr::onKeyInterest, this, _1, _2),
-                           std::bind(&Nlsr::onKeyPrefixRegSuccess, this, _1),
-                           std::bind(&Nlsr::registrationFailed, this, _1),
-                           m_signingInfo, ndn::nfd::ROUTE_FLAG_CAPTURE);
-
-  // Start listening for the interest of this router's certificate
-  ndn::Name routerKeyPrefix = m_confParam.getRouterPrefix();
-  routerKeyPrefix.append("KEY");
-
-  m_face.setInterestFilter(ndn::InterestFilter(routerKeyPrefix).allowLoopback(false),
-                           std::bind(&Nlsr::onKeyInterest, this, _1, _2),
-                           std::bind(&Nlsr::onKeyPrefixRegSuccess, this, _1),
-                           std::bind(&Nlsr::registrationFailed, this, _1),
-                           m_signingInfo, ndn::nfd::ROUTE_FLAG_CAPTURE);
-
-  // Start listening for the interest of this router's operator's certificate
-  ndn::Name operatorKeyPrefix = m_confParam.getNetwork();
-  operatorKeyPrefix.append(m_confParam.getSiteName());
-  operatorKeyPrefix.append(std::string("%C1.Operator"));
-
-  m_face.setInterestFilter(ndn::InterestFilter(operatorKeyPrefix).allowLoopback(false),
-                           std::bind(&Nlsr::onKeyInterest, this, _1, _2),
-                           std::bind(&Nlsr::onKeyPrefixRegSuccess, this, _1),
-                           std::bind(&Nlsr::registrationFailed, this, _1),
-                           m_signingInfo, ndn::nfd::ROUTE_FLAG_CAPTURE);
-
-  // Start listening for the interest of this router's site's certificate
-  ndn::Name siteKeyPrefix = m_confParam.getNetwork();
-  siteKeyPrefix.append(m_confParam.getSiteName());
-  siteKeyPrefix.append("KEY");
-
-  m_face.setInterestFilter(ndn::InterestFilter(siteKeyPrefix).allowLoopback(false),
-                           std::bind(&Nlsr::onKeyInterest, this, _1, _2),
-                           std::bind(&Nlsr::onKeyPrefixRegSuccess, this, _1),
-                           std::bind(&Nlsr::registrationFailed, this, _1),
-                           m_signingInfo, ndn::nfd::ROUTE_FLAG_CAPTURE);
-}
-
-void
 Nlsr::registerLocalhostPrefix()
 {
   m_face.registerPrefix(LOCALHOST_PREFIX,
@@ -420,28 +253,6 @@
 }
 
 void
-Nlsr::onKeyInterest(const ndn::Name& name, const ndn::Interest& interest)
-{
-  NLSR_LOG_DEBUG("Got interest for certificate. Interest: " << interest.getName());
-
-  const ndn::Name& interestName = interest.getName();
-  const ndn::security::v2::Certificate* cert = getCertificate(interestName);
-
-  if (cert == nullptr) {
-      NLSR_LOG_DEBUG("Certificate is not found for: " << interest);
-      return; // cert is not found
-  }
-
-  m_face.put(*cert);
-}
-
-void
-Nlsr::onKeyPrefixRegSuccess(const ndn::Name& name)
-{
-  NLSR_LOG_DEBUG("KEY prefix: " << name << " registration is successful.");
-}
-
-void
 Nlsr::onFaceEventNotification(const ndn::nfd::FaceEventNotification& faceEventNotification)
 {
   NLSR_LOG_TRACE("Nlsr::onFaceEventNotification called");
diff --git a/src/nlsr.hpp b/src/nlsr.hpp
index bc82d01..4e61bbc 100644
--- a/src/nlsr.hpp
+++ b/src/nlsr.hpp
@@ -1,6 +1,6 @@
 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
 /**
- * Copyright (c) 2014-2019,  The University of Memphis,
+ * Copyright (c) 2014-2020,  The University of Memphis,
  *                           Regents of the University of California,
  *                           Arizona Board of Regents.
  *
@@ -33,7 +33,6 @@
 #include "route/fib.hpp"
 #include "route/name-prefix-table.hpp"
 #include "route/routing-table.hpp"
-#include "security/certificate-store.hpp"
 #include "update/prefix-update-processor.hpp"
 #include "update/nfd-rib-command-processor.hpp"
 #include "utility/name-helper.hpp"
@@ -105,6 +104,12 @@
   void
   addDispatcherTopPrefix(const ndn::Name& topPrefix);
 
+  Lsdb&
+  getLsdb()
+  {
+    return m_lsdb;
+  }
+
   Fib&
   getFib()
   {
@@ -159,62 +164,10 @@
   registerAdjacencyPrefixes(const Adjacent& adj,
                             const ndn::time::milliseconds& timeout);
 
-  /*! \brief Add a certificate NLSR claims to be authoritative for to the certificate store.
-   *
-   * \sa CertificateStore
-   */
-  void
-  loadCertToPublish(const ndn::security::v2::Certificate& certificate);
-
-  /*! \brief Callback when SegmentFetcher retrieves a segment.
-   */
-  void
-  afterFetcherSignalEmitted(const ndn::Data& lsaSegment);
-
-  /*! \brief Retrieves the chain of certificates from Validator's cache and
-   *   store them in Nlsr's own CertificateStore.
-   * \param keyName Name of the first key in the certificate chain.
-   */
-  void
-  publishCertFromCache(const ndn::Name& keyName);
-
-  void
-  initializeKey();
-
-  /*! \brief Find a certificate
-   *
-   * Find a certificate that NLSR has. First it checks against the
-   * certificates this NLSR claims to be authoritative for, usually
-   * something like this specific router's certificate, and then
-   * checks the cache of certficates it has already fetched. If none
-   * can be found, it will return an empty pointer.
-   */
-  const ndn::security::v2::Certificate*
-  getCertificate(const ndn::Name& certificateKeyName)
-  {
-    const ndn::security::v2::Certificate* cert =
-      m_certStore.find(certificateKeyName);
-
-    return cert;
-  }
-
   void
   setStrategies();
 
-PUBLIC_WITH_TESTS_ELSE_PRIVATE:
-
-  security::CertificateStore&
-  getCertificateStore()
-  {
-    return m_certStore;
-  }
-
 private:
-  /*! \brief Registers the prefix that NLSR will use for key/certificate interests.
-   */
-  void
-  registerKeyPrefix();
-
   /*! \brief Registers the prefix that NLSR will consider to be the machine-local, secure prefix.
    */
   void
@@ -225,16 +178,6 @@
   void
   registerRouterPrefix();
 
-  /*! \brief Attempts to satisfy an Interest for a certificate, and send it back.
-   */
-  void
-  onKeyInterest(const ndn::Name& name, const ndn::Interest& interest);
-
-  /*! \brief Do nothing.
-   */
-  void
-  onKeyPrefixRegSuccess(const ndn::Name& name);
-
   /*! \brief Do nothing.
    */
   void
@@ -272,7 +215,6 @@
   bool m_isDaemonProcess;
   ndn::security::ValidatorConfig& m_validator;
   std::vector<ndn::Name> m_strategySetOnRouters;
-  uint16_t m_numSyncPrefixRegistered = 0;
 
 PUBLIC_WITH_TESTS_ELSE_PRIVATE:
   Fib m_fib;
@@ -282,7 +224,6 @@
   HelloProtocol m_helloProtocol;
 
 private:
-  ndn::util::signal::ScopedConnection m_afterSegmentValidatedConnection;
   ndn::util::signal::ScopedConnection m_onNewLsaConnection;
   ndn::util::signal::ScopedConnection m_onPrefixRegistrationSuccess;
   ndn::util::signal::ScopedConnection m_onHelloDataValidated;
@@ -295,13 +236,11 @@
   /*! \brief Where NLSR stores certificates it claims to be
    * authoritative for. Usually the router certificate.
    */
-  security::CertificateStore& m_certStore;
 
   ndn::nfd::Controller m_controller;
   ndn::nfd::Controller m_faceDatasetController;
 
 PUBLIC_WITH_TESTS_ELSE_PRIVATE:
-  ndn::security::SigningInfo m_signingInfo;
   update::PrefixUpdateProcessor m_prefixUpdateProcessor;
   update::NfdRibCommandProcessor m_nfdRibCommandProcessor;
 
diff --git a/src/security/certificate-store.cpp b/src/security/certificate-store.cpp
new file mode 100644
index 0000000..aa3ae32
--- /dev/null
+++ b/src/security/certificate-store.cpp
@@ -0,0 +1,179 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2014-2020,  The University of Memphis,
+ *                           Regents of the University of California,
+ *                           Arizona Board of Regents.
+ *
+ * This file is part of NLSR (Named-data Link State Routing).
+ * See AUTHORS.md for complete list of NLSR authors and contributors.
+ *
+ * NLSR is free software: you can redistribute it and/or modify it under the terms
+ * of the GNU General Public License as published by the Free Software Foundation,
+ * either version 3 of the License, or (at your option) any later version.
+ *
+ * NLSR 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 General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along with
+ * NLSR, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ **/
+
+#include "certificate-store.hpp"
+#include "conf-parameter.hpp"
+#include "logger.hpp"
+
+#include <ndn-cxx/util/io.hpp>
+
+namespace nlsr {
+namespace security {
+
+INIT_LOGGER(CertificateStore);
+
+CertificateStore::CertificateStore(ndn::Face& face, ConfParameter& confParam, Lsdb& lsdb)
+  : m_face(face)
+  , m_confParam(confParam)
+  , m_lsdb(lsdb)
+  , m_validator(m_confParam.getValidator())
+  , m_afterSegmentValidatedConnection(m_lsdb.afterSegmentValidatedSignal.connect(
+                                      std::bind(&CertificateStore::afterFetcherSignalEmitted,
+                                                this, _1)))
+{
+  for (const auto& x: confParam.getIdCerts()) {
+    auto idCert = ndn::io::load<ndn::security::v2::Certificate>(x);
+    insert(*idCert);
+  }
+
+  registerKeyPrefixes();
+}
+
+void
+CertificateStore::insert(const ndn::security::v2::Certificate& certificate)
+{
+  m_certificates[certificate.getKeyName()] = certificate;
+  NLSR_LOG_TRACE("Certificate inserted successfully");
+}
+
+const ndn::security::v2::Certificate*
+CertificateStore::find(const ndn::Name& keyName) const
+{
+  auto it = m_certificates.find(keyName);
+  return it != m_certificates.end() ? &it->second : nullptr;
+}
+
+void
+CertificateStore::clear()
+{
+  m_certificates.clear();
+}
+
+void
+CertificateStore::setInterestFilter(const ndn::Name& prefix, bool loopback)
+{
+  m_face.setInterestFilter(ndn::InterestFilter(prefix).allowLoopback(loopback),
+                           std::bind(&CertificateStore::onKeyInterest, this, _1, _2),
+                           std::bind(&CertificateStore::onKeyPrefixRegSuccess, this, _1),
+                           std::bind(&CertificateStore::registrationFailed, this, _1),
+                           m_confParam.getSigningInfo(), ndn::nfd::ROUTE_FLAG_CAPTURE);
+}
+
+void
+CertificateStore::registerKeyPrefixes()
+{
+  std::vector<ndn::Name> prefixes;
+
+  // Router's NLSR certificate
+  ndn::Name nlsrKeyPrefix = m_confParam.getRouterPrefix();
+  nlsrKeyPrefix.append("nlsr");
+  nlsrKeyPrefix.append("KEY");
+  prefixes.push_back(nlsrKeyPrefix);
+
+  // Router's certificate
+  ndn::Name routerKeyPrefix = m_confParam.getRouterPrefix();
+  routerKeyPrefix.append("KEY");
+  prefixes.push_back(routerKeyPrefix);
+
+  // Router's operator's certificate
+  ndn::Name operatorKeyPrefix = m_confParam.getNetwork();
+  operatorKeyPrefix.append(m_confParam.getSiteName());
+  operatorKeyPrefix.append(std::string("%C1.Operator"));
+  prefixes.push_back(operatorKeyPrefix);
+
+  // Router's site's certificate
+  ndn::Name siteKeyPrefix = m_confParam.getNetwork();
+  siteKeyPrefix.append(m_confParam.getSiteName());
+  siteKeyPrefix.append("KEY");
+  prefixes.push_back(siteKeyPrefix);
+
+  // Start listening for interest of this router's NLSR certificate,
+  // router's certificate and site's certificate
+  for (const auto& i : prefixes) {
+    setInterestFilter(i);
+  }
+}
+
+void
+CertificateStore::onKeyInterest(const ndn::Name& name, const ndn::Interest& interest)
+{
+  NLSR_LOG_DEBUG("Got interest for certificate. Interest: " << interest.getName());
+
+  const auto* cert = find(interest.getName());
+
+  if (!cert) {
+    NLSR_LOG_TRACE("Certificate is not found for: " << interest);
+    return;
+  }
+  m_face.put(*cert);
+}
+
+void
+CertificateStore::onKeyPrefixRegSuccess(const ndn::Name& name)
+{
+  NLSR_LOG_DEBUG("KEY prefix: " << name << " registration is successful.");
+}
+
+void
+CertificateStore::registrationFailed(const ndn::Name& name)
+{
+  NLSR_LOG_ERROR("ERROR: Failed to register prefix " << name);
+  BOOST_THROW_EXCEPTION(std::runtime_error("Prefix registration failed"));
+}
+
+void
+CertificateStore::publishCertFromCache(const ndn::Name& keyName)
+{
+  const auto* cert = m_validator.getUnverifiedCertCache().find(keyName);
+
+  if (cert) {
+    insert(*cert);
+    NLSR_LOG_TRACE(*cert);
+    ndn::Name certName = ndn::security::v2::extractKeyNameFromCertName(cert->getName());
+    NLSR_LOG_TRACE("Setting interest filter for: " << certName);
+
+    setInterestFilter(certName);
+
+    if (cert->getKeyName() != cert->getSignature().getKeyLocator().getName()) {
+      publishCertFromCache(cert->getSignature().getKeyLocator().getName());
+    }
+  }
+  else {
+    // Happens for root cert
+    NLSR_LOG_TRACE("Cert for " << keyName << " was not found in the Validator's cache. ");
+  }
+}
+
+void
+CertificateStore::afterFetcherSignalEmitted(const ndn::Data& lsaSegment)
+{
+  const auto keyName = lsaSegment.getSignature().getKeyLocator().getName();
+  if (!find(keyName)) {
+    NLSR_LOG_TRACE("Publishing certificate for: " << keyName);
+    publishCertFromCache(keyName);
+  }
+  else {
+    NLSR_LOG_TRACE("Certificate is already in the store: " << keyName);
+  }
+}
+
+} // namespace security
+} // namespace nlsr
diff --git a/src/security/certificate-store.hpp b/src/security/certificate-store.hpp
index 0445318..99b88bf 100644
--- a/src/security/certificate-store.hpp
+++ b/src/security/certificate-store.hpp
@@ -1,6 +1,6 @@
 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
 /**
- * Copyright (c) 2014-2017,  The University of Memphis,
+ * Copyright (c) 2014-2020,  The University of Memphis,
  *                           Regents of the University of California,
  *                           Arizona Board of Regents.
  *
@@ -22,13 +22,17 @@
 #ifndef NLSR_CERTIFICATE_STORE_HPP
 #define NLSR_CERTIFICATE_STORE_HPP
 
-#include "../common.hpp"
-#include "../test-access-control.hpp"
+#include "common.hpp"
+#include "test-access-control.hpp"
+#include "lsdb.hpp"
 
 #include <ndn-cxx/interest.hpp>
+#include <ndn-cxx/mgmt/nfd/controller.hpp>
 #include <ndn-cxx/security/v2/certificate.hpp>
+#include <ndn-cxx/security/validator-config.hpp>
 
 namespace nlsr {
+class ConfParameter;
 namespace security {
 
 /*! \brief Store certificates for names
@@ -40,35 +44,61 @@
  */
 class CertificateStore
 {
+
 public:
+  CertificateStore(ndn::Face& face, ConfParameter& confParam, Lsdb& lsdb);
+
   void
-  insert(const ndn::security::v2::Certificate& certificate)
-  {
-    m_certificates[certificate.getKeyName()] = certificate;
-  }
+  insert(const ndn::security::v2::Certificate& certificate);
 
+  /*! \brief Find a certificate
+   *
+   * Find a certificate that NLSR has. First it checks against the
+   * certificates this NLSR claims to be authoritative for, usually
+   * something like this specific router's certificate, and then
+   * checks the cache of certificates it has already fetched. If none
+   * can be found, it will return an null pointer.
+ */
   const ndn::security::v2::Certificate*
-  find(const ndn::Name keyName)
-  {
-    CertMap::iterator it = m_certificates.find(keyName);
+  find(const ndn::Name& keyName) const;
 
-    if (it != m_certificates.end()) {
-      return &it->second;
-    }
+  /*! \brief Retrieves the chain of certificates from Validator's cache and
+   *   store them in Nlsr's own CertificateStore.
+   * \param keyName Name of the first key in the certificate chain.
+  */
+  void
+  publishCertFromCache(const ndn::Name& keyName);
 
-    return nullptr;
-  }
+  void
+  afterFetcherSignalEmitted(const ndn::Data& lsaSegment);
 
 PUBLIC_WITH_TESTS_ELSE_PRIVATE:
   void
-  clear()
-  {
-    m_certificates.clear();
-  }
+  clear();
+
+  void
+  setInterestFilter(const ndn::Name& prefix, const bool loopback = false);
+
+  void
+  registerKeyPrefixes();
+
+  void
+  onKeyInterest(const ndn::Name& name, const ndn::Interest& interest);
+
+  void
+  onKeyPrefixRegSuccess(const ndn::Name& name);
+
+  void
+  registrationFailed(const ndn::Name& name);
 
 private:
   typedef std::map<ndn::Name, ndn::security::v2::Certificate> CertMap;
   CertMap m_certificates;
+  ndn::Face& m_face;
+  ConfParameter& m_confParam;
+  Lsdb& m_lsdb;
+  ndn::security::ValidatorConfig& m_validator;
+  ndn::util::signal::ScopedConnection m_afterSegmentValidatedConnection;
 };
 
 } // namespace security
diff --git a/src/update/prefix-update-processor.hpp b/src/update/prefix-update-processor.hpp
index 9aedae3..d705fa8 100644
--- a/src/update/prefix-update-processor.hpp
+++ b/src/update/prefix-update-processor.hpp
@@ -1,6 +1,6 @@
 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
 /**
- * Copyright (c) 2014-2019,  The University of Memphis,
+ * Copyright (c) 2014-2020,  The University of Memphis,
  *                           Regents of the University of California,
  *                           Arizona Board of Regents.
  *
@@ -31,11 +31,6 @@
 #include <boost/property_tree/info_parser.hpp>
 
 namespace nlsr {
-
-namespace security {
-  class CertificateStore;
-} // namespace security
-
 namespace update {
 
 typedef boost::property_tree::ptree ConfigSection;