merge detail folders
Change-Id: Id8f126bb4f4dd621f224d3d705b22f85e00babad
diff --git a/src/detail/ca-memory.cpp b/src/detail/ca-memory.cpp
new file mode 100644
index 0000000..b647dba
--- /dev/null
+++ b/src/detail/ca-memory.cpp
@@ -0,0 +1,99 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/*
+ * Copyright (c) 2017-2020, Regents of the University of California.
+ *
+ * This file is part of ndncert, a certificate management system based on NDN.
+ *
+ * ndncert 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.
+ *
+ * ndncert 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 copies of the GNU General Public License along with
+ * ndncert, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndncert authors and contributors.
+ */
+
+#include "ca-memory.hpp"
+#include <ndn-cxx/security/validation-policy.hpp>
+
+namespace ndn {
+namespace ndncert {
+
+const std::string
+CaMemory::STORAGE_TYPE = "ca-storage-memory";
+
+NDNCERT_REGISTER_CA_STORAGE(CaMemory);
+
+CaMemory::CaMemory(const Name& caName, const std::string& path)
+ : CaStorage()
+{
+}
+
+CaState
+CaMemory::getRequest(const std::string& requestId)
+{
+ auto search = m_requests.find(requestId);
+ if (search == m_requests.end()) {
+ NDN_THROW(std::runtime_error("Request " + requestId + " doest not exists"));
+ }
+ return search->second;
+}
+
+void
+CaMemory::addRequest(const CaState& request)
+{
+ auto search = m_requests.find(request.m_requestId);
+ if (search == m_requests.end()) {
+ m_requests[request.m_requestId] = request;
+ }
+ else {
+ NDN_THROW(std::runtime_error("Request " + request.m_requestId + " already exists"));
+ }
+}
+
+void
+CaMemory::updateRequest(const CaState& request)
+{
+ m_requests[request.m_requestId].m_status = request.m_status;
+ m_requests[request.m_requestId].m_challengeState = request.m_challengeState;
+}
+
+void
+CaMemory::deleteRequest(const std::string& requestId)
+{
+ auto search = m_requests.find(requestId);
+ auto keyName = search->second.m_cert.getKeyName();
+ if (search != m_requests.end()) {
+ m_requests.erase(search);
+ }
+}
+
+std::list<CaState>
+CaMemory::listAllRequests()
+{
+ std::list<CaState> result;
+ for (const auto& entry : m_requests) {
+ result.push_back(entry.second);
+ }
+ return result;
+}
+
+std::list<CaState>
+CaMemory::listAllRequests(const Name& caName)
+{
+ std::list<CaState> result;
+ for (const auto& entry : m_requests) {
+ if (entry.second.m_caPrefix == caName) {
+ result.push_back(entry.second);
+ }
+ }
+ return result;
+}
+
+} // namespace ndncert
+} // namespace ndn
diff --git a/src/detail/ca-memory.hpp b/src/detail/ca-memory.hpp
new file mode 100644
index 0000000..842121b
--- /dev/null
+++ b/src/detail/ca-memory.hpp
@@ -0,0 +1,67 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/*
+ * Copyright (c) 2017-2020, Regents of the University of California.
+ *
+ * This file is part of ndncert, a certificate management system based on NDN.
+ *
+ * ndncert 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.
+ *
+ * ndncert 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 copies of the GNU General Public License along with
+ * ndncert, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndncert authors and contributors.
+ */
+
+#ifndef NDNCERT_CA_DETAIL_CA_MEMORY_HPP
+#define NDNCERT_CA_DETAIL_CA_MEMORY_HPP
+
+#include "ca-storage.hpp"
+
+namespace ndn {
+namespace ndncert {
+
+class CaMemory : public CaStorage
+{
+public:
+ CaMemory(const Name& caName = Name(), const std::string& path = "");
+ const static std::string STORAGE_TYPE;
+
+public:
+ /**
+ * @throw if request cannot be fetched from underlying data storage
+ */
+ CaState
+ getRequest(const std::string& requestId) override;
+
+ /**
+ * @throw if there is an existing request with the same request ID
+ */
+ void
+ addRequest(const CaState& request) override;
+
+ void
+ updateRequest(const CaState& request) override;
+
+ void
+ deleteRequest(const std::string& requestId) override;
+
+ std::list<CaState>
+ listAllRequests() override;
+
+ std::list<CaState>
+ listAllRequests(const Name& caName) override;
+
+private:
+ std::map<Name, CaState> m_requests;
+};
+
+} // namespace ndncert
+} // namespace ndn
+
+#endif // NDNCERT_CA_DETAIL_CA_MEMORY_HPP
diff --git a/src/detail/ca-sqlite.cpp b/src/detail/ca-sqlite.cpp
new file mode 100644
index 0000000..b0d6af5
--- /dev/null
+++ b/src/detail/ca-sqlite.cpp
@@ -0,0 +1,303 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/*
+ * Copyright (c) 2017-2020, Regents of the University of California.
+ *
+ * This file is part of ndncert, a certificate management system based on NDN.
+ *
+ * ndncert 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.
+ *
+ * ndncert 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 copies of the GNU General Public License along with
+ * ndncert, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndncert authors and contributors.
+ */
+
+#include "ca-sqlite.hpp"
+
+#include <sqlite3.h>
+
+#include <boost/filesystem.hpp>
+#include <ndn-cxx/security/validation-policy.hpp>
+#include <ndn-cxx/util/sqlite3-statement.hpp>
+
+namespace ndn {
+namespace ndncert {
+
+using namespace ndn::util;
+const std::string CaSqlite::STORAGE_TYPE = "ca-storage-sqlite3";
+
+NDNCERT_REGISTER_CA_STORAGE(CaSqlite);
+
+std::string
+convertJson2String(const JsonSection& json)
+{
+ std::stringstream ss;
+ boost::property_tree::write_json(ss, json);
+ return ss.str();
+}
+
+JsonSection
+convertString2Json(const std::string& jsonContent)
+{
+ std::istringstream ss(jsonContent);
+ JsonSection json;
+ boost::property_tree::json_parser::read_json(ss, json);
+ return json;
+}
+
+static const std::string INITIALIZATION = R"_DBTEXT_(
+CREATE TABLE IF NOT EXISTS
+ CaStates(
+ id INTEGER PRIMARY KEY,
+ request_id TEXT NOT NULL,
+ ca_name BLOB NOT NULL,
+ request_type INTEGER NOT NULL,
+ status INTEGER NOT NULL,
+ cert_request BLOB NOT NULL,
+ challenge_type TEXT,
+ challenge_status TEXT,
+ challenge_tp TEXT,
+ remaining_tries INTEGER,
+ remaining_time INTEGER,
+ challenge_secrets TEXT,
+ encryption_key BLOB NOT NULL
+ );
+CREATE UNIQUE INDEX IF NOT EXISTS
+ CaStateIdIndex ON CaStates(request_id);
+)_DBTEXT_";
+
+CaSqlite::CaSqlite(const Name& caName, const std::string& path)
+ : CaStorage()
+{
+ // Determine the path of sqlite db
+ boost::filesystem::path dbDir;
+ if (!path.empty()) {
+ dbDir = boost::filesystem::path(path);
+ }
+ else {
+ std::string dbName = caName.toUri();
+ std::replace(dbName.begin(), dbName.end(), '/', '_');
+ dbName += ".db";
+ if (getenv("HOME") != nullptr) {
+ dbDir = boost::filesystem::path(getenv("HOME")) / ".ndncert";
+ }
+ else {
+ dbDir = boost::filesystem::current_path() / ".ndncert";
+ }
+ boost::filesystem::create_directories(dbDir);
+ dbDir /= dbName;
+ }
+
+ // open and initialize database
+ int result = sqlite3_open_v2(dbDir.c_str(), &m_database,
+ SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
+#ifdef NDN_CXX_DISABLE_SQLITE3_FS_LOCKING
+ "unix-dotfile"
+#else
+ nullptr
+#endif
+ );
+ if (result != SQLITE_OK)
+ NDN_THROW(std::runtime_error("CaSqlite DB cannot be opened/created: " + dbDir.string()));
+
+ // initialize database specific tables
+ char* errorMessage = nullptr;
+ result = sqlite3_exec(m_database, INITIALIZATION.data(),
+ nullptr, nullptr, &errorMessage);
+ if (result != SQLITE_OK && errorMessage != nullptr) {
+ sqlite3_free(errorMessage);
+ NDN_THROW(std::runtime_error("CaSqlite DB cannot be initialized"));
+ }
+}
+
+CaSqlite::~CaSqlite()
+{
+ sqlite3_close(m_database);
+}
+
+CaState
+CaSqlite::getRequest(const std::string& requestId)
+{
+ Sqlite3Statement statement(m_database,
+ R"_SQLTEXT_(SELECT id, ca_name, status,
+ challenge_status, cert_request,
+ challenge_type, challenge_secrets,
+ challenge_tp, remaining_tries, remaining_time, request_type, encryption_key
+ FROM CaStates where request_id = ?)_SQLTEXT_");
+ statement.bind(1, requestId, SQLITE_TRANSIENT);
+
+ if (statement.step() == SQLITE_ROW) {
+ Name caName(statement.getBlock(1));
+ auto status = static_cast<Status>(statement.getInt(2));
+ auto challengeStatus = statement.getString(3);
+ security::Certificate cert(statement.getBlock(4));
+ auto challengeType = statement.getString(5);
+ auto challengeSecrets = statement.getString(6);
+ auto challengeTp = statement.getString(7);
+ auto remainingTries = statement.getInt(8);
+ auto remainingTime = statement.getInt(9);
+ auto requestType = static_cast<RequestType>(statement.getInt(10));
+ auto encryptionKey = statement.getBlock(11);
+ if (challengeType != "") {
+ return CaState(caName, requestId, requestType, status, cert,
+ challengeType, challengeStatus, time::fromIsoString(challengeTp),
+ remainingTries, time::seconds(remainingTime),
+ convertString2Json(challengeSecrets), encryptionKey);
+ }
+ else {
+ return CaState(caName, requestId, requestType, status, cert, encryptionKey);
+ }
+ }
+ else {
+ NDN_THROW(std::runtime_error("Request " + requestId + " cannot be fetched from database"));
+ }
+}
+
+void
+CaSqlite::addRequest(const CaState& request)
+{
+ Sqlite3Statement statement(
+ m_database,
+ R"_SQLTEXT_(INSERT OR ABORT INTO CaStates (request_id, ca_name, status, request_type,
+ cert_request, challenge_type, challenge_status, challenge_secrets,
+ challenge_tp, remaining_tries, remaining_time, encryption_key)
+ values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?))_SQLTEXT_");
+ statement.bind(1, request.m_requestId, SQLITE_TRANSIENT);
+ statement.bind(2, request.m_caPrefix.wireEncode(), SQLITE_TRANSIENT);
+ statement.bind(3, static_cast<int>(request.m_status));
+ statement.bind(4, static_cast<int>(request.m_requestType));
+ statement.bind(5, request.m_cert.wireEncode(), SQLITE_TRANSIENT);
+ statement.bind(12, request.m_encryptionKey, SQLITE_TRANSIENT);
+ if (request.m_challengeState) {
+ statement.bind(6, request.m_challengeType, SQLITE_TRANSIENT);
+ statement.bind(7, request.m_challengeState->m_challengeStatus, SQLITE_TRANSIENT);
+ statement.bind(8, convertJson2String(request.m_challengeState->m_secrets),
+ SQLITE_TRANSIENT);
+ statement.bind(9, time::toIsoString(request.m_challengeState->m_timestamp), SQLITE_TRANSIENT);
+ statement.bind(10, request.m_challengeState->m_remainingTries);
+ statement.bind(11, request.m_challengeState->m_remainingTime.count());
+ }
+ if (statement.step() != SQLITE_DONE) {
+ NDN_THROW(std::runtime_error("Request " + request.m_requestId + " cannot be added to database"));
+ }
+}
+
+void
+CaSqlite::updateRequest(const CaState& request)
+{
+ Sqlite3Statement statement(m_database,
+ R"_SQLTEXT_(UPDATE CaStates
+ SET status = ?, challenge_type = ?, challenge_status = ?, challenge_secrets = ?,
+ challenge_tp = ?, remaining_tries = ?, remaining_time = ?
+ WHERE request_id = ?)_SQLTEXT_");
+ statement.bind(1, static_cast<int>(request.m_status));
+ statement.bind(2, request.m_challengeType, SQLITE_TRANSIENT);
+ if (request.m_challengeState) {
+ statement.bind(3, request.m_challengeState->m_challengeStatus, SQLITE_TRANSIENT);
+ statement.bind(4, convertJson2String(request.m_challengeState->m_secrets), SQLITE_TRANSIENT);
+ statement.bind(5, time::toIsoString(request.m_challengeState->m_timestamp), SQLITE_TRANSIENT);
+ statement.bind(6, request.m_challengeState->m_remainingTries);
+ statement.bind(7, request.m_challengeState->m_remainingTime.count());
+ }
+ else {
+ statement.bind(3, "", SQLITE_TRANSIENT);
+ statement.bind(4, "", SQLITE_TRANSIENT);
+ statement.bind(5, "", SQLITE_TRANSIENT);
+ statement.bind(6, 0);
+ statement.bind(7, 0);
+ }
+ statement.bind(8, request.m_requestId, SQLITE_TRANSIENT);
+
+ if (statement.step() != SQLITE_DONE) {
+ addRequest(request);
+ }
+}
+
+std::list<CaState>
+CaSqlite::listAllRequests()
+{
+ std::list<CaState> result;
+ Sqlite3Statement statement(m_database, R"_SQLTEXT_(SELECT id, request_id, ca_name, status,
+ challenge_status, cert_request, challenge_type, challenge_secrets,
+ challenge_tp, remaining_tries, remaining_time, request_type, encryption_key
+ FROM CaStates)_SQLTEXT_");
+ while (statement.step() == SQLITE_ROW) {
+ auto requestId = statement.getString(1);
+ Name caName(statement.getBlock(2));
+ auto status = static_cast<Status>(statement.getInt(3));
+ auto challengeStatus = statement.getString(4);
+ security::Certificate cert(statement.getBlock(5));
+ auto challengeType = statement.getString(6);
+ auto challengeSecrets = statement.getString(7);
+ auto challengeTp = statement.getString(8);
+ auto remainingTries = statement.getInt(9);
+ auto remainingTime = statement.getInt(10);
+ auto requestType = static_cast<RequestType>(statement.getInt(11));
+ auto encryptionKey = statement.getBlock(12);
+ if (challengeType != "") {
+ result.push_back(CaState(caName, requestId, requestType, status, cert,
+ challengeType, challengeStatus, time::fromIsoString(challengeTp),
+ remainingTries, time::seconds(remainingTime),
+ convertString2Json(challengeSecrets), encryptionKey));
+ }
+ else {
+ result.push_back(CaState(caName, requestId, requestType, status, cert, encryptionKey));
+ }
+ }
+ return result;
+}
+
+std::list<CaState>
+CaSqlite::listAllRequests(const Name& caName)
+{
+ std::list<CaState> result;
+ Sqlite3Statement statement(m_database,
+ R"_SQLTEXT_(SELECT id, request_id, ca_name, status,
+ challenge_status, cert_request, challenge_type, challenge_secrets,
+ challenge_tp, remaining_tries, remaining_time, request_type, encryption_key
+ FROM CaStates WHERE ca_name = ?)_SQLTEXT_");
+ statement.bind(1, caName.wireEncode(), SQLITE_TRANSIENT);
+
+ while (statement.step() == SQLITE_ROW) {
+ auto requestId = statement.getString(1);
+ Name caName(statement.getBlock(2));
+ auto status = static_cast<Status>(statement.getInt(3));
+ auto challengeStatus = statement.getString(4);
+ security::Certificate cert(statement.getBlock(5));
+ auto challengeType = statement.getString(6);
+ auto challengeSecrets = statement.getString(7);
+ auto challengeTp = statement.getString(8);
+ auto remainingTries = statement.getInt(9);
+ auto remainingTime = statement.getInt(10);
+ auto requestType = static_cast<RequestType>(statement.getInt(11));
+ auto encryptionKey = statement.getBlock(12);
+ if (challengeType != "") {
+ result.push_back(CaState(caName, requestId, requestType, status, cert,
+ challengeType, challengeStatus, time::fromIsoString(challengeTp),
+ remainingTries, time::seconds(remainingTime),
+ convertString2Json(challengeSecrets), encryptionKey));
+ }
+ else {
+ result.push_back(CaState(caName, requestId, requestType, status, cert, encryptionKey));
+ }
+ }
+ return result;
+}
+
+void
+CaSqlite::deleteRequest(const std::string& requestId)
+{
+ Sqlite3Statement statement(m_database,
+ R"_SQLTEXT_(DELETE FROM CaStates WHERE request_id = ?)_SQLTEXT_");
+ statement.bind(1, requestId, SQLITE_TRANSIENT);
+ statement.step();
+}
+
+} // namespace ndncert
+} // namespace ndn
diff --git a/src/detail/ca-sqlite.hpp b/src/detail/ca-sqlite.hpp
new file mode 100644
index 0000000..5d12188
--- /dev/null
+++ b/src/detail/ca-sqlite.hpp
@@ -0,0 +1,73 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/*
+ * Copyright (c) 2017-2020, Regents of the University of California.
+ *
+ * This file is part of ndncert, a certificate management system based on NDN.
+ *
+ * ndncert 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.
+ *
+ * ndncert 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 copies of the GNU General Public License along with
+ * ndncert, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndncert authors and contributors.
+ */
+
+#ifndef NDNCERT_CA_DETAIL_CA_SQLITE_HPP
+#define NDNCERT_CA_DETAIL_CA_SQLITE_HPP
+
+#include "ca-storage.hpp"
+
+struct sqlite3;
+
+namespace ndn {
+namespace ndncert {
+
+class CaSqlite : public CaStorage
+{
+public:
+ const static std::string STORAGE_TYPE;
+
+ explicit
+ CaSqlite(const Name& caName, const std::string& path = "");
+
+ ~CaSqlite();
+
+public:
+ /**
+ * @throw if request cannot be fetched from underlying data storage
+ */
+ CaState
+ getRequest(const std::string& requestId) override;
+
+ /**
+ * @throw if there is an existing request with the same request ID
+ */
+ void
+ addRequest(const CaState& request) override;
+
+ void
+ updateRequest(const CaState& request) override;
+
+ void
+ deleteRequest(const std::string& requestId) override;
+
+ std::list<CaState>
+ listAllRequests() override;
+
+ std::list<CaState>
+ listAllRequests(const Name& caName) override;
+
+private:
+ sqlite3* m_database;
+};
+
+} // namespace ndncert
+} // namespace ndn
+
+#endif // NDNCERT_CA_DETAIL_CA_SQLITE_HPP
diff --git a/src/detail/ca-state.cpp b/src/detail/ca-state.cpp
new file mode 100644
index 0000000..185fbdd
--- /dev/null
+++ b/src/detail/ca-state.cpp
@@ -0,0 +1,117 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2017-2020, Regents of the University of California.
+ *
+ * This file is part of ndncert, a certificate management system based on NDN.
+ *
+ * ndncert 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.
+ *
+ * ndncert 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 copies of the GNU General Public License along with
+ * ndncert, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndncert authors and contributors.
+ */
+
+#include "ca-state.hpp"
+#include <ndn-cxx/util/indented-stream.hpp>
+
+namespace ndn {
+namespace ndncert {
+
+std::string statusToString(Status status) {
+ switch (status)
+ {
+ case Status::BEFORE_CHALLENGE:
+ return "Before challenge";
+ case Status::CHALLENGE:
+ return "In challenge";
+ case Status::PENDING:
+ return "Pending after challenge";
+ case Status::SUCCESS:
+ return "Success";
+ case Status::FAILURE:
+ return "Failure";
+ case Status::NOT_STARTED:
+ return "Not started";
+ case Status::ENDED:
+ return "Ended";
+ default:
+ return "Unrecognized status";
+ }
+}
+
+ChallengeState::ChallengeState(const std::string& challengeStatus,
+ const time::system_clock::TimePoint& challengeTp,
+ size_t remainingTries, time::seconds remainingTime,
+ JsonSection&& challengeSecrets)
+ : m_challengeStatus(challengeStatus)
+ , m_timestamp(challengeTp)
+ , m_remainingTries(remainingTries)
+ , m_remainingTime(remainingTime)
+ , m_secrets(std::move(challengeSecrets))
+{
+}
+
+CaState::CaState()
+ : m_requestType(RequestType::NOTINITIALIZED)
+ , m_status(Status::NOT_STARTED)
+{
+}
+
+CaState::CaState(const Name& caName, const std::string& requestId, RequestType requestType, Status status,
+ const security::Certificate& cert, Block encryptionKey)
+ : m_caPrefix(caName)
+ , m_requestId(requestId)
+ , m_requestType(requestType)
+ , m_status(status)
+ , m_cert(cert)
+ , m_encryptionKey(std::move(encryptionKey))
+{
+}
+
+CaState::CaState(const Name& caName, const std::string& requestId, RequestType requestType, Status status,
+ const security::Certificate& cert, const std::string& challengeType,
+ const std::string& challengeStatus, const time::system_clock::TimePoint& challengeTp,
+ size_t remainingTries, time::seconds remainingTime, JsonSection&& challengeSecrets,
+ Block encryptionKey)
+ : m_caPrefix(caName)
+ , m_requestId(requestId)
+ , m_requestType(requestType)
+ , m_status(status)
+ , m_cert(cert)
+ , m_encryptionKey(std::move(encryptionKey))
+ , m_challengeType(challengeType)
+ , m_challengeState(ChallengeState(challengeStatus, challengeTp, remainingTries, remainingTime, std::move(challengeSecrets)))
+{
+}
+
+std::ostream&
+operator<<(std::ostream& os, const CaState& request)
+{
+ os << "Request's CA name: " << request.m_caPrefix << "\n";
+ os << "Request's request ID: " << request.m_requestId << "\n";
+ os << "Request's status: " << statusToString(request.m_status) << "\n";
+ os << "Request's challenge type: " << request.m_challengeType << "\n";
+ if (request.m_challengeState) {
+ os << "Challenge Status: " << request.m_challengeState->m_challengeStatus << "\n";
+ os << "Challenge remaining tries:" << request.m_challengeState->m_remainingTries << " times\n";
+ os << "Challenge remaining time: " << request.m_challengeState->m_remainingTime.count() << " seconds\n";
+ os << "Challenge last update: " << time::toIsoString(request.m_challengeState->m_timestamp) << "\n";
+ std::stringstream ss;
+ boost::property_tree::write_json(ss, request.m_challengeState->m_secrets);
+ os << "Challenge secret:\n" << ss.str() << "\n";
+ }
+ os << "Certificate:\n";
+ util::IndentedStream os2(os, " ");
+ os2 << request.m_cert;
+ return os;
+}
+
+} // namespace ndncert
+} // namespace ndn
diff --git a/src/detail/ca-state.hpp b/src/detail/ca-state.hpp
new file mode 100644
index 0000000..2204f1c
--- /dev/null
+++ b/src/detail/ca-state.hpp
@@ -0,0 +1,94 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2017-2020, Regents of the University of California.
+ *
+ * This file is part of ndncert, a certificate management system based on NDN.
+ *
+ * ndncert 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.
+ *
+ * ndncert 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 copies of the GNU General Public License along with
+ * ndncert, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndncert authors and contributors.
+ */
+
+#ifndef NDNCERT_CA_STATE_HPP
+#define NDNCERT_CA_STATE_HPP
+
+#include "detail/ndncert-common.hpp"
+
+namespace ndn {
+namespace ndncert {
+
+// NDNCERT Request status enumeration
+enum class Status : uint16_t {
+ BEFORE_CHALLENGE = 0,
+ CHALLENGE = 1,
+ PENDING = 2,
+ SUCCESS = 3,
+ FAILURE = 4,
+ NOT_STARTED = 5,
+ ENDED = 6
+};
+
+// Convert request status to string
+std::string
+statusToString(Status status);
+
+/**
+ * @brief The state maintained by the Challenge modules
+ */
+struct ChallengeState
+{
+ ChallengeState(const std::string& challengeStatus, const time::system_clock::TimePoint& challengeTp,
+ size_t remainingTries, time::seconds remainingTime,
+ JsonSection&& challengeSecrets);
+ std::string m_challengeStatus;
+ time::system_clock::TimePoint m_timestamp;
+ size_t m_remainingTries;
+ time::seconds m_remainingTime;
+ JsonSection m_secrets;
+};
+
+/**
+ * @brief Represents a certificate request instance kept by the CA.
+ *
+ * ChallengeModule should take use of ChallengeState to keep state.
+ */
+class CaState
+{
+public:
+ CaState();
+ CaState(const Name& caName, const std::string& requestId, RequestType requestType, Status status,
+ const security::Certificate& cert, Block m_encryptionKey);
+ CaState(const Name& caName, const std::string& requestId, RequestType requestType, Status status,
+ const security::Certificate& cert, const std::string& challengeType,
+ const std::string& challengeStatus, const time::system_clock::TimePoint& challengeTp,
+ size_t remainingTries, time::seconds remainingTime, JsonSection&& challengeSecrets,
+ Block m_encryptionKey);
+
+public:
+ Name m_caPrefix;
+ std::string m_requestId;
+ RequestType m_requestType;
+ Status m_status;
+ security::Certificate m_cert;
+ Block m_encryptionKey;
+
+ std::string m_challengeType;
+ boost::optional<ChallengeState> m_challengeState;
+};
+
+std::ostream&
+operator<<(std::ostream& os, const CaState& request);
+
+} // namespace ndncert
+} // namespace ndn
+
+#endif // NDNCERT_CA_STATE_HPP
diff --git a/src/detail/ca-storage.cpp b/src/detail/ca-storage.cpp
new file mode 100644
index 0000000..a7195f6
--- /dev/null
+++ b/src/detail/ca-storage.cpp
@@ -0,0 +1,42 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2017-2020, Regents of the University of California.
+ *
+ * This file is part of ndncert, a certificate management system based on NDN.
+ *
+ * ndncert 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.
+ *
+ * ndncert 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 copies of the GNU General Public License along with
+ * ndncert, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndncert authors and contributors.
+ */
+
+#include "detail/ca-storage.hpp"
+
+namespace ndn {
+namespace ndncert {
+
+unique_ptr<CaStorage>
+CaStorage::createCaStorage(const std::string& caStorageType, const Name& caName, const std::string& path)
+{
+ CaStorageFactory& factory = getFactory();
+ auto i = factory.find(caStorageType);
+ return i == factory.end() ? nullptr : i->second(caName, path);
+}
+
+CaStorage::CaStorageFactory&
+CaStorage::getFactory()
+{
+ static CaStorage::CaStorageFactory factory;
+ return factory;
+}
+
+} // namespace ndncert
+} // namespace ndn
diff --git a/src/detail/ca-storage.hpp b/src/detail/ca-storage.hpp
new file mode 100644
index 0000000..70a0ac9
--- /dev/null
+++ b/src/detail/ca-storage.hpp
@@ -0,0 +1,95 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2017-2020, Regents of the University of California.
+ *
+ * This file is part of ndncert, a certificate management system based on NDN.
+ *
+ * ndncert 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.
+ *
+ * ndncert 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 copies of the GNU General Public License along with
+ * ndncert, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndncert authors and contributors.
+ */
+
+#ifndef NDNCERT_CA_STORAGE_HPP
+#define NDNCERT_CA_STORAGE_HPP
+
+#include "detail/ca-state.hpp"
+
+namespace ndn {
+namespace ndncert {
+
+class CaStorage : noncopyable
+{
+public: // request related
+ /**
+ * @throw if request cannot be fetched from underlying data storage
+ */
+ virtual CaState
+ getRequest(const std::string& requestId) = 0;
+
+ /**
+ * @throw if there is an existing request with the same request ID
+ */
+ virtual void
+ addRequest(const CaState& request) = 0;
+
+ virtual void
+ updateRequest(const CaState& request) = 0;
+
+ virtual void
+ deleteRequest(const std::string& requestId) = 0;
+
+ virtual std::list<CaState>
+ listAllRequests() = 0;
+
+ virtual std::list<CaState>
+ listAllRequests(const Name& caName) = 0;
+
+public: // factory
+ template<class CaStorageType>
+ static void
+ registerCaStorage(const std::string& caStorageType = CaStorageType::STORAGE_TYPE)
+ {
+ CaStorageFactory& factory = getFactory();
+ BOOST_ASSERT(factory.count(caStorageType) == 0);
+ factory[caStorageType] = [] (const Name& caName, const std::string& path) {
+ return std::make_unique<CaStorageType>(caName, path);
+ };
+ }
+
+ static unique_ptr<CaStorage>
+ createCaStorage(const std::string& caStorageType, const Name& caName, const std::string& path);
+
+ virtual
+ ~CaStorage() = default;
+
+private:
+ using CaStorageCreateFunc = function<unique_ptr<CaStorage> (const Name&, const std::string&)>;
+ using CaStorageFactory = std::map<std::string, CaStorageCreateFunc>;
+
+ static CaStorageFactory&
+ getFactory();
+};
+
+#define NDNCERT_REGISTER_CA_STORAGE(C) \
+static class NdnCert ## C ## CaStorageRegistrationClass \
+{ \
+public: \
+ NdnCert ## C ## CaStorageRegistrationClass() \
+ { \
+ ::ndn::ndncert::CaStorage::registerCaStorage<C>(); \
+ } \
+} g_NdnCert ## C ## CaStorageRegistrationVariable
+
+} // namespace ndncert
+} // namespace ndn
+
+#endif // NDNCERT_CA_STORAGE_HPP
diff --git a/src/detail/challenge-encoder.cpp b/src/detail/challenge-encoder.cpp
new file mode 100644
index 0000000..658cbd8
--- /dev/null
+++ b/src/detail/challenge-encoder.cpp
@@ -0,0 +1,63 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2017-2020, Regents of the University of California.
+ *
+ * This file is part of ndncert, a certificate management system based on NDN.
+ *
+ * ndncert 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.
+ *
+ * ndncert 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 copies of the GNU General Public License along with
+ * ndncert, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndncert authors and contributors.
+ */
+
+#include "challenge-encoder.hpp"
+
+namespace ndn {
+namespace ndncert {
+
+Block
+ChallengeEncoder::encodeDataContent(const CaState& request)
+{
+ Block response = makeEmptyBlock(tlv::EncryptedPayload);
+ response.push_back(makeNonNegativeIntegerBlock(tlv::Status, static_cast<size_t>(request.m_status)));
+ if (request.m_challengeState) {
+ response.push_back(makeStringBlock(tlv::ChallengeStatus, request.m_challengeState->m_challengeStatus));
+ response.push_back(
+ makeNonNegativeIntegerBlock(tlv::RemainingTries, request.m_challengeState->m_remainingTries));
+ response.push_back(
+ makeNonNegativeIntegerBlock(tlv::RemainingTime, request.m_challengeState->m_remainingTime.count()));
+ }
+ response.encode();
+ return response;
+}
+
+void
+ChallengeEncoder::decodeDataContent(const Block& data, RequesterState& state)
+{
+ data.parse();
+ state.m_status = static_cast<Status>(readNonNegativeInteger(data.get(tlv::Status)));
+ if (data.find(tlv::ChallengeStatus) != data.elements_end()) {
+ state.m_challengeStatus = readString(data.get(tlv::ChallengeStatus));
+ }
+ if (data.find(tlv::RemainingTries) != data.elements_end()) {
+ state.m_remainingTries = readNonNegativeInteger(data.get(tlv::RemainingTries));
+ }
+ if (data.find(tlv::RemainingTime) != data.elements_end()) {
+ state.m_freshBefore = time::system_clock::now() + time::seconds(readNonNegativeInteger(data.get(tlv::RemainingTime)));
+ }
+ if (data.find(tlv::IssuedCertName) != data.elements_end()) {
+ Block issuedCertNameBlock = data.get(tlv::IssuedCertName);
+ state.m_issuedCertName = Name(issuedCertNameBlock.blockFromValue());
+ }
+}
+
+} // namespace ndncert
+} // namespace ndn
diff --git a/src/detail/challenge-encoder.hpp b/src/detail/challenge-encoder.hpp
new file mode 100644
index 0000000..cce4108
--- /dev/null
+++ b/src/detail/challenge-encoder.hpp
@@ -0,0 +1,43 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2017-2020, Regents of the University of California.
+ *
+ * This file is part of ndncert, a certificate management system based on NDN.
+ *
+ * ndncert 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.
+ *
+ * ndncert 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 copies of the GNU General Public License along with
+ * ndncert, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndncert authors and contributors.
+ */
+
+#ifndef NDNCERT_PROTOCOL_DETAIL_CHALLENGE_STEP_HPP
+#define NDNCERT_PROTOCOL_DETAIL_CHALLENGE_STEP_HPP
+
+#include "../detail/ca-state.hpp"
+#include "../requester-state.hpp"
+
+namespace ndn {
+namespace ndncert {
+
+class ChallengeEncoder
+{
+public:
+ static Block
+ encodeDataContent(const CaState& request);
+
+ static void
+ decodeDataContent(const Block& data, RequesterState& state);
+};
+
+} // namespace ndncert
+} // namespace ndn
+
+#endif // NDNCERT_PROTOCOL_DETAIL_CHALLENGE_STEP_HPP
\ No newline at end of file
diff --git a/src/detail/crypto-helper.cpp b/src/detail/crypto-helper.cpp
new file mode 100644
index 0000000..a7f561d
--- /dev/null
+++ b/src/detail/crypto-helper.cpp
@@ -0,0 +1,436 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2017-2020, Regents of the University of California.
+ *
+ * This file is part of ndncert, a certificate management system based on NDN.
+ *
+ * ndncert 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.
+ *
+ * ndncert 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 copies of the GNU General Public License along with
+ * ndncert, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndncert authors and contributors.
+ */
+
+#include "crypto-helper.hpp"
+#include <openssl/err.h>
+#include <openssl/hmac.h>
+#include <openssl/pem.h>
+#include <openssl/ec.h>
+#include <openssl/evp.h>
+#include <ndn-cxx/encoding/buffer-stream.hpp>
+#include <ndn-cxx/security/transform/base64-decode.hpp>
+#include <ndn-cxx/security/transform/base64-encode.hpp>
+#include <ndn-cxx/security/transform/buffer-source.hpp>
+#include <ndn-cxx/security/transform/private-key.hpp>
+#include <ndn-cxx/security/transform/signer-filter.hpp>
+#include <ndn-cxx/security/transform/step-source.hpp>
+#include <ndn-cxx/security/transform/stream-sink.hpp>
+#include <ndn-cxx/util/random.hpp>
+
+namespace ndn {
+namespace ndncert {
+
+const size_t HASH_SIZE = 32;
+
+NDN_LOG_INIT(ndncert.cryptosupport);
+
+void
+handleErrors(const std::string& errorInfo)
+{
+ NDN_LOG_DEBUG("Error in CRYPTO SUPPORT " << errorInfo);
+ NDN_THROW(std::runtime_error("Error in CRYPTO SUPPORT: " + errorInfo));
+}
+
+struct ECDHState::ECDH_CTX
+{
+ int EC_NID;
+ EVP_PKEY_CTX* ctx_params;
+ EVP_PKEY_CTX* ctx_keygen;
+ EVP_PKEY* privkey;
+ EVP_PKEY* peerkey;
+ EVP_PKEY* params;
+};
+
+ECDHState::ECDHState()
+ : m_publicKeyLen(0)
+ , m_sharedSecretLen(0)
+{
+ OpenSSL_add_all_algorithms();
+ context = std::make_unique<ECDH_CTX>();
+ context->EC_NID = NID_X9_62_prime256v1;
+
+ // Create the context for parameter generation
+ if (nullptr == (context->ctx_params = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, nullptr))) {
+ handleErrors("Could not create context contexts.");
+ return;
+ }
+
+ // Initialise the parameter generation
+ if (EVP_PKEY_paramgen_init(context->ctx_params) != 1) {
+ handleErrors("Could not initialize parameter generation.");
+ return;
+ }
+
+ // We're going to use the ANSI X9.62 Prime 256v1 curve
+ if (1 != EVP_PKEY_CTX_set_ec_paramgen_curve_nid(context->ctx_params, context->EC_NID)) {
+ handleErrors("Likely unknown elliptical curve ID specified.");
+ return;
+ }
+
+ // Create the parameter object params
+ if (!EVP_PKEY_paramgen(context->ctx_params, &context->params)) {
+ // the generated key is written to context->params
+ handleErrors("Could not create parameter object parameters.");
+ return;
+ }
+
+ // Create the context for the key generation
+ if (nullptr == (context->ctx_keygen = EVP_PKEY_CTX_new(context->params, nullptr))) {
+ //The EVP_PKEY_CTX_new() function allocates public key algorithm context using
+ //the algorithm specified in pkey and ENGINE e (in this case nullptr).
+ handleErrors("Could not create the context for the key generation");
+ return;
+ }
+
+ // initializes a public key algorithm context
+ if (1 != EVP_PKEY_keygen_init(context->ctx_keygen)) {
+ handleErrors("Could not init context for key generation.");
+ return;
+ }
+ if (1 != EVP_PKEY_keygen(context->ctx_keygen, &context->privkey)) {
+ //performs a key generation operation, the generated key is written to context->privkey.
+ handleErrors("Could not generate DHE keys in final step");
+ return;
+ }
+}
+
+ECDHState::~ECDHState()
+{
+ // Contexts
+ if (context->ctx_params != nullptr) {
+ EVP_PKEY_CTX_free(context->ctx_params);
+ }
+ if (context->ctx_keygen != nullptr) {
+ EVP_PKEY_CTX_free(context->ctx_keygen);
+ }
+
+ // Keys
+ if (context->privkey != nullptr) {
+ EVP_PKEY_free(context->privkey);
+ }
+ if (context->peerkey != nullptr) {
+ EVP_PKEY_free(context->peerkey);
+ }
+ if (context->params != nullptr) {
+ EVP_PKEY_free(context->params);
+ }
+}
+
+uint8_t*
+ECDHState::getRawSelfPubKey()
+{
+ auto privECKey = EVP_PKEY_get1_EC_KEY(context->privkey);
+
+ if (privECKey == nullptr) {
+ handleErrors("Could not get referenced key when calling EVP_PKEY_get1_EC_KEY().");
+ return nullptr;
+ }
+
+ auto ecPoint = EC_KEY_get0_public_key(privECKey);
+ const EC_GROUP* group = EC_KEY_get0_group(privECKey);
+ m_publicKeyLen = EC_POINT_point2oct(group, ecPoint, POINT_CONVERSION_COMPRESSED,
+ m_publicKey, 256, nullptr);
+ EC_KEY_free(privECKey);
+ if (m_publicKeyLen == 0) {
+ handleErrors("Could not convert EC_POINTS to octet string when calling EC_POINT_point2oct.");
+ return nullptr;
+ }
+
+ return m_publicKey;
+}
+
+std::string
+ECDHState::getBase64PubKey()
+{
+ namespace t = ndn::security::transform;
+
+ if (m_publicKeyLen == 0) {
+ this->getRawSelfPubKey();
+ }
+ std::ostringstream os;
+ t::bufferSource(m_publicKey, m_publicKeyLen) >> t::base64Encode(false) >> t::streamSink(os);
+ return os.str();
+}
+
+uint8_t*
+ECDHState::deriveSecret(const uint8_t* peerkey, int peerKeySize)
+{
+ auto privECKey = EVP_PKEY_get1_EC_KEY(context->privkey);
+
+ if (privECKey == nullptr) {
+ handleErrors("Could not get referenced key when calling EVP_PKEY_get1_EC_KEY()");
+ return nullptr;
+ }
+
+ auto group = EC_KEY_get0_group(privECKey);
+ auto peerPoint = EC_POINT_new(group);
+ int result = EC_POINT_oct2point(group, peerPoint, peerkey, peerKeySize, nullptr);
+ if (result == 0) {
+ EC_POINT_free(peerPoint);
+ EC_KEY_free(privECKey);
+ handleErrors("Cannot convert peer's key into a EC point when calling EC_POINT_oct2point()");
+ }
+
+ result = ECDH_compute_key(m_sharedSecret, 256, peerPoint, privECKey, nullptr);
+ if (result == -1) {
+ EC_POINT_free(peerPoint);
+ EC_KEY_free(privECKey);
+ handleErrors("Cannot generate ECDH secret when calling ECDH_compute_key()");
+ }
+ m_sharedSecretLen = static_cast<size_t>(result);
+ EC_POINT_free(peerPoint);
+ EC_KEY_free(privECKey);
+ return m_sharedSecret;
+}
+
+uint8_t*
+ECDHState::deriveSecret(const std::string& peerKeyStr)
+{
+ namespace t = ndn::security::transform;
+
+ OBufferStream os;
+ t::bufferSource(peerKeyStr) >> t::base64Decode(false) >> t::streamSink(os);
+ auto result = os.buf();
+
+ return this->deriveSecret(result->data(), result->size());
+}
+
+int
+hmac_sha256(const uint8_t* data, const unsigned data_length,
+ const uint8_t* key, const unsigned key_length,
+ uint8_t* result)
+{
+ HMAC(EVP_sha256(), key, key_length,
+ (unsigned char*)data, data_length,
+ (unsigned char*)result, nullptr);
+ return 0;
+}
+
+int
+hkdf(const uint8_t* secret, int secret_len, const uint8_t* salt,
+ int salt_len, uint8_t* output, int output_len,
+ const uint8_t* info, int info_len)
+{
+ namespace t = ndn::security::transform;
+
+ // hkdf generate prk
+ uint8_t prk[HASH_SIZE];
+ if (salt_len == 0) {
+ uint8_t realSalt[HASH_SIZE] = {0};
+ hmac_sha256(secret, secret_len, realSalt, HASH_SIZE, prk);
+ }
+ else {
+ hmac_sha256(secret, secret_len, salt, salt_len, prk);
+ }
+
+ // hkdf expand
+ uint8_t prev[HASH_SIZE] = {0};
+ int done_len = 0, dig_len = HASH_SIZE, n = output_len / dig_len;
+ if (output_len % dig_len)
+ n++;
+ if (n > 255 || output == nullptr)
+ return 0;
+
+ for (int i = 1; i <= n; i++) {
+ size_t copy_len;
+ const uint8_t ctr = i;
+
+ t::StepSource source;
+ t::PrivateKey privKey;
+ privKey.loadRaw(KeyType::HMAC, prk, dig_len);
+ OBufferStream os;
+ source >> t::signerFilter(DigestAlgorithm::SHA256, privKey) >> t::streamSink(os);
+
+ if (i > 1) {
+ source.write(prev, dig_len);
+ }
+ source.write(info, info_len);
+ source.write(&ctr, 1);
+ source.end();
+
+ auto result = os.buf();
+ memcpy(prev, result->data(), dig_len);
+ copy_len = (done_len + dig_len > output_len) ? output_len - done_len : dig_len;
+ memcpy(output + done_len, prev, copy_len);
+ done_len += copy_len;
+ }
+ return done_len;
+}
+
+int
+aes_gcm_128_encrypt(const uint8_t* plaintext, size_t plaintext_len, const uint8_t* associated, size_t associated_len,
+ const uint8_t* key, const uint8_t* iv, uint8_t* ciphertext, uint8_t* tag)
+{
+ EVP_CIPHER_CTX* ctx;
+ int len;
+ int ciphertext_len;
+
+ // Create and initialise the context
+ if (!(ctx = EVP_CIPHER_CTX_new())) {
+ handleErrors("Cannot create and initialise the context when calling EVP_CIPHER_CTX_new()");
+ }
+
+ // Initialise the encryption operation.
+ if (1 != EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), nullptr, nullptr, nullptr)) {
+ handleErrors("Cannot initialise the encryption operation when calling EVP_EncryptInit_ex()");
+ }
+
+ // Set IV length if default 12 bytes (96 bits) is not appropriate
+ if (1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 12, nullptr)) {
+ handleErrors("Cannot set IV length when calling EVP_CIPHER_CTX_ctrl()");
+ }
+
+ // Initialise key and IV
+ if (1 != EVP_EncryptInit_ex(ctx, nullptr, nullptr, key, iv)) {
+ handleErrors("Cannot initialize key and IV when calling EVP_EncryptInit_ex()");
+ }
+
+ // Provide any AAD data. This can be called zero or more times as required
+ if (1 != EVP_EncryptUpdate(ctx, nullptr, &len, associated, associated_len)) {
+ handleErrors("Cannot set associated authentication data when calling EVP_EncryptUpdate()");
+ }
+
+ // Provide the message to be encrypted, and obtain the encrypted output.
+ // EVP_EncryptUpdate can be called multiple times if necessary
+ if (1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len)) {
+ handleErrors("Cannot encrypt when calling EVP_EncryptUpdate()");
+ }
+ ciphertext_len = len;
+
+ // Finalise the encryption. Normally ciphertext bytes may be written at
+ // this stage, but this does not occur in GCM mode
+ if (1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) {
+ handleErrors("Cannot finalise the encryption when calling EVP_EncryptFinal_ex()");
+ }
+ ciphertext_len += len;
+
+ // Get the tag
+ if (1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, 16, tag)) {
+ handleErrors("Cannot get tag when calling EVP_CIPHER_CTX_ctrl()");
+ }
+
+ // Clean up
+ EVP_CIPHER_CTX_free(ctx);
+ return ciphertext_len;
+}
+
+int
+aes_gcm_128_decrypt(const uint8_t* ciphertext, size_t ciphertext_len, const uint8_t* associated, size_t associated_len,
+ const uint8_t* tag, const uint8_t* key, const uint8_t* iv, uint8_t* plaintext)
+{
+ EVP_CIPHER_CTX* ctx;
+ int len;
+ int plaintext_len;
+ int ret;
+
+ // Create and initialise the context
+ if (!(ctx = EVP_CIPHER_CTX_new())) {
+ handleErrors("Cannot create and initialise the context when calling EVP_CIPHER_CTX_new()");
+ }
+
+ // Initialise the decryption operation.
+ if (!EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), nullptr, nullptr, nullptr)) {
+ handleErrors("Cannot initialise the decryption operation when calling EVP_DecryptInit_ex()");
+ }
+
+ // Set IV length. Not necessary if this is 12 bytes (96 bits)
+ if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 12, nullptr)) {
+ handleErrors("Cannot set IV length when calling EVP_CIPHER_CTX_ctrl");
+ }
+
+ // Initialise key and IV
+ if (!EVP_DecryptInit_ex(ctx, nullptr, nullptr, key, iv)) {
+ handleErrors("Cannot initialise key and IV when calling EVP_DecryptInit_ex()");
+ }
+
+ // Provide any AAD data. This can be called zero or more times as required
+ if (!EVP_DecryptUpdate(ctx, nullptr, &len, associated, associated_len)) {
+ handleErrors("Cannot set associated authentication data when calling EVP_EncryptUpdate()");
+ }
+
+ // Provide the message to be decrypted, and obtain the plaintext output.
+ // EVP_DecryptUpdate can be called multiple times if necessary
+ if (!EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len)) {
+ handleErrors("Cannot decrypt when calling EVP_DecryptUpdate()");
+ }
+ plaintext_len = len;
+
+ // Set expected tag value. Works in OpenSSL 1.0.1d and later
+ if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, 16, (void*)tag)) {
+ handleErrors("Cannot set tag value when calling EVP_CIPHER_CTX_ctrl");
+ }
+
+ // Finalise the decryption. A positive return value indicates success,
+ // anything else is a failure - the plaintext is not trustworthy.
+ ret = EVP_DecryptFinal_ex(ctx, plaintext + len, &len);
+
+ // Clean up
+ EVP_CIPHER_CTX_free(ctx);
+
+ if (ret > 0) {
+ // Success
+ plaintext_len += len;
+ return plaintext_len;
+ }
+ else {
+ // Verify failed
+ return -1;
+ }
+}
+
+Block
+encodeBlockWithAesGcm128(uint32_t tlv_type, const uint8_t* key, const uint8_t* payload, size_t payloadSize,
+ const uint8_t* associatedData, size_t associatedDataSize)
+{
+ Buffer iv;
+ iv.resize(12);
+ random::generateSecureBytes(iv.data(), iv.size());
+
+ uint8_t* encryptedPayload = new uint8_t[payloadSize];
+ uint8_t tag[16];
+ size_t encryptedPayloadLen = aes_gcm_128_encrypt(payload, payloadSize, associatedData, associatedDataSize,
+ key, iv.data(), encryptedPayload, tag);
+ auto content = makeEmptyBlock(tlv_type);
+ content.push_back(makeBinaryBlock(tlv::InitializationVector, iv.data(), iv.size()));
+ content.push_back(makeBinaryBlock(tlv::AuthenticationTag, tag, 16));
+ content.push_back(makeBinaryBlock(tlv::EncryptedPayload, encryptedPayload, encryptedPayloadLen));
+ content.encode();
+ delete[] encryptedPayload;
+ return content;
+}
+
+Buffer
+decodeBlockWithAesGcm128(const Block& block, const uint8_t* key, const uint8_t* associatedData, size_t associatedDataSize)
+{
+ block.parse();
+ Buffer result;
+ result.resize(block.get(tlv::EncryptedPayload).value_size());
+ int resultLen = aes_gcm_128_decrypt(block.get(tlv::EncryptedPayload).value(),
+ block.get(tlv::EncryptedPayload).value_size(),
+ associatedData, associatedDataSize, block.get(tlv::AuthenticationTag).value(),
+ key, block.get(tlv::InitializationVector).value(), result.data());
+ if (resultLen == -1 || resultLen != (int)block.get(tlv::EncryptedPayload).value_size()) {
+ return Buffer();
+ }
+ return result;
+}
+
+} // namespace ndncert
+} // namespace ndn
diff --git a/src/detail/crypto-helper.hpp b/src/detail/crypto-helper.hpp
new file mode 100644
index 0000000..50aa7bb
--- /dev/null
+++ b/src/detail/crypto-helper.hpp
@@ -0,0 +1,157 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2017-2020, Regents of the University of California.
+ *
+ * This file is part of ndncert, a certificate management system based on NDN.
+ *
+ * ndncert 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.
+ *
+ * ndncert 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 copies of the GNU General Public License along with
+ * ndncert, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndncert authors and contributors.
+ */
+
+#ifndef NDNCERT_PROTOCOL_DETAIL_CRYPTO_HELPER_HPP
+#define NDNCERT_PROTOCOL_DETAIL_CRYPTO_HELPER_HPP
+
+#include "ndncert-common.hpp"
+
+namespace ndn {
+namespace ndncert {
+
+static const int INFO_LEN = 10;
+static const uint8_t INFO[] = {0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9};
+static const int AES_128_KEY_LEN = 16;
+
+class ECDHState
+{
+public:
+ ECDHState();
+ ~ECDHState();
+
+ std::string
+ getBase64PubKey();
+
+ uint8_t*
+ deriveSecret(const std::string& peerKeyStr);
+
+ uint8_t m_publicKey[256];
+ size_t m_publicKeyLen;
+ uint8_t m_sharedSecret[256];
+ size_t m_sharedSecretLen;
+
+PUBLIC_WITH_TESTS_ELSE_PRIVATE:
+ uint8_t*
+ deriveSecret(const uint8_t* peerkey, int peerKeySize);
+
+ uint8_t*
+ getRawSelfPubKey();
+
+private:
+ struct ECDH_CTX;
+ unique_ptr<ECDH_CTX> context;
+};
+
+/**
+ * HMAC based key derivation function (HKDF)
+ * @p secret, intput, the input to the HKDF
+ * @p secretLen, intput, the length of the secret
+ * @p salt, intput, the salt used in HKDF
+ * @p saltLen, intput, the length of the salt
+ * @p output, output, the output of the HKDF
+ * @p output_len, intput, the length of expected output
+ * @p info, intput, the additional information used in HKDF
+ * @p info_len, intput, the additional information used in HKDF
+ * @return the length of the derived key if successful, -1 if failed
+ */
+int
+hkdf(const uint8_t* secret, int secret_len,
+ const uint8_t* salt, int salt_len,
+ uint8_t* output, int output_len,
+ const uint8_t* info = INFO, int info_len = INFO_LEN);
+
+/**
+ * HMAC based on SHA-256
+ * @p data, intput, the array to hmac
+ * @p data_length, intput, the length of the array
+ * @p key, intput, the key for the function
+ * @p key_len, intput, the length of the key
+ * @p result, output, result of the HMAC. Enough memory (32 Bytes) must be allocated beforehands
+ * @return 0 if successful, -1 if failed
+ */
+int
+hmac_sha256(const uint8_t* data, const unsigned data_length,
+ const uint8_t* key, const unsigned key_length,
+ uint8_t* result);
+
+/**
+ * Authenticated GCM 128 Encryption with associated data
+ * @p plaintext, input, plaintext
+ * @p plaintext_len, input, size of plaintext
+ * @p associated, input, associated authentication data
+ * @p associated_len, input, size of associated authentication data
+ * @p key, input, 16 bytes AES key
+ * @p iv, input, 12 bytes IV
+ * @p ciphertext, output, enough memory must be allocated beforehands
+ * @p tag, output, 16 bytes tag
+ * @return the size of ciphertext
+ * @throw runtime_error when there is an error in the process of encryption
+ */
+int
+aes_gcm_128_encrypt(const uint8_t* plaintext, size_t plaintext_len, const uint8_t* associated, size_t associated_len,
+ const uint8_t* key, const uint8_t* iv, uint8_t* ciphertext, uint8_t* tag);
+
+/**
+ * Authenticated GCM 128 Decryption with associated data
+ * @p ciphertext, input, ciphertext
+ * @p ciphertext_len, input, size of ciphertext
+ * @p associated, input, associated authentication data
+ * @p associated_len, input, size of associated authentication data
+ * @p tag, input, 16 bytes tag
+ * @p key, input, 16 bytes AES key
+ * @p iv, input, 12 bytes IV
+ * @p plaintext, output, enough memory must be allocated beforehands
+ * @return the size of plaintext or -1 if the verification fails
+ * @throw runtime_error when there is an error in the process of encryption
+ */
+int
+aes_gcm_128_decrypt(const uint8_t* ciphertext, size_t ciphertext_len, const uint8_t* associated, size_t associated_len,
+ const uint8_t* tag, const uint8_t* key, const uint8_t* iv, uint8_t* plaintext);
+
+/**
+ * Encode the payload into TLV block with Authenticated GCM 128 Encryption
+ * @p tlv::type, intput, the TLV TYPE of the encoded block, either ApplicationParameters or Content
+ * @p key, intput, 16 Bytes, the AES key used for encryption
+ * @p payload, input, the plaintext payload
+ * @p payloadSize, input, the size of the plaintext payload
+ * @p associatedData, input, associated data used for authentication
+ * @p associatedDataSize, input, the size of associated data
+ * @return the TLV block with @p tlv::type TLV TYPE
+ */
+Block
+encodeBlockWithAesGcm128(uint32_t tlv_type, const uint8_t* key, const uint8_t* payload, size_t payloadSize,
+ const uint8_t* associatedData, size_t associatedDataSize);
+
+/**
+ * Decode the payload from TLV block with Authenticated GCM 128 Encryption
+ * @p block, intput, the TLV block in the format of NDNCERT protocol
+ * @p key, intput, 16 Bytes, the AES key used for encryption
+ * @p associatedData, input, associated data used for authentication
+ * @p associatedDataSize, input, the size of associated data
+ * @return the plaintext buffer
+ */
+Buffer
+decodeBlockWithAesGcm128(const Block& block, const uint8_t* key,
+ const uint8_t* associatedData, size_t associatedDataSize);
+
+} // namespace ndncert
+} // namespace ndn
+
+#endif // NDNCERT_PROTOCOL_DETAIL_CRYPTO_HELPER_HPP
diff --git a/src/detail/error-encoder.cpp b/src/detail/error-encoder.cpp
new file mode 100644
index 0000000..84b7866
--- /dev/null
+++ b/src/detail/error-encoder.cpp
@@ -0,0 +1,48 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2017-2020, Regents of the University of California.
+ *
+ * This file is part of ndncert, a certificate management system based on NDN.
+ *
+ * ndncert 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.
+ *
+ * ndncert 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 copies of the GNU General Public License along with
+ * ndncert, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndncert authors and contributors.
+ */
+
+#include "error-encoder.hpp"
+
+namespace ndn {
+namespace ndncert {
+
+Block
+ErrorEncoder::encodeDataContent(ErrorCode errorCode, const std::string& description)
+{
+ Block response = makeEmptyBlock(ndn::tlv::Content);
+ response.push_back(makeNonNegativeIntegerBlock(tlv::ErrorCode, static_cast<size_t>(errorCode)));
+ response.push_back(makeStringBlock(tlv::ErrorInfo, description));
+ response.encode();
+ return response;
+}
+
+std::tuple<ErrorCode, std::string>
+ErrorEncoder::decodefromDataContent(const Block& block)
+{
+ block.parse();
+ if (block.find(tlv::ErrorCode) == block.elements_end()) {
+ return std::make_tuple(ErrorCode::NO_ERROR, "");
+ }
+ ErrorCode error = static_cast<ErrorCode>(readNonNegativeInteger(block.get(tlv::ErrorCode)));
+ return std::make_tuple(error, readString(block.get(tlv::ErrorInfo)));
+}
+
+} // namespace ndncert
+} // namespace ndn
diff --git a/src/detail/error-encoder.hpp b/src/detail/error-encoder.hpp
new file mode 100644
index 0000000..76ecb36
--- /dev/null
+++ b/src/detail/error-encoder.hpp
@@ -0,0 +1,48 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2017-2020, Regents of the University of California.
+ *
+ * This file is part of ndncert, a certificate management system based on NDN.
+ *
+ * ndncert 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.
+ *
+ * ndncert 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 copies of the GNU General Public License along with
+ * ndncert, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndncert authors and contributors.
+ */
+
+#ifndef NDNCERT_PROTOCOL_DETAIL_ERROR_ENCODER_HPP
+#define NDNCERT_PROTOCOL_DETAIL_ERROR_ENCODER_HPP
+
+#include "../configuration.hpp"
+
+namespace ndn {
+namespace ndncert {
+
+class ErrorEncoder
+{
+public:
+ /**
+ * Encode error information into a Data content TLV
+ */
+ static Block
+ encodeDataContent(ErrorCode errorCode, const std::string& description);
+
+ /**
+ * Decode error information from Data content TLV
+ */
+ static std::tuple<ErrorCode, std::string>
+ decodefromDataContent(const Block& block);
+};
+
+} // namespace ndncert
+} // namespace ndn
+
+#endif // NDNCERT_PROTOCOL_DETAIL_ERROR_ENCODER_HPP
\ No newline at end of file
diff --git a/src/detail/info-encoder.cpp b/src/detail/info-encoder.cpp
new file mode 100644
index 0000000..7939526
--- /dev/null
+++ b/src/detail/info-encoder.cpp
@@ -0,0 +1,81 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2017-2020, Regents of the University of California.
+ *
+ * This file is part of ndncert, a certificate management system based on NDN.
+ *
+ * ndncert 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.
+ *
+ * ndncert 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 copies of the GNU General Public License along with
+ * ndncert, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndncert authors and contributors.
+ */
+
+#include "info-encoder.hpp"
+
+namespace ndn {
+namespace ndncert {
+
+Block
+InfoEncoder::encodeDataContent(const CaProfile& caConfig, const security::Certificate& certificate)
+{
+ auto content = makeEmptyBlock(ndn::tlv::Content);
+ content.push_back(makeNestedBlock(tlv::CaPrefix, caConfig.m_caPrefix));
+ std::string caInfo = "";
+ if (caConfig.m_caInfo == "") {
+ caInfo = "Issued by " + certificate.getSignatureInfo().getKeyLocator().getName().toUri();
+ }
+ else {
+ caInfo = caConfig.m_caInfo;
+ }
+ content.push_back(makeStringBlock(tlv::CaInfo, caInfo));
+ for (const auto& key : caConfig.m_probeParameterKeys) {
+ content.push_back(makeStringBlock(tlv::ParameterKey, key));
+ }
+ content.push_back(makeNonNegativeIntegerBlock(tlv::MaxValidityPeriod, caConfig.m_maxValidityPeriod.count()));
+ content.push_back(makeNestedBlock(tlv::CaCertificate, certificate));
+ content.encode();
+ return content;
+}
+
+CaProfile
+InfoEncoder::decodeDataContent(const Block& block)
+{
+ CaProfile result;
+ block.parse();
+ for (auto const& item : block.elements()) {
+ switch (item.type()) {
+ case tlv::CaPrefix:
+ item.parse();
+ result.m_caPrefix.wireDecode(item.get(ndn::tlv::Name));
+ break;
+ case tlv::CaInfo:
+ result.m_caInfo = readString(item);
+ break;
+ case tlv::ParameterKey:
+ result.m_probeParameterKeys.push_back(readString(item));
+ break;
+ case tlv::MaxValidityPeriod:
+ result.m_maxValidityPeriod = time::seconds(readNonNegativeInteger(item));
+ break;
+ case tlv::CaCertificate:
+ item.parse();
+ result.m_cert = std::make_shared<security::Certificate>(item.get(ndn::tlv::Data));
+ break;
+ default:
+ continue;
+ break;
+ }
+ }
+ return result;
+}
+
+} // namespace ndncert
+} // namespace ndn
\ No newline at end of file
diff --git a/src/detail/info-encoder.hpp b/src/detail/info-encoder.hpp
new file mode 100644
index 0000000..e317d5a
--- /dev/null
+++ b/src/detail/info-encoder.hpp
@@ -0,0 +1,48 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2017-2020, Regents of the University of California.
+ *
+ * This file is part of ndncert, a certificate management system based on NDN.
+ *
+ * ndncert 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.
+ *
+ * ndncert 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 copies of the GNU General Public License along with
+ * ndncert, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndncert authors and contributors.
+ */
+
+#ifndef NDNCERT_PROTOCOL_DETAIL_INFO_ENCODER_HPP
+#define NDNCERT_PROTOCOL_DETAIL_INFO_ENCODER_HPP
+
+#include "../configuration.hpp"
+
+namespace ndn {
+namespace ndncert {
+
+class InfoEncoder
+{
+public:
+ /**
+ * Encode CA configuration and its certificate into a TLV block as INFO Data packet content.
+ */
+ static Block
+ encodeDataContent(const CaProfile& caConfig, const security::Certificate& certificate);
+
+ /**
+ * Decode CA configuration from the TLV block of INFO Data packet content.
+ */
+ static CaProfile
+ decodeDataContent(const Block& block);
+};
+
+} // namespace ndncert
+} // namespace ndn
+
+#endif // NDNCERT_PROTOCOL_DETAIL_INFO_ENCODER_HPP
\ No newline at end of file
diff --git a/src/detail/ndncert-common.cpp b/src/detail/ndncert-common.cpp
new file mode 100644
index 0000000..1915082
--- /dev/null
+++ b/src/detail/ndncert-common.cpp
@@ -0,0 +1,57 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2017-2020, Regents of the University of California.
+ *
+ * This file is part of ndncert, a certificate management system based on NDN.
+ *
+ * ndncert 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.
+ *
+ * ndncert 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 copies of the GNU General Public License along with
+ * ndncert, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndncert authors and contributors.
+ */
+
+#include "ndncert-common.hpp"
+
+namespace ndn {
+namespace ndncert {
+
+const std::map<ErrorCode, std::string> errorCodeText = {
+ {ErrorCode::NO_ERROR, "NO_ERROR"},
+ {ErrorCode::BAD_INTEREST_FORMAT, "BAD_INTEREST_FORMAT"},
+ {ErrorCode::BAD_PARAMETER_FORMAT, "BAD_PARAMETER_FORMAT"},
+ {ErrorCode::BAD_SIGNATURE, "BAD_SIGNATURE"},
+ {ErrorCode::INVALID_PARAMETER, "INVALID_PARAMETER"},
+ {ErrorCode::NAME_NOT_ALLOWED, "NAME_NOT_ALLOWED"},
+ {ErrorCode::BAD_VALIDITY_PERIOD, "BAD_VALIDITY_PERIOD"},
+ {ErrorCode::OUT_OF_TRIES, "OUT_OF_TRIES"},
+ {ErrorCode::OUT_OF_TIME, "OUT_OF_TIME"},
+ {ErrorCode::NO_AVAILABLE_NAMES, "NO_AVAILABLE_NAMES"}
+};
+
+const std::map<RequestType, std::string> requestTypeText = {
+ {RequestType::NEW, "New"},
+ {RequestType::RENEW, "Renew"},
+ {RequestType::REVOKE, "Revoke"},
+ {RequestType::NOTINITIALIZED, "Not Initialized"},
+};
+
+std::string errorCodeToString(ErrorCode code)
+{
+ return errorCodeText.at(code);
+}
+
+std::string requestTypeToString(RequestType type)
+{
+ return requestTypeText.at(type);
+}
+
+} // namespace ndncert
+} // namespace ndn
diff --git a/src/detail/ndncert-common.hpp b/src/detail/ndncert-common.hpp
new file mode 100644
index 0000000..5805f74
--- /dev/null
+++ b/src/detail/ndncert-common.hpp
@@ -0,0 +1,132 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2017-2020, Regents of the University of California.
+ *
+ * This file is part of ndncert, a certificate management system based on NDN.
+ *
+ * ndncert 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.
+ *
+ * ndncert 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 copies of the GNU General Public License along with
+ * ndncert, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndncert authors and contributors.
+ */
+
+#ifndef NDNCERT_NDNCERT_COMMON_HPP
+#define NDNCERT_NDNCERT_COMMON_HPP
+
+#include "ndncert-config.hpp"
+
+#ifdef HAVE_TESTS
+#define VIRTUAL_WITH_TESTS virtual
+#define PUBLIC_WITH_TESTS_ELSE_PROTECTED public
+#define PUBLIC_WITH_TESTS_ELSE_PRIVATE public
+#define PROTECTED_WITH_TESTS_ELSE_PRIVATE protected
+#else
+#define VIRTUAL_WITH_TESTS
+#define PUBLIC_WITH_TESTS_ELSE_PROTECTED protected
+#define PUBLIC_WITH_TESTS_ELSE_PRIVATE private
+#define PROTECTED_WITH_TESTS_ELSE_PRIVATE private
+#endif
+
+#include <cstddef>
+#include <cstdint>
+#include <tuple>
+#include <ndn-cxx/encoding/tlv.hpp>
+#include <ndn-cxx/data.hpp>
+#include <ndn-cxx/encoding/block.hpp>
+#include <ndn-cxx/encoding/block-helpers.hpp>
+#include <ndn-cxx/face.hpp>
+#include <ndn-cxx/interest.hpp>
+#include <ndn-cxx/link.hpp>
+#include <ndn-cxx/lp/nack.hpp>
+#include <ndn-cxx/name.hpp>
+#include <ndn-cxx/security/key-chain.hpp>
+#include <ndn-cxx/security/certificate.hpp>
+#include <ndn-cxx/util/logger.hpp>
+#include <boost/algorithm/string.hpp>
+#include <boost/assert.hpp>
+#include <boost/noncopyable.hpp>
+#include <boost/property_tree/info_parser.hpp>
+#include <boost/property_tree/json_parser.hpp>
+#include <boost/property_tree/ptree.hpp>
+
+namespace ndn {
+namespace ndncert {
+
+namespace tlv {
+
+enum : uint32_t {
+ CaPrefix = 129,
+ CaInfo = 131,
+ ParameterKey = 133,
+ ParameterValue = 135,
+ CaCertificate = 137,
+ MaxValidityPeriod = 139,
+ ProbeResponse = 141,
+ MaxSuffixLength = 143,
+ EcdhPub = 145,
+ CertRequest = 147,
+ Salt = 149,
+ RequestId = 151,
+ Challenge = 153,
+ Status = 155,
+ InitializationVector = 157,
+ EncryptedPayload = 159,
+ SelectedChallenge = 161,
+ ChallengeStatus = 163,
+ RemainingTries = 165,
+ RemainingTime = 167,
+ IssuedCertName = 169,
+ ErrorCode = 171,
+ ErrorInfo = 173,
+ AuthenticationTag = 175,
+ CertToRevoke = 177,
+ ProbeRedirect = 179
+};
+
+} // namespace tlv
+
+using boost::noncopyable;
+typedef boost::property_tree::ptree JsonSection;
+
+// NDNCERT error code
+enum class ErrorCode : uint16_t {
+ NO_ERROR = 0,
+ BAD_INTEREST_FORMAT = 1,
+ BAD_PARAMETER_FORMAT = 2,
+ BAD_SIGNATURE = 3,
+ INVALID_PARAMETER = 4,
+ NAME_NOT_ALLOWED = 5,
+ BAD_VALIDITY_PERIOD = 6,
+ OUT_OF_TRIES = 7,
+ OUT_OF_TIME = 8,
+ NO_AVAILABLE_NAMES = 9
+};
+
+// Convert error code to string
+std::string
+errorCodeToString(ErrorCode code);
+
+// NDNCERT request type
+enum class RequestType : uint16_t {
+ NOTINITIALIZED = 0,
+ NEW = 1,
+ RENEW = 2,
+ REVOKE = 3
+};
+
+// Convert request type to string
+std::string
+requestTypeToString(RequestType type);
+
+} // namespace ndncert
+} // namespace ndn
+
+#endif // NDNCERT_NDNCERT_COMMON_HPP
diff --git a/src/detail/new-renew-revoke-encoder.cpp b/src/detail/new-renew-revoke-encoder.cpp
new file mode 100644
index 0000000..3afe2ad
--- /dev/null
+++ b/src/detail/new-renew-revoke-encoder.cpp
@@ -0,0 +1,111 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2017-2020, Regents of the University of California.
+ *
+ * This file is part of ndncert, a certificate management system based on NDN.
+ *
+ * ndncert 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.
+ *
+ * ndncert 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 copies of the GNU General Public License along with
+ * ndncert, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndncert authors and contributors.
+ */
+
+#include "new-renew-revoke-encoder.hpp"
+#include <ndn-cxx/security/transform/base64-encode.hpp>
+#include <ndn-cxx/security/transform/buffer-source.hpp>
+#include <ndn-cxx/security/transform/stream-sink.hpp>
+
+namespace ndn {
+namespace ndncert {
+
+NDN_LOG_INIT(ndncert.encoding.new_renew_revoke);
+
+Block
+NewRenewRevokeEncoder::encodeApplicationParameters(RequestType requestType, const std::string& ecdhPub, const security::Certificate& certRequest)
+{
+ Block request = makeEmptyBlock(ndn::tlv::ApplicationParameters);
+ std::stringstream ss;
+ try {
+ security::transform::bufferSource(certRequest.wireEncode().wire(), certRequest.wireEncode().size())
+ >> security::transform::base64Encode(false)
+ >> security::transform::streamSink(ss);
+ }
+ catch (const security::transform::Error& e) {
+ NDN_LOG_ERROR("Cannot convert self-signed cert into BASE64 string " << e.what());
+ return request;
+ }
+
+ request.push_back(makeStringBlock(tlv::EcdhPub, ecdhPub));
+ if (requestType == RequestType::NEW || requestType == RequestType::RENEW) {
+ request.push_back(makeNestedBlock(tlv::CertRequest, certRequest));
+ } else if (requestType == RequestType::REVOKE) {
+ request.push_back(makeNestedBlock(tlv::CertToRevoke, certRequest));
+ }
+ request.encode();
+ return request;
+}
+
+void
+NewRenewRevokeEncoder::decodeApplicationParameters(const Block& payload, RequestType requestType, std::string& ecdhPub,
+ shared_ptr<security::Certificate>& clientCert) {
+ payload.parse();
+
+ ecdhPub = readString(payload.get(tlv::EcdhPub));
+ Block requestPayload;
+ if (requestType == RequestType::NEW) {
+ requestPayload = payload.get(tlv::CertRequest);
+ }
+ else if (requestType == RequestType::REVOKE) {
+ requestPayload = payload.get(tlv::CertToRevoke);
+ }
+ requestPayload.parse();
+
+ security::Certificate cert = security::Certificate(requestPayload.get(ndn::tlv::Data));
+ clientCert =std::make_shared<security::Certificate>(cert);
+}
+
+Block
+NewRenewRevokeEncoder::encodeDataContent(const std::string& ecdhKey, const std::string& salt,
+ const CaState& request,
+ const std::list<std::string>& challenges)
+{
+ Block response = makeEmptyBlock(ndn::tlv::Content);
+ response.push_back(makeStringBlock(tlv::EcdhPub, ecdhKey));
+ response.push_back(makeStringBlock(tlv::Salt, salt));
+ response.push_back(makeStringBlock(tlv::RequestId, request.m_requestId));
+ response.push_back(makeNonNegativeIntegerBlock(tlv::Status, static_cast<size_t>(request.m_status)));
+ for (const auto& entry: challenges) {
+ response.push_back(makeStringBlock(tlv::Challenge, entry));
+ }
+ response.encode();
+ return response;
+}
+
+NewRenewRevokeEncoder::DecodedData
+NewRenewRevokeEncoder::decodeDataContent(const Block& content)
+{
+ content.parse();
+ const auto& ecdhKey = readString(content.get(tlv::EcdhPub));
+ const auto& salt = readString(content.get(tlv::Salt));
+ uint64_t saltInt = std::stoull(salt);
+ const auto& requestStatus = static_cast<Status>(readNonNegativeInteger(content.get(tlv::Status)));
+ const auto& requestId = readString(content.get(tlv::RequestId));
+ std::list<std::string> challenges;
+ for (auto const& element : content.elements()) {
+ if (element.type() == tlv::Challenge) {
+ challenges.push_back(readString(element));
+ }
+ }
+ return DecodedData{ecdhKey, saltInt, requestId, requestStatus, challenges};
+}
+
+} // namespace ndncert
+} // namespace ndn
\ No newline at end of file
diff --git a/src/detail/new-renew-revoke-encoder.hpp b/src/detail/new-renew-revoke-encoder.hpp
new file mode 100644
index 0000000..70e69aa
--- /dev/null
+++ b/src/detail/new-renew-revoke-encoder.hpp
@@ -0,0 +1,56 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2017-2020, Regents of the University of California.
+ *
+ * This file is part of ndncert, a certificate management system based on NDN.
+ *
+ * ndncert 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.
+ *
+ * ndncert 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 copies of the GNU General Public License along with
+ * ndncert, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndncert authors and contributors.
+ */
+
+#ifndef NDNCERT_PROTOCOL_DETAIL_NEW_RENEW_REVOKE_ENCODER_HPP
+#define NDNCERT_PROTOCOL_DETAIL_NEW_RENEW_REVOKE_ENCODER_HPP
+
+#include "../detail/ca-state.hpp"
+
+namespace ndn {
+namespace ndncert {
+
+class NewRenewRevokeEncoder
+{
+public:
+ static Block
+ encodeApplicationParameters(RequestType requestType, const std::string& ecdhPub, const security::Certificate& certRequest);
+
+ static void
+ decodeApplicationParameters(const Block& block, RequestType requestType, std::string& ecdhPub, shared_ptr<security::Certificate>& certRequest);
+
+ static Block
+ encodeDataContent(const std::string& ecdhKey, const std::string& salt,
+ const CaState& request,
+ const std::list<std::string>& challenges);
+ struct DecodedData {
+ std::string ecdhKey;
+ uint64_t salt;
+ std::string requestId;
+ Status requestStatus;
+ std::list<std::string> challenges;
+ };
+ static DecodedData
+ decodeDataContent(const Block& content);
+};
+
+} // namespace ndncert
+} // namespace ndn
+
+#endif // NDNCERT_PROTOCOL_DETAIL_NEW_RENEW_REVOKE_HPP
\ No newline at end of file
diff --git a/src/detail/probe-encoder.cpp b/src/detail/probe-encoder.cpp
new file mode 100644
index 0000000..ce3c3fe
--- /dev/null
+++ b/src/detail/probe-encoder.cpp
@@ -0,0 +1,106 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2017-2020, Regents of the University of California.
+ *
+ * This file is part of ndncert, a certificate management system based on NDN.
+ *
+ * ndncert 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.
+ *
+ * ndncert 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 copies of the GNU General Public License along with
+ * ndncert, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndncert authors and contributors.
+ */
+
+#include "probe-encoder.hpp"
+
+namespace ndn {
+namespace ndncert {
+
+Block
+ProbeEncoder::encodeApplicationParameters(std::vector<std::tuple<std::string, std::string>>&& parameters)
+{
+ auto content = makeEmptyBlock(ndn::tlv::ApplicationParameters);
+ for (size_t i = 0; i < parameters.size(); ++i) {
+ content.push_back(makeStringBlock(tlv::ParameterKey, std::get<0>(parameters[i])));
+ content.push_back(makeStringBlock(tlv::ParameterValue, std::get<1>(parameters[i])));
+ }
+ content.encode();
+ return content;
+}
+
+std::vector<std::tuple<std::string, std::string>>
+ProbeEncoder::decodeApplicationParameters(const Block& block)
+{
+ std::vector<std::tuple<std::string, std::string>> result;
+ block.parse();
+ for (size_t i = 0; i < block.elements().size() - 1; ++i) {
+ if (block.elements().at(i).type() == tlv::ParameterKey && block.elements().at(i + 1).type() == tlv::ParameterValue) {
+ result.push_back(std::make_tuple(readString(block.elements().at(i)), readString(block.elements().at(i + 1))));
+ }
+ }
+ return result;
+}
+
+Block
+ProbeEncoder::encodeDataContent(const std::vector<Name>& identifiers, boost::optional<size_t> maxSuffixLength,
+ boost::optional<std::vector<std::shared_ptr<security::Certificate>>> redirectionItems)
+{
+ Block content = makeEmptyBlock(ndn::tlv::Content);
+ for (const auto& name : identifiers) {
+ Block item(tlv::ProbeResponse);
+ item.push_back(name.wireEncode());
+ if (maxSuffixLength) {
+ item.push_back(makeNonNegativeIntegerBlock(tlv::MaxSuffixLength, *maxSuffixLength));
+ }
+ content.push_back(item);
+ }
+ if (redirectionItems) {
+ for (const auto& item : *redirectionItems) {
+ content.push_back(makeNestedBlock(tlv::ProbeRedirect, item->getFullName()));
+ }
+ }
+ content.encode();
+ return content;
+}
+
+void
+ProbeEncoder::decodeDataContent(const Block& block,
+ std::vector<std::pair<Name, int>>& availableNames,
+ std::vector<Name>& availableRedirection)
+{
+ block.parse();
+ for (const auto& item : block.elements()) {
+ if (item.type() == tlv::ProbeResponse) {
+ item.parse();
+ Name elementName;
+ int maxSuffixLength = 0;
+ for (const auto& subBlock: item.elements()) {
+ if (subBlock.type() == ndn::tlv::Name) {
+ if (!elementName.empty()) {
+ NDN_THROW(std::runtime_error("Invalid probe format"));
+ }
+ elementName.wireDecode(subBlock);
+ } else if (subBlock.type() == tlv::MaxSuffixLength) {
+ maxSuffixLength = readNonNegativeInteger(subBlock);
+ }
+ }
+ if (elementName.empty()) {
+ NDN_THROW(std::runtime_error("Invalid probe format"));
+ }
+ availableNames.emplace_back(elementName, maxSuffixLength);
+ }
+ if (item.type() == tlv::ProbeRedirect) {
+ availableRedirection.emplace_back(Name(item.blockFromValue()));
+ }
+ }
+}
+
+} // namespace ndncert
+} // namespace ndn
\ No newline at end of file
diff --git a/src/detail/probe-encoder.hpp b/src/detail/probe-encoder.hpp
new file mode 100644
index 0000000..c0e038e
--- /dev/null
+++ b/src/detail/probe-encoder.hpp
@@ -0,0 +1,53 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2017-2020, Regents of the University of California.
+ *
+ * This file is part of ndncert, a certificate management system based on NDN.
+ *
+ * ndncert 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.
+ *
+ * ndncert 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 copies of the GNU General Public License along with
+ * ndncert, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndncert authors and contributors.
+ */
+
+#ifndef NDNCERT_PROTOCOL_DETAIL_PROBE_ENCODER_HPP
+#define NDNCERT_PROTOCOL_DETAIL_PROBE_ENCODER_HPP
+
+#include "../configuration.hpp"
+
+namespace ndn {
+namespace ndncert {
+
+class ProbeEncoder
+{
+public:
+ // For Client use
+ static Block
+ encodeApplicationParameters(std::vector<std::tuple<std::string, std::string>>&& parameters);
+
+ static void
+ decodeDataContent(const Block& block, std::vector<std::pair<Name, int>>& availableNames,
+ std::vector<Name>& availableRedirection);
+
+ // For CA use
+ static Block
+ encodeDataContent(const std::vector<Name>& identifiers,
+ boost::optional<size_t> maxSuffixLength = boost::none,
+ boost::optional<std::vector<std::shared_ptr<security::Certificate>>> redirectionItems = boost::none);
+
+ static std::vector<std::tuple<std::string, std::string>>
+ decodeApplicationParameters(const Block& block);
+};
+
+} // namespace ndncert
+} // namespace ndn
+
+#endif // NDNCERT_PROTOCOL_DETAIL_PROBE_ENCODER_HPP
\ No newline at end of file