Adding Group Manager

Change-Id: I033c9a71d052b6346c1be33004deb9d5d9b359e1
Refs: #3015
diff --git a/src/common.hpp b/src/common.hpp
index 675b17a..4b39994 100644
--- a/src/common.hpp
+++ b/src/common.hpp
@@ -22,7 +22,7 @@
 
 #include "config.hpp"
 
-#ifdef WITH_TESTS
+#ifdef NDN_GEP_HAVE_TESTS
 #define VIRTUAL_WITH_TESTS virtual
 #define PUBLIC_WITH_TESTS_ELSE_PROTECTED public
 #define PUBLIC_WITH_TESTS_ELSE_PRIVATE public
diff --git a/src/group-manager-db.cpp b/src/group-manager-db.cpp
index 7a955b5..ec0473d 100644
--- a/src/group-manager-db.cpp
+++ b/src/group-manager-db.cpp
@@ -20,6 +20,7 @@
  */
 
 #include "group-manager-db.hpp"
+#include "algo/rsa.hpp"
 
 #include <sqlite3.h>
 #include <boost/filesystem.hpp>
@@ -46,7 +47,8 @@
   "    member_id           INTEGER PRIMARY KEY,       \n"
   "    schedule_id         INTEGER NOT NULL,          \n"
   "    member_name         BLOB NOT NULL,             \n"
-  "    member_cert         BLOB NOT NULL,             \n"
+  "    key_name            BLOB NOT NULL,             \n"
+  "    pubkey              BLOB NOT NULL,             \n"
   "    FOREIGN KEY(schedule_id)                       \n"
   "      REFERENCES schedules(schedule_id)            \n"
   "      ON DELETE CASCADE                            \n"
@@ -155,21 +157,24 @@
   return result;
 }
 
-std::map<Name, Data>
+std::map<Name, Buffer>
 GroupManagerDB::getScheduleMembers(const std::string& name) const
 {
-  std::map<Name, Data> result;
+  std::map<Name, Buffer> result;
   Sqlite3Statement statement(m_impl->m_database,
-                             "SELECT member_name, member_cert\
+                             "SELECT key_name, pubkey\
                               FROM members JOIN schedules\
                               ON members.schedule_id=schedules.schedule_id\
                               WHERE schedule_name=?");
   statement.bind(1, name, SQLITE_TRANSIENT);
-
   result.clear();
+
+  const uint8_t* keyBytes = nullptr;
   while (statement.step() == SQLITE_ROW) {
-    result.insert(std::pair<Name, Data>(Name(statement.getBlock(0)),
-                                        Data(statement.getBlock(1))));
+    keyBytes = statement.getBlob(1);
+    const int& keyBytesSize = statement.getSize(1);
+    result.insert(std::pair<Name, Buffer>(Name(statement.getBlock(0)),
+                                          Buffer(keyBytes, keyBytesSize)));
   }
   return result;
 }
@@ -248,22 +253,6 @@
   return result;
 }
 
-Data
-GroupManagerDB::getMemberCert(const Name& identity) const
-{
-  Sqlite3Statement statement(m_impl->m_database,
-                             "SELECT member_cert FROM members WHERE member_name=?");
-  statement.bind(1, identity.wireEncode(), SQLITE_TRANSIENT);
-  Data result;
-  if (statement.step() == SQLITE_ROW) {
-    result.wireDecode(statement.getBlock(0));
-  }
-  else {
-    BOOST_THROW_EXCEPTION(Error("Cannot get the result from database"));
-  }
-  return result;
-}
-
 std::string
 GroupManagerDB::getMemberSchedule(const Name& identity) const
 {
@@ -285,21 +274,24 @@
 }
 
 void
-GroupManagerDB::addMember(const std::string& scheduleName, const Data& certificate)
+GroupManagerDB::addMember(const std::string& scheduleName, const Name& keyName,
+                          const Buffer& key)
 {
   int scheduleId = m_impl->getScheduleId(scheduleName);
   if (scheduleId == -1)
     BOOST_THROW_EXCEPTION(Error("The schedule dose not exist"));
 
-  IdentityCertificate cert(certificate);
-  Name memberName = cert.getPublicKeyName().getPrefix(-1);
+  // need to be changed in the future
+  Name memberName = keyName.getPrefix(-1);
 
   Sqlite3Statement statement(m_impl->m_database,
-                             "INSERT INTO members(schedule_id, member_name, member_cert)\
-                              values (?, ?, ?)");
+                             "INSERT INTO members(schedule_id, member_name, key_name, pubkey)\
+                              values (?, ?, ?, ?)");
   statement.bind(1, scheduleId);
   statement.bind(2, memberName.wireEncode(), SQLITE_TRANSIENT);
-  statement.bind(3, certificate.wireEncode(), SQLITE_TRANSIENT);
+  statement.bind(3, keyName.wireEncode(), SQLITE_TRANSIENT);
+  statement.bind(4, key.buf(), key.size(), SQLITE_TRANSIENT);
+
   if (statement.step() != SQLITE_DONE)
     BOOST_THROW_EXCEPTION(Error("Cannot add the member to database"));
 }
diff --git a/src/group-manager-db.hpp b/src/group-manager-db.hpp
index e64d677..bf5ef2f 100644
--- a/src/group-manager-db.hpp
+++ b/src/group-manager-db.hpp
@@ -75,10 +75,9 @@
   getSchedule(const std::string& name) const;
 
   /**
-   * @brief Get member information of a schedule with @p name.
-   * The member information include member name and certificate.
+   * @brief Get member key name and public key buffer of a schedule with @p name.
    */
-  std::map<Name, Data>
+  std::map<Name, Buffer>
   getScheduleMembers(const std::string& name) const;
 
   /**
@@ -129,14 +128,6 @@
   listAllMembers() const;
 
   /**
-   * @brief Get the certificate of the member with name @p identity
-   *
-   * @throw Error if there is no member with name @p identity in database
-   */
-  Data
-  getMemberCert(const Name& identity) const;
-
-  /**
    * @brief Get the schedule name of a member with name @p identity
    *
    * @throw Error if there is no member with name @p identity in database
@@ -145,13 +136,15 @@
   getMemberSchedule(const Name& identity) const;
 
   /**
-   * @brief Add a new member with @p certificate into a schedule with name @p scheduleName.
+   * @brief Add a new member with @p key of @p keyName
+   *        into a schedule with name @p scheduleName.
    *
    * @throw Error when there's no schedule named @p scheduleName
-   * @throw Error if add operation fails, e.g., a member with the same name exists
+   * @throw Error if add operation fails, e.g., the added member exists
    */
   void
-  addMember(const std::string& scheduleName, const Data& certificate);
+  addMember(const std::string& scheduleName, const Name& keyName,
+            const Buffer& key);
 
   /**
    * @brief Change the schedule of a member with name @p identity to a schedule with @p scheduleName
diff --git a/src/group-manager.cpp b/src/group-manager.cpp
new file mode 100644
index 0000000..587c488
--- /dev/null
+++ b/src/group-manager.cpp
@@ -0,0 +1,207 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2014-2015,  Regents of the University of California
+ *
+ * This file is part of ndn-group-encrypt (Group-based Encryption Protocol for NDN).
+ * See AUTHORS.md for complete list of ndn-group-encrypt authors and contributors.
+ *
+ * ndn-group-encrypt 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.
+ *
+ * ndn-group-encrypt 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
+ * ndn-group-encrypt, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ * @author Zhiyi Zhang <dreamerbarrychang@gmail.com>
+ */
+
+#include "group-manager.hpp"
+#include "encryptor.hpp"
+#include "encrypted-content.hpp"
+
+#include <map>
+
+namespace ndn {
+namespace gep {
+
+static const std::string E_KEY_COMPONENT = "E-KEY";
+static const std::string D_KEY_COMPONENT = "D-KEY";
+
+GroupManager::GroupManager(const Name& managedNamespace, const std::string& dbDir,
+                           const int paramLength, const int freshPeriod)
+  : m_namespace(managedNamespace)
+  , m_db(dbDir)
+  , m_paramLength(paramLength)
+  , m_freshPeriod(freshPeriod)
+{
+}
+
+std::list<Data>
+GroupManager::getGroupKey(const TimeStamp& timeslot)
+{
+  std::map<Name, Buffer> memberKeys;
+  std::list<Data> result;
+
+  // get time interval
+  Interval finalInterval = calculateInterval(timeslot, memberKeys);
+  if (finalInterval.isValid() == false)
+    return result;
+
+  std::string startTs = boost::posix_time::to_iso_string(finalInterval.getStartTime());
+  std::string endTs = boost::posix_time::to_iso_string(finalInterval.getEndTime());
+
+  // generate the pri key and pub key
+  Buffer priKeyBuf, pubKeyBuf;
+  generateKeyPairs(priKeyBuf, pubKeyBuf);
+
+  // add the first element to the result
+  // E-KEY (public key) data packet name convention:
+  // /<data_type>/E-KEY/[start-ts]/[end-ts]
+  Data data = createEKeyData(startTs, endTs, pubKeyBuf);
+  result.push_back(data);
+
+  // encrypt pri key with pub key from certificate
+  for (const auto& entry : memberKeys) {
+    const Name& keyName = entry.first;
+    const Buffer& certKey = entry.second;
+
+    // generate the name of the packet
+    // D-KEY (private key) data packet name convention:
+    // /<data_type>/D-KEY/[start-ts]/[end-ts]/[member-name]
+    data = createDKeyData(startTs, endTs, keyName, priKeyBuf, certKey);
+    result.push_back(data);
+  }
+  return result;
+}
+
+void
+GroupManager::addSchedule(const std::string& scheduleName, const Schedule& schedule)
+{
+  m_db.addSchedule(scheduleName, schedule);
+}
+
+void
+GroupManager::deleteSchedule(const std::string& scheduleName)
+{
+  m_db.deleteSchedule(scheduleName);
+}
+
+void
+GroupManager::updateSchedule(const std::string& scheduleName, const Schedule& schedule)
+{
+  m_db.updateSchedule(scheduleName, schedule);
+}
+
+void
+GroupManager::addMember(const std::string& scheduleName, const Data& memCert)
+{
+  IdentityCertificate cert(memCert);
+  m_db.addMember(scheduleName, cert.getPublicKeyName(), cert.getPublicKeyInfo().get());
+}
+
+void
+GroupManager::removeMember(const Name& identity)
+{
+  m_db.deleteMember(identity);
+}
+
+void
+GroupManager::updateMemberSchedule(const Name& identity, const std::string& scheduleName)
+{
+  m_db.updateMemberSchedule(identity, scheduleName);
+}
+
+Interval
+GroupManager::calculateInterval(const TimeStamp& timeslot, std::map<Name, Buffer>& memberKeys)
+{
+  // prepare
+  Interval positiveResult;
+  Interval negativeResult;
+  Interval tempInterval;
+  Interval finalInterval;
+  bool isPositive;
+  memberKeys.clear();
+
+  // get the all intervals from schedules
+  for (const std::string& scheduleName : m_db.listAllScheduleNames()) {
+
+    const Schedule& schedule = m_db.getSchedule(scheduleName);
+    std::tie(isPositive, tempInterval) = schedule.getCoveringInterval(timeslot);
+
+    if (isPositive) {
+      if (!positiveResult.isValid())
+        positiveResult = tempInterval;
+      positiveResult && tempInterval;
+
+      std::map<Name, Buffer> m = m_db.getScheduleMembers(scheduleName);
+      memberKeys.insert(m.begin(), m.end());
+    }
+    else {
+      if (!negativeResult.isValid())
+        negativeResult = tempInterval;
+      negativeResult && tempInterval;
+    }
+  }
+  if (!positiveResult.isValid()) {
+    // return invalid interval when there is no member has interval covering the time slot
+    return Interval(false);
+  }
+
+  // get the final interval result
+  if (negativeResult.isValid())
+    finalInterval = positiveResult && negativeResult;
+  else
+    finalInterval = positiveResult;
+
+  return finalInterval;
+}
+
+void
+GroupManager::generateKeyPairs(Buffer& priKeyBuf, Buffer& pubKeyBuf) const
+{
+  RandomNumberGenerator rng;
+  RsaKeyParams params(m_paramLength);
+  algo::EncryptParams eparams(tlv::AlgorithmRsaPkcs);
+  DecryptKey<algo::Rsa> privateKey = algo::Rsa::generateKey(rng, params);
+  priKeyBuf = privateKey.getKeyBits();
+  EncryptKey<algo::Rsa> publicKey = algo::Rsa::deriveEncryptKey(priKeyBuf);
+  pubKeyBuf = publicKey.getKeyBits();
+}
+
+
+Data
+GroupManager::createEKeyData(const std::string& startTs, const std::string& endTs,
+                             const Buffer& pubKeyBuf)
+{
+  Name dataName(m_namespace);
+  dataName.append(E_KEY_COMPONENT).append(startTs).append(endTs);
+  Data data(dataName);
+  data.setFreshnessPeriod(time::hours(m_freshPeriod));
+  data.setContent(pubKeyBuf.get(), pubKeyBuf.size());
+  m_keyChain.sign(data);
+  return data;
+}
+
+Data
+GroupManager::createDKeyData(const std::string& startTs, const std::string& endTs,
+                             const Name& keyName, const Buffer& priKeyBuf,
+                             const Buffer& certKey)
+{
+  Name dataName(m_namespace);
+  dataName.append(D_KEY_COMPONENT);
+  dataName.append(startTs).append(endTs).append(keyName.getPrefix(-1));
+  Data data = Data(dataName);
+  data.setFreshnessPeriod(time::hours(m_freshPeriod));
+  algo::EncryptParams eparams(tlv::AlgorithmRsaPkcs);
+  algo::encryptData(data, priKeyBuf.buf(), priKeyBuf.size(), keyName,
+                    certKey.buf(), certKey.size(), eparams);
+  m_keyChain.sign(data);
+  return data;
+}
+
+} // namespace ndn
+} // namespace ndn
diff --git a/src/group-manager.hpp b/src/group-manager.hpp
new file mode 100644
index 0000000..34937da
--- /dev/null
+++ b/src/group-manager.hpp
@@ -0,0 +1,128 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2014-2015,  Regents of the University of California
+ *
+ * This file is part of ndn-group-encrypt (Group-based Encryption Protocol for NDN).
+ * See AUTHORS.md for complete list of ndn-group-encrypt authors and contributors.
+ *
+ * ndn-group-encrypt 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.
+ *
+ * ndn-group-encrypt 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
+ * ndn-group-encrypt, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ * @author Zhiyi Zhang <dreamerbarrychang@gmail.com>
+ */
+
+#ifndef NDN_GEP_GROUP_MANAGER_HPP
+#define NDN_GEP_GROUP_MANAGER_HPP
+
+#include "group-manager-db.hpp"
+#include "algo/rsa.hpp"
+
+#include <ndn-cxx/security/key-chain.hpp>
+
+namespace ndn {
+namespace gep {
+
+class GroupManager
+{
+public:
+  class Error : public std::runtime_error
+  {
+  public:
+    explicit
+    Error(const std::string& what)
+      : std::runtime_error(what)
+    {
+    }
+  };
+
+public:
+  /// @brief Create group manager using @p managedNamespace
+  GroupManager(const Name& managedNamespace, const std::string& dbDir,
+               const int paramLength, const int freshPeriod);
+
+  /**
+   * @brief Create a group key for interval which
+   *        @p timeslot falls into
+   *
+   * This method creates a group key if it does not
+   * exist, and encrypts the key using public key of
+   * all eligible members
+   *
+   * @returns The group key (the first one is the
+   *          public key, and the rest are encrypted
+   *          private key.
+   */
+  std::list<Data>
+  getGroupKey(const TimeStamp& timeslot);
+
+  /// @brief Add @p schedule with @p scheduleName
+  void
+  addSchedule(const std::string& scheduleName, const Schedule& schedule);
+
+  /// @brief Delete schedule with name @p scheduleName
+  void
+  deleteSchedule(const std::string& scheduleName);
+
+  /// @brief Update a schedule by name @p scheduleName with a new @p schedule
+  void
+  updateSchedule(const std::string& scheduleName, const Schedule& schedule);
+
+  /// @brief Add @p memCert with @p scheduleName
+  void
+  addMember(const std::string& scheduleName, const Data& memCert);
+
+  /// @brief Remove member with name @p identity from the group.
+  void
+  removeMember(const Name& identity);
+
+  /// @brief Update @p member with a schedule of @p schedule Name.
+  void
+  updateMemberSchedule(const Name& identity, const std::string& scheduleName);
+
+PUBLIC_WITH_TESTS_ELSE_PRIVATE:
+  /**
+   * @brief Calculate interval that covers @p timeslot
+   * and fill @p memberKeys with the info of members who is allowed to access the interval.
+   */
+  Interval
+  calculateInterval(const TimeStamp& timeslot, std::map<Name, Buffer>& certMap);
+
+  /**
+   * @brief Generate rsa key pairs according to the member variable m_paramLength.
+   * @p priKeyBuf The generated private key buffer
+   * @p pubKeyBuf The generated public key buffer
+   */
+  void
+  generateKeyPairs(Buffer& priKeyBuf, Buffer& pubKeyBuf) const;
+
+  /// @brief Create E-KEY data.
+  Data
+  createEKeyData(const std::string& startTs, const std::string& endTs,
+                 const Buffer& pubKeyBuf);
+
+  /// @brief Create D-KEY data.
+  Data
+  createDKeyData(const std::string& startTs, const std::string& endTs, const Name& keyName,
+                 const Buffer& priKeyBuf, const Buffer& certKey);
+
+private:
+  Name m_namespace;
+  GroupManagerDB m_db;
+  int m_paramLength;
+  int m_freshPeriod;
+
+  KeyChain m_keyChain;
+};
+
+} // namespace gep
+} // namespace ndn
+
+#endif // NDN_GEP_GROUP_MANAGER_HPP