blob: c9a52c7ced0574b061bf79d3193bfc005143f772 [file] [log] [blame]
Zhiyi Zhangf5246c42017-01-26 09:39:20 -08001/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
swa770de007bc2020-03-24 21:26:21 -07002/**
Davide Pesaventob48bbda2020-07-27 19:41:37 -04003 * Copyright (c) 2017-2020, Regents of the University of California.
Zhiyi Zhangf5246c42017-01-26 09:39:20 -08004 *
5 * This file is part of ndncert, a certificate management system based on NDN.
6 *
7 * ndncert is free software: you can redistribute it and/or modify it under the terms
8 * of the GNU General Public License as published by the Free Software Foundation, either
9 * version 3 of the License, or (at your option) any later version.
10 *
11 * ndncert is distributed in the hope that it will be useful, but WITHOUT ANY
12 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
13 * PARTICULAR PURPOSE. See the GNU General Public License for more details.
14 *
15 * You should have received copies of the GNU General Public License along with
16 * ndncert, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
17 *
18 * See AUTHORS.md for complete list of ndncert authors and contributors.
19 */
20
21#include "ca-module.hpp"
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -070022
Zhiyi Zhangfc1678a2020-05-12 16:52:14 -070023#include <ndn-cxx/metadata-object.hpp>
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -070024#include <ndn-cxx/security/signing-helpers.hpp>
25#include <ndn-cxx/security/verification-helpers.hpp>
26#include <ndn-cxx/util/io.hpp>
27#include <ndn-cxx/util/random.hpp>
28
29#include "challenge-module.hpp"
30#include "crypto-support/enc-tlv.hpp"
31#include "logging.hpp"
32#include "protocol-detail/challenge.hpp"
33#include "protocol-detail/error.hpp"
34#include "protocol-detail/info.hpp"
35#include "protocol-detail/new.hpp"
36#include "protocol-detail/probe.hpp"
37#include "protocol-detail/revoke.hpp"
Zhiyi Zhangf5246c42017-01-26 09:39:20 -080038
39namespace ndn {
40namespace ndncert {
41
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070042static const int IS_SUBNAME_MIN_OFFSET = 5;
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -070043static const time::seconds DEFAULT_DATA_FRESHNESS_PERIOD = 1_s;
Zhiyi Zhang1a735bc2019-07-04 21:36:49 -070044static const time::seconds REQUEST_VALIDITY_PERIOD_NOT_BEFORE_GRACE_PERIOD = 120_s;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070045
Zhiyi Zhangf5246c42017-01-26 09:39:20 -080046_LOG_INIT(ndncert.ca);
47
48CaModule::CaModule(Face& face, security::v2::KeyChain& keyChain,
49 const std::string& configPath, const std::string& storageType)
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -070050 : m_face(face)
51 , m_keyChain(keyChain)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -080052{
Zhiyi Zhanga63b7372017-05-17 14:14:34 -070053 // load the config and create storage
Zhiyi Zhangf5246c42017-01-26 09:39:20 -080054 m_config.load(configPath);
55 m_storage = CaStorage::createCaStorage(storageType);
56
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +080057 registerPrefix();
Zhiyi Zhangf5246c42017-01-26 09:39:20 -080058}
59
60CaModule::~CaModule()
61{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070062 for (auto handle : m_interestFilterHandles) {
63 handle.cancel();
Zhiyi Zhangf5246c42017-01-26 09:39:20 -080064 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070065 for (auto handle : m_registeredPrefixHandles) {
66 handle.unregister();
Zhiyi Zhangf5246c42017-01-26 09:39:20 -080067 }
68}
69
70void
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +080071CaModule::registerPrefix()
72{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070073 // register localhop discovery prefix
swa77020643ac2020-03-26 02:24:45 -070074 Name localhopInfoPrefix("/localhop/CA/INFO");
75 auto prefixId = m_face.setInterestFilter(InterestFilter(localhopInfoPrefix),
76 bind(&CaModule::onInfo, this, _2),
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +080077 bind(&CaModule::onRegisterFailed, this, _2));
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070078 m_registeredPrefixHandles.push_back(prefixId);
swa77020643ac2020-03-26 02:24:45 -070079 _LOG_TRACE("Prefix " << localhopInfoPrefix << " got registered");
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +080080
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070081 // register prefixes
Suyong Won256c9062020-05-11 02:45:56 -070082 Name prefix = m_config.m_caPrefix;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070083 prefix.append("CA");
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +080084
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -070085 prefixId = m_face.registerPrefix(
86 prefix,
87 [&](const Name& name) {
88 // register INFO prefix
89 auto filterId = m_face.setInterestFilter(Name(name).append("INFO"),
90 bind(&CaModule::onInfo, this, _2));
91 m_interestFilterHandles.push_back(filterId);
swa77020643ac2020-03-26 02:24:45 -070092
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -070093 // register PROBE prefix
94 filterId = m_face.setInterestFilter(Name(name).append("PROBE"),
95 bind(&CaModule::onProbe, this, _2));
96 m_interestFilterHandles.push_back(filterId);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070097
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -070098 // register NEW prefix
99 filterId = m_face.setInterestFilter(Name(name).append("NEW"),
100 bind(&CaModule::onNew, this, _2));
101 m_interestFilterHandles.push_back(filterId);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700102
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700103 // register SELECT prefix
104 filterId = m_face.setInterestFilter(Name(name).append("CHALLENGE"),
105 bind(&CaModule::onChallenge, this, _2));
106 m_interestFilterHandles.push_back(filterId);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700107
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700108 // register REVOKE prefix
109 filterId = m_face.setInterestFilter(Name(name).append("REVOKE"),
110 bind(&CaModule::onRevoke, this, _2));
111 m_interestFilterHandles.push_back(filterId);
112 _LOG_TRACE("Prefix " << name << " got registered");
113 },
114 bind(&CaModule::onRegisterFailed, this, _2));
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700115 m_registeredPrefixHandles.push_back(prefixId);
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800116}
117
Zhiyi Zhangf6c5d272020-09-28 10:17:32 -0700118void
119CaModule::setNameAssignmentFunction(const NameAssignmentFunc& handler)
Zhiyi Zhang7420cf52017-12-18 18:59:21 +0800120{
Zhiyi Zhangf6c5d272020-09-28 10:17:32 -0700121 m_config.m_nameAssignmentFunc = handler;
Zhiyi Zhang7420cf52017-12-18 18:59:21 +0800122}
123
Zhiyi Zhang343cdfb2018-01-17 12:04:28 -0800124bool
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700125CaModule::setStatusUpdateCallback(const StatusUpdateCallback& onUpdateCallback)
Zhiyi Zhang7420cf52017-12-18 18:59:21 +0800126{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700127 m_config.m_statusUpdateCallback = onUpdateCallback;
Zhiyi Zhang343cdfb2018-01-17 12:04:28 -0800128 return false;
Zhiyi Zhang7420cf52017-12-18 18:59:21 +0800129}
130
Zhiyi Zhangfc1678a2020-05-12 16:52:14 -0700131shared_ptr<Data>
132CaModule::generateCaConfigMetaData()
swa77020643ac2020-03-26 02:24:45 -0700133{
Zhiyi Zhangfc1678a2020-05-12 16:52:14 -0700134 // @TODO
135 // make metadata a class member variable m_infoMetadata
136 // check whether the m_infoMetadata has the latest versioned name, if not, then generate a new one
137 // otherwise, directly reply m_infoMetadata.makeData
138
139 auto infoPacket = generateCaConfigData();
140 MetadataObject metadata;
141 metadata.setVersionedName(infoPacket->getName().getPrefix(-1));
142 Name discoveryInterestName(infoPacket->getName().getPrefix(-2));
143 name::Component metadataComponent(32, reinterpret_cast<const uint8_t*>("metadata"), std::strlen("metadata"));
144 discoveryInterestName.append(metadataComponent);
145 auto metadataData = metadata.makeData(discoveryInterestName, m_keyChain, signingByIdentity(m_config.m_caPrefix));
146 return make_shared<Data>(metadataData);
147}
148
149shared_ptr<Data>
150CaModule::generateCaConfigData()
151{
152 // @TODO
153 // make CaInfo Data packet a class member variable m_infoData
154 // check whether the m_infoData is still valid, if not, then generate a new one
155 // otherwise, directly reply m_infoData
Suyong Won19fba4d2020-05-09 13:39:46 -0700156
157 const auto& pib = m_keyChain.getPib();
Suyong Won256c9062020-05-11 02:45:56 -0700158 const auto& identity = pib.getIdentity(m_config.m_caPrefix);
Suyong Won19fba4d2020-05-09 13:39:46 -0700159 const auto& cert = identity.getDefaultKey().getDefaultCertificate();
Zhiyi Zhang61c43a62020-09-28 12:56:01 -0700160 Block contentTLV = INFO::encodeDataContent(m_config, cert);
swa77020643ac2020-03-26 02:24:45 -0700161
Zhiyi Zhangfc1678a2020-05-12 16:52:14 -0700162 Name infoPacketName(m_config.m_caPrefix);
163 infoPacketName.append("CA").append("INFO").appendVersion().appendSegment(0);
164 Data infoData(infoPacketName);
165 infoData.setContent(contentTLV);
166 infoData.setFreshnessPeriod(DEFAULT_DATA_FRESHNESS_PERIOD);
167 m_keyChain.sign(infoData, signingByIdentity(m_config.m_caPrefix));
168 return make_shared<Data>(infoData);
169}
swa77020643ac2020-03-26 02:24:45 -0700170
Zhiyi Zhangfc1678a2020-05-12 16:52:14 -0700171void
172CaModule::onInfo(const Interest& request)
173{
174 _LOG_TRACE("Received INFO request");
175
176 if (request.getName().get(-1).type() == 32) {
177 m_face.put(*generateCaConfigMetaData());
178 }
179 else {
180 m_face.put(*generateCaConfigData());
181 }
swa77020643ac2020-03-26 02:24:45 -0700182
183 _LOG_TRACE("Handle INFO: send out the INFO response");
184}
185
186void
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700187CaModule::onProbe(const Interest& request)
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800188{
swa77020643ac2020-03-26 02:24:45 -0700189 // PROBE Naming Convention: /<CA-Prefix>/CA/PROBE/[ParametersSha256DigestComponent]
190 _LOG_TRACE("Received PROBE request");
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800191
swa77020643ac2020-03-26 02:24:45 -0700192 // process PROBE requests: find an available name
Zhiyi Zhangf6c5d272020-09-28 10:17:32 -0700193 std::string availableId = "";
Suyong Won19fba4d2020-05-09 13:39:46 -0700194 const auto& parameterTLV = request.getApplicationParameters();
Suyong Won44d0cce2020-05-10 04:07:43 -0700195 parameterTLV.parse();
Suyong Won19fba4d2020-05-09 13:39:46 -0700196 if (!parameterTLV.hasValue()) {
197 _LOG_ERROR("Empty TLV obtained from the Interest parameter.");
swa77020643ac2020-03-26 02:24:45 -0700198 return;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700199 }
Suyong Won44d0cce2020-05-10 04:07:43 -0700200
Zhiyi Zhangf6c5d272020-09-28 10:17:32 -0700201 // if (m_config.m_nameAssignmentFunc) {
202 // try {
203 // availableId = m_config.m_nameAssignmentFunc(parameterTLV);
204 // }
205 // catch (const std::exception& e) {
206 // _LOG_TRACE("Cannot find PROBE input from PROBE parameters: " << e.what());
207 // return;
208 // }
209 // }
210 // else {
211 // // if there is no app-specified name lookup, use a random name id
212 // availableId = std::to_string(random::generateSecureWord64());
213 // }
214 // Name newIdentityName = m_config.m_caPrefix;
215 // newIdentityName.append(availableId);
216 // _LOG_TRACE("Handle PROBE: generate an identity " << newIdentityName);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800217
Zhiyi Zhangf6c5d272020-09-28 10:17:32 -0700218 // Block contentTLV = PROBE::encodeDataContent(newIdentityName.toUri(), m_config.m_probe, parameterTLV);
219
220 // Data result;
221 // result.setName(request.getName());
222 // result.setContent(contentTLV);
223 // result.setFreshnessPeriod(DEFAULT_DATA_FRESHNESS_PERIOD);
224 // m_keyChain.sign(result, signingByIdentity(m_config.m_caPrefix));
225 // m_face.put(result);
226 // _LOG_TRACE("Handle PROBE: send out the PROBE response");
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800227}
228
229void
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700230CaModule::onNew(const Interest& request)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800231{
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700232 // NEW Naming Convention: /<CA-prefix>/CA/NEW/[SignedInterestParameters_Digest]
233 onRequestInit(request, REQUEST_TYPE_NEW);
tylerliu4a00aad2020-09-26 02:03:17 -0700234}
235
236void
237CaModule::onRevoke(const Interest& request)
238{
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700239 // REVOKE Naming Convention: /<CA-prefix>/CA/REVOKE/[SignedInterestParameters_Digest]
240 onRequestInit(request, REQUEST_TYPE_REVOKE);
tylerliu4a00aad2020-09-26 02:03:17 -0700241}
242
243void
244CaModule::onRequestInit(const Interest& request, int requestType)
245{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700246 // get ECDH pub key and cert request
Suyong Won19fba4d2020-05-09 13:39:46 -0700247 const auto& parameterTLV = request.getApplicationParameters();
Suyong Won7968f7a2020-05-12 01:01:25 -0700248 parameterTLV.parse();
249
Suyong Won19fba4d2020-05-09 13:39:46 -0700250 if (!parameterTLV.hasValue()) {
251 _LOG_ERROR("Empty TLV obtained from the Interest parameter.");
Zhiyi Zhang547c8512019-06-18 23:46:14 -0700252 return;
253 }
Suyong Won19fba4d2020-05-09 13:39:46 -0700254
255 std::string peerKeyBase64 = readString(parameterTLV.get(tlv_ecdh_pub));
256
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700257 if (peerKeyBase64 == "") {
Suyong Won19fba4d2020-05-09 13:39:46 -0700258 _LOG_ERROR("Empty ECDH PUB obtained from the Interest parameter.");
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700259 return;
260 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700261
262 // get server's ECDH pub key
263 auto myEcdhPubKeyBase64 = m_ecdh.getBase64PubKey();
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700264 try {
265 m_ecdh.deriveSecret(peerKeyBase64);
266 }
267 catch (const std::exception& e) {
268 _LOG_ERROR("Cannot derive a shared secret using the provided ECDH key: " << e.what());
269 return;
270 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700271 // generate salt for HKDF
272 auto saltInt = random::generateSecureWord64();
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700273 // hkdf
274 hkdf(m_ecdh.context->sharedSecret, m_ecdh.context->sharedSecretLen,
Zhiyi Zhang36706832019-07-04 21:33:03 -0700275 (uint8_t*)&saltInt, sizeof(saltInt), m_aesKey, sizeof(m_aesKey));
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700276
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700277 shared_ptr<security::v2::Certificate> clientCert = nullptr;
Suyong Won7968f7a2020-05-12 01:01:25 -0700278
tylerliu4a00aad2020-09-26 02:03:17 -0700279 if (requestType == REQUEST_TYPE_NEW) {
280 // parse certificate request
281 Block cert_req = parameterTLV.get(tlv_cert_request);
282 cert_req.parse();
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700283
tylerliu4a00aad2020-09-26 02:03:17 -0700284 try {
285 security::v2::Certificate cert = security::v2::Certificate(cert_req.get(tlv::Data));
286 clientCert = make_shared<security::v2::Certificate>(cert);
287 }
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700288 catch (const std::exception& e) {
tylerliu4a00aad2020-09-26 02:03:17 -0700289 _LOG_ERROR("Unrecognized certificate request: " << e.what());
290 return;
291 }
292 // check the validity period
293 auto expectedPeriod = clientCert->getValidityPeriod().getPeriod();
294 auto currentTime = time::system_clock::now();
295 if (expectedPeriod.first < currentTime - REQUEST_VALIDITY_PERIOD_NOT_BEFORE_GRACE_PERIOD) {
296 _LOG_ERROR("Client requests a too old notBefore timepoint.");
297 return;
298 }
299 if (expectedPeriod.second > currentTime + m_config.m_maxValidityPeriod ||
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700300 expectedPeriod.second <= expectedPeriod.first) {
tylerliu4a00aad2020-09-26 02:03:17 -0700301 _LOG_ERROR("Client requests an invalid validity period or a notAfter timepoint beyond the allowed time period.");
302 return;
303 }
304
305 // verify the self-signed certificate, the request, and the token
306 if (!m_config.m_caPrefix.isPrefixOf(clientCert->getName()) // under ca prefix
307 || !security::v2::Certificate::isValidName(clientCert->getName()) // is valid cert name
tylerliu0b6d0db2020-09-28 17:52:02 -0700308 || clientCert->getName().size() < m_config.m_caPrefix.size() + IS_SUBNAME_MIN_OFFSET
309 || clientCert->getName().size() >
310 m_config.m_caPrefix.size() + IS_SUBNAME_MIN_OFFSET - 1 + m_config.m_maxSuffixLength) {
tylerliu4a00aad2020-09-26 02:03:17 -0700311 _LOG_ERROR("Invalid self-signed certificate name " << clientCert->getName());
312 return;
313 }
314 if (!security::verifySignature(*clientCert, *clientCert)) {
315 _LOG_ERROR("Cert request with bad signature.");
316 return;
317 }
318 if (!security::verifySignature(request, *clientCert)) {
319 _LOG_ERROR("Interest with bad signature.");
320 return;
321 }
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700322 }
323 else if (requestType == REQUEST_TYPE_REVOKE) {
tylerliu4a00aad2020-09-26 02:03:17 -0700324 // parse certificate request
325 Block cert_revoke = parameterTLV.get(tlv_cert_to_revoke);
326 cert_revoke.parse();
327
328 try {
329 security::v2::Certificate cert = security::v2::Certificate(cert_revoke.get(tlv::Data));
330 clientCert = make_shared<security::v2::Certificate>(cert);
331 }
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700332 catch (const std::exception& e) {
tylerliu4a00aad2020-09-26 02:03:17 -0700333 _LOG_ERROR("Unrecognized certificate: " << e.what());
334 return;
335 }
336
337 // verify the certificate
Zhiyi Zhangf6c5d272020-09-28 10:17:32 -0700338 if (!m_config.m_caPrefix.isPrefixOf(clientCert->getName()) // under ca prefix
tylerliu4a00aad2020-09-26 02:03:17 -0700339 || !security::v2::Certificate::isValidName(clientCert->getName()) // is valid cert name
tylerliu0b6d0db2020-09-28 17:52:02 -0700340 || clientCert->getName().size() < m_config.m_caPrefix.size() + IS_SUBNAME_MIN_OFFSET
341 || clientCert->getName().size() >
342 m_config.m_caPrefix.size() + IS_SUBNAME_MIN_OFFSET - 1 + m_config.m_maxSuffixLength) {
tylerliu4a00aad2020-09-26 02:03:17 -0700343 _LOG_ERROR("Invalid certificate name " << clientCert->getName());
344 return;
345 }
Zhiyi Zhangf6c5d272020-09-28 10:17:32 -0700346 const auto& cert = m_keyChain.getPib().getIdentity(m_config.m_caPrefix).getDefaultKey().getDefaultCertificate();
tylerliu4a00aad2020-09-26 02:03:17 -0700347 if (!security::verifySignature(*clientCert, cert)) {
348 _LOG_ERROR("Cert request with bad signature.");
349 return;
350 }
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700351 }
352
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700353 // create new request instance
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800354 std::string requestId = std::to_string(random::generateWord64());
Zhiyi Zhang48f23782020-09-28 12:11:24 -0700355 CertificateRequest certRequest(m_config.m_caPrefix, requestId, requestType, Status::BEFORE_CHALLENGE, *clientCert);
Suyong Won19fba4d2020-05-09 13:39:46 -0700356
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800357 try {
358 m_storage->addRequest(certRequest);
359 }
360 catch (const std::exception& e) {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700361 _LOG_ERROR("Cannot add new request instance into the storage: " << e.what());
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800362 return;
363 }
364
365 Data result;
366 result.setName(request.getName());
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700367 result.setFreshnessPeriod(DEFAULT_DATA_FRESHNESS_PERIOD);
tylerliu4a00aad2020-09-26 02:03:17 -0700368 if (requestType == REQUEST_TYPE_NEW) {
369 result.setContent(NEW::encodeDataContent(myEcdhPubKeyBase64,
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700370 std::to_string(saltInt),
371 certRequest,
372 m_config.m_supportedChallenges));
373 }
374 else if (requestType == REQUEST_TYPE_REVOKE) {
tylerliu4a00aad2020-09-26 02:03:17 -0700375 result.setContent(REVOKE::encodeDataContent(myEcdhPubKeyBase64,
376 std::to_string(saltInt),
377 certRequest,
378 m_config.m_supportedChallenges));
379 }
Suyong Won256c9062020-05-11 02:45:56 -0700380 m_keyChain.sign(result, signingByIdentity(m_config.m_caPrefix));
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800381 m_face.put(result);
Zhiyi Zhanga63b7372017-05-17 14:14:34 -0700382
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700383 if (m_config.m_statusUpdateCallback) {
384 m_config.m_statusUpdateCallback(certRequest);
Zhiyi Zhang7420cf52017-12-18 18:59:21 +0800385 }
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800386}
387
388void
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700389CaModule::onChallenge(const Interest& request)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800390{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700391 // get certificate request state
392 CertificateRequest certRequest = getCertificateRequest(request);
393 if (certRequest.m_requestId == "") {
394 // cannot get the request state
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700395 _LOG_ERROR("Cannot find certificate request state from CA's storage.");
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700396 m_face.put(generateErrorDataPacket(request.getName(), ErrorCode::INVALID_PARAMETER,
397 "Cannot find certificate request state from CA's storage."));
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800398 return;
399 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700400 // verify signature
401 if (!security::verifySignature(request, certRequest.m_cert)) {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700402 _LOG_ERROR("Challenge Interest with bad signature.");
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700403 m_face.put(generateErrorDataPacket(request.getName(), ErrorCode::BAD_SIGNATURE, "Bad signature."));
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800404 return;
405 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700406 // decrypt the parameters
Suyong Won19fba4d2020-05-09 13:39:46 -0700407 Buffer paramTLVPayload;
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700408 try {
Suyong Won19fba4d2020-05-09 13:39:46 -0700409 paramTLVPayload = decodeBlockWithAesGcm128(request.getApplicationParameters(), m_aesKey,
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700410 (uint8_t*)"test", strlen("test"));
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700411 }
412 catch (const std::exception& e) {
413 _LOG_ERROR("Cannot successfully decrypt the Interest parameters: " << e.what());
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700414 m_storage->deleteRequest(certRequest.m_requestId);
415 m_face.put(generateErrorDataPacket(request.getName(), ErrorCode::INVALID_PARAMETER,
416 "Cannot successfully decrypt the Interest parameters."));
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700417 return;
418 }
Suyong Won19fba4d2020-05-09 13:39:46 -0700419 if (paramTLVPayload.size() == 0) {
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700420 _LOG_ERROR("Got an empty buffer from content decryption.");
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700421 m_storage->deleteRequest(certRequest.m_requestId);
422 m_face.put(generateErrorDataPacket(request.getName(), ErrorCode::INVALID_PARAMETER,
423 "Empty buffer from content decryption."));
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700424 return;
425 }
Suyong Won44d0cce2020-05-10 04:07:43 -0700426 Block paramTLV = makeBinaryBlock(tlv_encrypted_payload, paramTLVPayload.data(), paramTLVPayload.size());
427 paramTLV.parse();
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800428
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700429 // load the corresponding challenge module
Suyong Won19fba4d2020-05-09 13:39:46 -0700430 std::string challengeType = readString(paramTLV.get(tlv_selected_challenge));
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800431 auto challenge = ChallengeModule::createChallengeModule(challengeType);
432 if (challenge == nullptr) {
433 _LOG_TRACE("Unrecognized challenge type " << challengeType);
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700434 m_storage->deleteRequest(certRequest.m_requestId);
435 m_face.put(generateErrorDataPacket(request.getName(), ErrorCode::INVALID_PARAMETER, "Unrecognized challenge type"));
436 return;
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800437 }
Suyong Won19fba4d2020-05-09 13:39:46 -0700438
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700439 _LOG_TRACE("CHALLENGE module to be load: " << challengeType);
440 auto errorInfo = challenge->handleChallengeRequest(paramTLV, certRequest);
441 if (std::get<0>(errorInfo) != ErrorCode::NO_ERROR) {
442 m_storage->deleteRequest(certRequest.m_requestId);
443 m_face.put(generateErrorDataPacket(request.getName(), std::get<0>(errorInfo), std::get<1>(errorInfo)));
444 return;
445 }
Suyong Won19fba4d2020-05-09 13:39:46 -0700446
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700447 Block payload;
448 if (certRequest.m_status == Status::PENDING) {
449 // if challenge succeeded
450 if (certRequest.m_requestType == REQUEST_TYPE_NEW) {
451 auto issuedCert = issueCertificate(certRequest);
452 certRequest.m_cert = issuedCert;
453 certRequest.m_status = Status::SUCCESS;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700454 try {
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700455 m_storage->addCertificate(certRequest.m_requestId, issuedCert);
456 m_storage->deleteRequest(certRequest.m_requestId);
457 _LOG_TRACE("New Certificate Issued " << issuedCert.getName());
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700458 }
459 catch (const std::exception& e) {
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700460 _LOG_ERROR("Cannot add issued cert and remove the request: " << e.what());
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700461 return;
462 }
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700463
Suyong Won44d0cce2020-05-10 04:07:43 -0700464 payload = CHALLENGE::encodeDataPayload(certRequest);
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700465 payload.parse();
466 payload.push_back(makeNestedBlock(tlv_issued_cert_name, issuedCert.getName()));
467 payload.encode();
468
469 //contentJson.add(JSON_CA_CERT_ID, readString(issuedCert.getName().at(-1)));
470 _LOG_TRACE("Challenge succeeded. Certificate has been issued");
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800471 }
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700472 else if (certRequest.m_requestType == REQUEST_TYPE_REVOKE) {
473 certRequest.m_status = Status::SUCCESS;
474 try {
475 m_storage->deleteRequest(certRequest.m_requestId);
476 _LOG_TRACE("Certificate Revoked");
477 }
478 catch (const std::exception& e) {
479 _LOG_ERROR("Cannot add issued cert and remove the request: " << e.what());
480 return;
481 }
482
483 payload = CHALLENGE::encodeDataPayload(certRequest);
484 payload.parse();
485 _LOG_TRACE("Challenge succeeded. Certificate has been revoked");
486 }
487 }
488 else {
489 m_storage->updateRequest(certRequest);
490 payload = CHALLENGE::encodeDataPayload(certRequest);
491 _LOG_TRACE("No failure no success. Challenge moves on");
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800492 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700493
494 Data result;
495 result.setName(request.getName());
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700496 result.setFreshnessPeriod(DEFAULT_DATA_FRESHNESS_PERIOD);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700497
498 // encrypt the content
Suyong Won7968f7a2020-05-12 01:01:25 -0700499 auto contentBlock = encodeBlockWithAesGcm128(tlv::Content, m_aesKey, payload.value(),
500 payload.value_size(), (uint8_t*)"test", strlen("test"));
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700501 result.setContent(contentBlock);
Suyong Won256c9062020-05-11 02:45:56 -0700502 m_keyChain.sign(result, signingByIdentity(m_config.m_caPrefix));
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700503 m_face.put(result);
504
505 if (m_config.m_statusUpdateCallback) {
506 m_config.m_statusUpdateCallback(certRequest);
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800507 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700508}
509
Zhiyi Zhang343cdfb2018-01-17 12:04:28 -0800510security::v2::Certificate
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700511CaModule::issueCertificate(const CertificateRequest& certRequest)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800512{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700513 auto expectedPeriod =
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700514 certRequest.m_cert.getValidityPeriod().getPeriod();
Zhiyi Zhang1a735bc2019-07-04 21:36:49 -0700515 security::ValidityPeriod period(expectedPeriod.first, expectedPeriod.second);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800516 security::v2::Certificate newCert;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700517
518 Name certName = certRequest.m_cert.getKeyName();
519 certName.append("NDNCERT").append(std::to_string(random::generateSecureWord64()));
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800520 newCert.setName(certName);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700521 newCert.setContent(certRequest.m_cert.getContent());
522 _LOG_TRACE("cert request content " << certRequest.m_cert);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800523 SignatureInfo signatureInfo;
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800524 signatureInfo.setValidityPeriod(period);
Zhiyi Zhangad6cf932017-10-26 16:19:15 -0700525 security::SigningInfo signingInfo(security::SigningInfo::SIGNER_TYPE_ID,
Suyong Won256c9062020-05-11 02:45:56 -0700526 m_config.m_caPrefix, signatureInfo);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800527
528 m_keyChain.sign(newCert, signingInfo);
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700529 _LOG_TRACE("new cert got signed" << newCert);
Zhiyi Zhang343cdfb2018-01-17 12:04:28 -0800530 return newCert;
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800531}
532
533CertificateRequest
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700534CaModule::getCertificateRequest(const Interest& request)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800535{
Davide Pesaventob48bbda2020-07-27 19:41:37 -0400536 std::string requestId;
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800537 CertificateRequest certRequest;
538 try {
Suyong Won256c9062020-05-11 02:45:56 -0700539 requestId = readString(request.getName().at(m_config.m_caPrefix.size() + 2));
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700540 }
541 catch (const std::exception& e) {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700542 _LOG_ERROR("Cannot read the request ID out from the request: " << e.what());
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700543 }
544 try {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700545 _LOG_TRACE("Request Id to query the database " << requestId);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800546 certRequest = m_storage->getRequest(requestId);
547 }
548 catch (const std::exception& e) {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700549 _LOG_ERROR("Cannot get certificate request record from the storage: " << e.what());
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800550 }
551 return certRequest;
552}
553
554void
555CaModule::onRegisterFailed(const std::string& reason)
556{
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700557 _LOG_ERROR("Failed to register prefix in local hub's daemon, REASON: " << reason);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800558}
559
560Block
561CaModule::dataContentFromJson(const JsonSection& jsonSection)
562{
563 std::stringstream ss;
564 boost::property_tree::write_json(ss, jsonSection);
565 return makeStringBlock(ndn::tlv::Content, ss.str());
566}
567
568JsonSection
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700569CaModule::jsonFromBlock(const Block& block)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800570{
571 std::string jsonString;
572 try {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700573 jsonString = encoding::readString(block);
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700574 std::istringstream ss(jsonString);
575 JsonSection json;
576 boost::property_tree::json_parser::read_json(ss, json);
577 return json;
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800578 }
579 catch (const std::exception& e) {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700580 _LOG_ERROR("Cannot read JSON string from TLV Value: " << e.what());
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800581 return JsonSection();
582 }
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800583}
584
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700585Data
586CaModule::generateErrorDataPacket(const Name& name, ErrorCode error, const std::string& errorInfo)
587{
588 Data result;
589 result.setName(name);
590 result.setFreshnessPeriod(DEFAULT_DATA_FRESHNESS_PERIOD);
591 result.setContent(ErrorTLV::encodeDataContent(error, errorInfo));
592 m_keyChain.sign(result, signingByIdentity(m_config.m_caPrefix));
593 return result;
594}
595
596} // namespace ndncert
597} // namespace ndn