blob: 5a16ab3e5a81330ab6faa8641b7d6af3ddb55802 [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 Zhang42e1cf32019-06-22 17:11:42 -070042static const time::seconds DEFAULT_DATA_FRESHNESS_PERIOD = 1_s;
Zhiyi Zhang1a735bc2019-07-04 21:36:49 -070043static const time::seconds REQUEST_VALIDITY_PERIOD_NOT_BEFORE_GRACE_PERIOD = 120_s;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070044
Zhiyi Zhangf5246c42017-01-26 09:39:20 -080045_LOG_INIT(ndncert.ca);
46
47CaModule::CaModule(Face& face, security::v2::KeyChain& keyChain,
48 const std::string& configPath, const std::string& storageType)
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -070049 : m_face(face)
50 , m_keyChain(keyChain)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -080051{
Zhiyi Zhanga63b7372017-05-17 14:14:34 -070052 // load the config and create storage
Zhiyi Zhangf5246c42017-01-26 09:39:20 -080053 m_config.load(configPath);
54 m_storage = CaStorage::createCaStorage(storageType);
55
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +080056 registerPrefix();
Zhiyi Zhangf5246c42017-01-26 09:39:20 -080057}
58
59CaModule::~CaModule()
60{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070061 for (auto handle : m_interestFilterHandles) {
62 handle.cancel();
Zhiyi Zhangf5246c42017-01-26 09:39:20 -080063 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070064 for (auto handle : m_registeredPrefixHandles) {
65 handle.unregister();
Zhiyi Zhangf5246c42017-01-26 09:39:20 -080066 }
67}
68
69void
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +080070CaModule::registerPrefix()
71{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070072 // register localhop discovery prefix
swa77020643ac2020-03-26 02:24:45 -070073 Name localhopInfoPrefix("/localhop/CA/INFO");
74 auto prefixId = m_face.setInterestFilter(InterestFilter(localhopInfoPrefix),
75 bind(&CaModule::onInfo, this, _2),
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +080076 bind(&CaModule::onRegisterFailed, this, _2));
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070077 m_registeredPrefixHandles.push_back(prefixId);
swa77020643ac2020-03-26 02:24:45 -070078 _LOG_TRACE("Prefix " << localhopInfoPrefix << " got registered");
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +080079
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070080 // register prefixes
Suyong Won256c9062020-05-11 02:45:56 -070081 Name prefix = m_config.m_caPrefix;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070082 prefix.append("CA");
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +080083
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -070084 prefixId = m_face.registerPrefix(
85 prefix,
86 [&](const Name& name) {
87 // register INFO prefix
88 auto filterId = m_face.setInterestFilter(Name(name).append("INFO"),
89 bind(&CaModule::onInfo, this, _2));
90 m_interestFilterHandles.push_back(filterId);
swa77020643ac2020-03-26 02:24:45 -070091
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -070092 // register PROBE prefix
93 filterId = m_face.setInterestFilter(Name(name).append("PROBE"),
94 bind(&CaModule::onProbe, this, _2));
95 m_interestFilterHandles.push_back(filterId);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070096
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -070097 // register NEW prefix
98 filterId = m_face.setInterestFilter(Name(name).append("NEW"),
99 bind(&CaModule::onNew, this, _2));
100 m_interestFilterHandles.push_back(filterId);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700101
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700102 // register SELECT prefix
103 filterId = m_face.setInterestFilter(Name(name).append("CHALLENGE"),
104 bind(&CaModule::onChallenge, this, _2));
105 m_interestFilterHandles.push_back(filterId);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700106
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700107 // register REVOKE prefix
108 filterId = m_face.setInterestFilter(Name(name).append("REVOKE"),
109 bind(&CaModule::onRevoke, this, _2));
110 m_interestFilterHandles.push_back(filterId);
111 _LOG_TRACE("Prefix " << name << " got registered");
112 },
113 bind(&CaModule::onRegisterFailed, this, _2));
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700114 m_registeredPrefixHandles.push_back(prefixId);
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800115}
116
Zhiyi Zhangf6c5d272020-09-28 10:17:32 -0700117void
118CaModule::setNameAssignmentFunction(const NameAssignmentFunc& handler)
Zhiyi Zhang7420cf52017-12-18 18:59:21 +0800119{
Zhiyi Zhangf6c5d272020-09-28 10:17:32 -0700120 m_config.m_nameAssignmentFunc = handler;
Zhiyi Zhang7420cf52017-12-18 18:59:21 +0800121}
122
Zhiyi Zhang343cdfb2018-01-17 12:04:28 -0800123bool
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700124CaModule::setStatusUpdateCallback(const StatusUpdateCallback& onUpdateCallback)
Zhiyi Zhang7420cf52017-12-18 18:59:21 +0800125{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700126 m_config.m_statusUpdateCallback = onUpdateCallback;
Zhiyi Zhang343cdfb2018-01-17 12:04:28 -0800127 return false;
Zhiyi Zhang7420cf52017-12-18 18:59:21 +0800128}
129
Zhiyi Zhangfc1678a2020-05-12 16:52:14 -0700130shared_ptr<Data>
131CaModule::generateCaConfigMetaData()
swa77020643ac2020-03-26 02:24:45 -0700132{
Zhiyi Zhangfc1678a2020-05-12 16:52:14 -0700133 // @TODO
134 // make metadata a class member variable m_infoMetadata
135 // check whether the m_infoMetadata has the latest versioned name, if not, then generate a new one
136 // otherwise, directly reply m_infoMetadata.makeData
137
138 auto infoPacket = generateCaConfigData();
139 MetadataObject metadata;
140 metadata.setVersionedName(infoPacket->getName().getPrefix(-1));
141 Name discoveryInterestName(infoPacket->getName().getPrefix(-2));
142 name::Component metadataComponent(32, reinterpret_cast<const uint8_t*>("metadata"), std::strlen("metadata"));
143 discoveryInterestName.append(metadataComponent);
144 auto metadataData = metadata.makeData(discoveryInterestName, m_keyChain, signingByIdentity(m_config.m_caPrefix));
145 return make_shared<Data>(metadataData);
146}
147
148shared_ptr<Data>
149CaModule::generateCaConfigData()
150{
151 // @TODO
152 // make CaInfo Data packet a class member variable m_infoData
153 // check whether the m_infoData is still valid, if not, then generate a new one
154 // otherwise, directly reply m_infoData
Suyong Won19fba4d2020-05-09 13:39:46 -0700155
156 const auto& pib = m_keyChain.getPib();
Suyong Won256c9062020-05-11 02:45:56 -0700157 const auto& identity = pib.getIdentity(m_config.m_caPrefix);
Suyong Won19fba4d2020-05-09 13:39:46 -0700158 const auto& cert = identity.getDefaultKey().getDefaultCertificate();
Zhiyi Zhang61c43a62020-09-28 12:56:01 -0700159 Block contentTLV = INFO::encodeDataContent(m_config, cert);
swa77020643ac2020-03-26 02:24:45 -0700160
Zhiyi Zhangfc1678a2020-05-12 16:52:14 -0700161 Name infoPacketName(m_config.m_caPrefix);
162 infoPacketName.append("CA").append("INFO").appendVersion().appendSegment(0);
163 Data infoData(infoPacketName);
164 infoData.setContent(contentTLV);
165 infoData.setFreshnessPeriod(DEFAULT_DATA_FRESHNESS_PERIOD);
166 m_keyChain.sign(infoData, signingByIdentity(m_config.m_caPrefix));
167 return make_shared<Data>(infoData);
168}
swa77020643ac2020-03-26 02:24:45 -0700169
Zhiyi Zhangfc1678a2020-05-12 16:52:14 -0700170void
171CaModule::onInfo(const Interest& request)
172{
173 _LOG_TRACE("Received INFO request");
174
175 if (request.getName().get(-1).type() == 32) {
176 m_face.put(*generateCaConfigMetaData());
177 }
178 else {
179 m_face.put(*generateCaConfigData());
180 }
swa77020643ac2020-03-26 02:24:45 -0700181
182 _LOG_TRACE("Handle INFO: send out the INFO response");
183}
184
185void
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700186CaModule::onProbe(const Interest& request)
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800187{
swa77020643ac2020-03-26 02:24:45 -0700188 // PROBE Naming Convention: /<CA-Prefix>/CA/PROBE/[ParametersSha256DigestComponent]
189 _LOG_TRACE("Received PROBE request");
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800190
swa77020643ac2020-03-26 02:24:45 -0700191 // process PROBE requests: find an available name
Zhiyi Zhangf6c5d272020-09-28 10:17:32 -0700192 std::string availableId = "";
Suyong Won19fba4d2020-05-09 13:39:46 -0700193 const auto& parameterTLV = request.getApplicationParameters();
Suyong Won44d0cce2020-05-10 04:07:43 -0700194 parameterTLV.parse();
Suyong Won19fba4d2020-05-09 13:39:46 -0700195 if (!parameterTLV.hasValue()) {
196 _LOG_ERROR("Empty TLV obtained from the Interest parameter.");
swa77020643ac2020-03-26 02:24:45 -0700197 return;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700198 }
Suyong Won44d0cce2020-05-10 04:07:43 -0700199
Zhiyi Zhangf6c5d272020-09-28 10:17:32 -0700200 // if (m_config.m_nameAssignmentFunc) {
201 // try {
202 // availableId = m_config.m_nameAssignmentFunc(parameterTLV);
203 // }
204 // catch (const std::exception& e) {
205 // _LOG_TRACE("Cannot find PROBE input from PROBE parameters: " << e.what());
206 // return;
207 // }
208 // }
209 // else {
210 // // if there is no app-specified name lookup, use a random name id
211 // availableId = std::to_string(random::generateSecureWord64());
212 // }
213 // Name newIdentityName = m_config.m_caPrefix;
214 // newIdentityName.append(availableId);
215 // _LOG_TRACE("Handle PROBE: generate an identity " << newIdentityName);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800216
Zhiyi Zhangf6c5d272020-09-28 10:17:32 -0700217 // Block contentTLV = PROBE::encodeDataContent(newIdentityName.toUri(), m_config.m_probe, parameterTLV);
218
219 // Data result;
220 // result.setName(request.getName());
221 // result.setContent(contentTLV);
222 // result.setFreshnessPeriod(DEFAULT_DATA_FRESHNESS_PERIOD);
223 // m_keyChain.sign(result, signingByIdentity(m_config.m_caPrefix));
224 // m_face.put(result);
225 // _LOG_TRACE("Handle PROBE: send out the PROBE response");
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800226}
227
228void
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700229CaModule::onNew(const Interest& request)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800230{
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700231 // NEW Naming Convention: /<CA-prefix>/CA/NEW/[SignedInterestParameters_Digest]
232 onRequestInit(request, REQUEST_TYPE_NEW);
tylerliu4a00aad2020-09-26 02:03:17 -0700233}
234
235void
236CaModule::onRevoke(const Interest& request)
237{
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700238 // REVOKE Naming Convention: /<CA-prefix>/CA/REVOKE/[SignedInterestParameters_Digest]
239 onRequestInit(request, REQUEST_TYPE_REVOKE);
tylerliu4a00aad2020-09-26 02:03:17 -0700240}
241
242void
243CaModule::onRequestInit(const Interest& request, int requestType)
244{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700245 // get ECDH pub key and cert request
Suyong Won19fba4d2020-05-09 13:39:46 -0700246 const auto& parameterTLV = request.getApplicationParameters();
Suyong Won7968f7a2020-05-12 01:01:25 -0700247 parameterTLV.parse();
248
Suyong Won19fba4d2020-05-09 13:39:46 -0700249 if (!parameterTLV.hasValue()) {
250 _LOG_ERROR("Empty TLV obtained from the Interest parameter.");
Zhiyi Zhang547c8512019-06-18 23:46:14 -0700251 return;
252 }
Suyong Won19fba4d2020-05-09 13:39:46 -0700253
254 std::string peerKeyBase64 = readString(parameterTLV.get(tlv_ecdh_pub));
255
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700256 if (peerKeyBase64 == "") {
Suyong Won19fba4d2020-05-09 13:39:46 -0700257 _LOG_ERROR("Empty ECDH PUB obtained from the Interest parameter.");
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700258 return;
259 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700260
261 // get server's ECDH pub key
262 auto myEcdhPubKeyBase64 = m_ecdh.getBase64PubKey();
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700263 try {
264 m_ecdh.deriveSecret(peerKeyBase64);
265 }
266 catch (const std::exception& e) {
267 _LOG_ERROR("Cannot derive a shared secret using the provided ECDH key: " << e.what());
268 return;
269 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700270 // generate salt for HKDF
271 auto saltInt = random::generateSecureWord64();
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700272 // hkdf
273 hkdf(m_ecdh.context->sharedSecret, m_ecdh.context->sharedSecretLen,
Zhiyi Zhang36706832019-07-04 21:33:03 -0700274 (uint8_t*)&saltInt, sizeof(saltInt), m_aesKey, sizeof(m_aesKey));
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700275
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700276 shared_ptr<security::v2::Certificate> clientCert = nullptr;
Suyong Won7968f7a2020-05-12 01:01:25 -0700277
tylerliu4a00aad2020-09-26 02:03:17 -0700278 if (requestType == REQUEST_TYPE_NEW) {
279 // parse certificate request
280 Block cert_req = parameterTLV.get(tlv_cert_request);
281 cert_req.parse();
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700282
tylerliu4a00aad2020-09-26 02:03:17 -0700283 try {
284 security::v2::Certificate cert = security::v2::Certificate(cert_req.get(tlv::Data));
285 clientCert = make_shared<security::v2::Certificate>(cert);
286 }
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700287 catch (const std::exception& e) {
tylerliu4a00aad2020-09-26 02:03:17 -0700288 _LOG_ERROR("Unrecognized certificate request: " << e.what());
289 return;
290 }
291 // check the validity period
292 auto expectedPeriod = clientCert->getValidityPeriod().getPeriod();
293 auto currentTime = time::system_clock::now();
294 if (expectedPeriod.first < currentTime - REQUEST_VALIDITY_PERIOD_NOT_BEFORE_GRACE_PERIOD) {
295 _LOG_ERROR("Client requests a too old notBefore timepoint.");
296 return;
297 }
298 if (expectedPeriod.second > currentTime + m_config.m_maxValidityPeriod ||
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700299 expectedPeriod.second <= expectedPeriod.first) {
tylerliu4a00aad2020-09-26 02:03:17 -0700300 _LOG_ERROR("Client requests an invalid validity period or a notAfter timepoint beyond the allowed time period.");
301 return;
302 }
303
304 // verify the self-signed certificate, the request, and the token
305 if (!m_config.m_caPrefix.isPrefixOf(clientCert->getName()) // under ca prefix
306 || !security::v2::Certificate::isValidName(clientCert->getName()) // is valid cert name
tylerliuc84c3ba2020-09-28 18:09:46 -0700307 || clientCert->getIdentity().size() <= m_config.m_caPrefix.size()
308 || clientCert->getIdentity().size() > m_config.m_caPrefix.size() + m_config.m_maxSuffixLength) {
tylerliu4a00aad2020-09-26 02:03:17 -0700309 _LOG_ERROR("Invalid self-signed certificate name " << clientCert->getName());
310 return;
311 }
312 if (!security::verifySignature(*clientCert, *clientCert)) {
313 _LOG_ERROR("Cert request with bad signature.");
314 return;
315 }
316 if (!security::verifySignature(request, *clientCert)) {
317 _LOG_ERROR("Interest with bad signature.");
318 return;
319 }
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700320 }
321 else if (requestType == REQUEST_TYPE_REVOKE) {
tylerliu4a00aad2020-09-26 02:03:17 -0700322 // parse certificate request
323 Block cert_revoke = parameterTLV.get(tlv_cert_to_revoke);
324 cert_revoke.parse();
325
326 try {
327 security::v2::Certificate cert = security::v2::Certificate(cert_revoke.get(tlv::Data));
328 clientCert = make_shared<security::v2::Certificate>(cert);
329 }
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700330 catch (const std::exception& e) {
tylerliu4a00aad2020-09-26 02:03:17 -0700331 _LOG_ERROR("Unrecognized certificate: " << e.what());
332 return;
333 }
334
335 // verify the certificate
Zhiyi Zhangf6c5d272020-09-28 10:17:32 -0700336 if (!m_config.m_caPrefix.isPrefixOf(clientCert->getName()) // under ca prefix
tylerliu4a00aad2020-09-26 02:03:17 -0700337 || !security::v2::Certificate::isValidName(clientCert->getName()) // is valid cert name
tylerliuc84c3ba2020-09-28 18:09:46 -0700338 || clientCert->getIdentity().size() <= m_config.m_caPrefix.size()
339 || clientCert->getIdentity().size() > m_config.m_caPrefix.size() + m_config.m_maxSuffixLength) {
tylerliu4a00aad2020-09-26 02:03:17 -0700340 _LOG_ERROR("Invalid certificate name " << clientCert->getName());
341 return;
342 }
Zhiyi Zhangf6c5d272020-09-28 10:17:32 -0700343 const auto& cert = m_keyChain.getPib().getIdentity(m_config.m_caPrefix).getDefaultKey().getDefaultCertificate();
tylerliu4a00aad2020-09-26 02:03:17 -0700344 if (!security::verifySignature(*clientCert, cert)) {
345 _LOG_ERROR("Cert request with bad signature.");
346 return;
347 }
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700348 }
349
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700350 // create new request instance
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800351 std::string requestId = std::to_string(random::generateWord64());
Zhiyi Zhang48f23782020-09-28 12:11:24 -0700352 CertificateRequest certRequest(m_config.m_caPrefix, requestId, requestType, Status::BEFORE_CHALLENGE, *clientCert);
Suyong Won19fba4d2020-05-09 13:39:46 -0700353
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800354 try {
355 m_storage->addRequest(certRequest);
356 }
357 catch (const std::exception& e) {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700358 _LOG_ERROR("Cannot add new request instance into the storage: " << e.what());
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800359 return;
360 }
361
362 Data result;
363 result.setName(request.getName());
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700364 result.setFreshnessPeriod(DEFAULT_DATA_FRESHNESS_PERIOD);
tylerliu4a00aad2020-09-26 02:03:17 -0700365 if (requestType == REQUEST_TYPE_NEW) {
366 result.setContent(NEW::encodeDataContent(myEcdhPubKeyBase64,
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700367 std::to_string(saltInt),
368 certRequest,
369 m_config.m_supportedChallenges));
370 }
371 else if (requestType == REQUEST_TYPE_REVOKE) {
tylerliu4a00aad2020-09-26 02:03:17 -0700372 result.setContent(REVOKE::encodeDataContent(myEcdhPubKeyBase64,
373 std::to_string(saltInt),
374 certRequest,
375 m_config.m_supportedChallenges));
376 }
Suyong Won256c9062020-05-11 02:45:56 -0700377 m_keyChain.sign(result, signingByIdentity(m_config.m_caPrefix));
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800378 m_face.put(result);
Zhiyi Zhanga63b7372017-05-17 14:14:34 -0700379
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700380 if (m_config.m_statusUpdateCallback) {
381 m_config.m_statusUpdateCallback(certRequest);
Zhiyi Zhang7420cf52017-12-18 18:59:21 +0800382 }
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800383}
384
385void
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700386CaModule::onChallenge(const Interest& request)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800387{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700388 // get certificate request state
389 CertificateRequest certRequest = getCertificateRequest(request);
390 if (certRequest.m_requestId == "") {
391 // cannot get the request state
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700392 _LOG_ERROR("Cannot find certificate request state from CA's storage.");
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700393 m_face.put(generateErrorDataPacket(request.getName(), ErrorCode::INVALID_PARAMETER,
394 "Cannot find certificate request state from CA's storage."));
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800395 return;
396 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700397 // verify signature
398 if (!security::verifySignature(request, certRequest.m_cert)) {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700399 _LOG_ERROR("Challenge Interest with bad signature.");
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700400 m_face.put(generateErrorDataPacket(request.getName(), ErrorCode::BAD_SIGNATURE, "Bad signature."));
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800401 return;
402 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700403 // decrypt the parameters
Suyong Won19fba4d2020-05-09 13:39:46 -0700404 Buffer paramTLVPayload;
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700405 try {
Suyong Won19fba4d2020-05-09 13:39:46 -0700406 paramTLVPayload = decodeBlockWithAesGcm128(request.getApplicationParameters(), m_aesKey,
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700407 (uint8_t*)"test", strlen("test"));
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700408 }
409 catch (const std::exception& e) {
410 _LOG_ERROR("Cannot successfully decrypt the Interest parameters: " << e.what());
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700411 m_storage->deleteRequest(certRequest.m_requestId);
412 m_face.put(generateErrorDataPacket(request.getName(), ErrorCode::INVALID_PARAMETER,
413 "Cannot successfully decrypt the Interest parameters."));
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700414 return;
415 }
Suyong Won19fba4d2020-05-09 13:39:46 -0700416 if (paramTLVPayload.size() == 0) {
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700417 _LOG_ERROR("Got an empty buffer from content decryption.");
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700418 m_storage->deleteRequest(certRequest.m_requestId);
419 m_face.put(generateErrorDataPacket(request.getName(), ErrorCode::INVALID_PARAMETER,
420 "Empty buffer from content decryption."));
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700421 return;
422 }
Suyong Won44d0cce2020-05-10 04:07:43 -0700423 Block paramTLV = makeBinaryBlock(tlv_encrypted_payload, paramTLVPayload.data(), paramTLVPayload.size());
424 paramTLV.parse();
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800425
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700426 // load the corresponding challenge module
Suyong Won19fba4d2020-05-09 13:39:46 -0700427 std::string challengeType = readString(paramTLV.get(tlv_selected_challenge));
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800428 auto challenge = ChallengeModule::createChallengeModule(challengeType);
429 if (challenge == nullptr) {
430 _LOG_TRACE("Unrecognized challenge type " << challengeType);
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700431 m_storage->deleteRequest(certRequest.m_requestId);
432 m_face.put(generateErrorDataPacket(request.getName(), ErrorCode::INVALID_PARAMETER, "Unrecognized challenge type"));
433 return;
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800434 }
Suyong Won19fba4d2020-05-09 13:39:46 -0700435
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700436 _LOG_TRACE("CHALLENGE module to be load: " << challengeType);
437 auto errorInfo = challenge->handleChallengeRequest(paramTLV, certRequest);
438 if (std::get<0>(errorInfo) != ErrorCode::NO_ERROR) {
439 m_storage->deleteRequest(certRequest.m_requestId);
440 m_face.put(generateErrorDataPacket(request.getName(), std::get<0>(errorInfo), std::get<1>(errorInfo)));
441 return;
442 }
Suyong Won19fba4d2020-05-09 13:39:46 -0700443
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700444 Block payload;
445 if (certRequest.m_status == Status::PENDING) {
446 // if challenge succeeded
447 if (certRequest.m_requestType == REQUEST_TYPE_NEW) {
448 auto issuedCert = issueCertificate(certRequest);
449 certRequest.m_cert = issuedCert;
450 certRequest.m_status = Status::SUCCESS;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700451 try {
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700452 m_storage->addCertificate(certRequest.m_requestId, issuedCert);
453 m_storage->deleteRequest(certRequest.m_requestId);
454 _LOG_TRACE("New Certificate Issued " << issuedCert.getName());
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700455 }
456 catch (const std::exception& e) {
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700457 _LOG_ERROR("Cannot add issued cert and remove the request: " << e.what());
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700458 return;
459 }
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700460
Suyong Won44d0cce2020-05-10 04:07:43 -0700461 payload = CHALLENGE::encodeDataPayload(certRequest);
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700462 payload.parse();
463 payload.push_back(makeNestedBlock(tlv_issued_cert_name, issuedCert.getName()));
464 payload.encode();
465
466 //contentJson.add(JSON_CA_CERT_ID, readString(issuedCert.getName().at(-1)));
467 _LOG_TRACE("Challenge succeeded. Certificate has been issued");
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800468 }
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700469 else if (certRequest.m_requestType == REQUEST_TYPE_REVOKE) {
470 certRequest.m_status = Status::SUCCESS;
471 try {
472 m_storage->deleteRequest(certRequest.m_requestId);
473 _LOG_TRACE("Certificate Revoked");
474 }
475 catch (const std::exception& e) {
476 _LOG_ERROR("Cannot add issued cert and remove the request: " << e.what());
477 return;
478 }
479
480 payload = CHALLENGE::encodeDataPayload(certRequest);
481 payload.parse();
482 _LOG_TRACE("Challenge succeeded. Certificate has been revoked");
483 }
484 }
485 else {
486 m_storage->updateRequest(certRequest);
487 payload = CHALLENGE::encodeDataPayload(certRequest);
488 _LOG_TRACE("No failure no success. Challenge moves on");
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800489 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700490
491 Data result;
492 result.setName(request.getName());
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700493 result.setFreshnessPeriod(DEFAULT_DATA_FRESHNESS_PERIOD);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700494
495 // encrypt the content
Suyong Won7968f7a2020-05-12 01:01:25 -0700496 auto contentBlock = encodeBlockWithAesGcm128(tlv::Content, m_aesKey, payload.value(),
497 payload.value_size(), (uint8_t*)"test", strlen("test"));
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700498 result.setContent(contentBlock);
Suyong Won256c9062020-05-11 02:45:56 -0700499 m_keyChain.sign(result, signingByIdentity(m_config.m_caPrefix));
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700500 m_face.put(result);
501
502 if (m_config.m_statusUpdateCallback) {
503 m_config.m_statusUpdateCallback(certRequest);
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800504 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700505}
506
Zhiyi Zhang343cdfb2018-01-17 12:04:28 -0800507security::v2::Certificate
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700508CaModule::issueCertificate(const CertificateRequest& certRequest)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800509{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700510 auto expectedPeriod =
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700511 certRequest.m_cert.getValidityPeriod().getPeriod();
Zhiyi Zhang1a735bc2019-07-04 21:36:49 -0700512 security::ValidityPeriod period(expectedPeriod.first, expectedPeriod.second);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800513 security::v2::Certificate newCert;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700514
515 Name certName = certRequest.m_cert.getKeyName();
516 certName.append("NDNCERT").append(std::to_string(random::generateSecureWord64()));
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800517 newCert.setName(certName);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700518 newCert.setContent(certRequest.m_cert.getContent());
519 _LOG_TRACE("cert request content " << certRequest.m_cert);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800520 SignatureInfo signatureInfo;
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800521 signatureInfo.setValidityPeriod(period);
Zhiyi Zhangad6cf932017-10-26 16:19:15 -0700522 security::SigningInfo signingInfo(security::SigningInfo::SIGNER_TYPE_ID,
Suyong Won256c9062020-05-11 02:45:56 -0700523 m_config.m_caPrefix, signatureInfo);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800524
525 m_keyChain.sign(newCert, signingInfo);
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700526 _LOG_TRACE("new cert got signed" << newCert);
Zhiyi Zhang343cdfb2018-01-17 12:04:28 -0800527 return newCert;
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800528}
529
530CertificateRequest
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700531CaModule::getCertificateRequest(const Interest& request)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800532{
Davide Pesaventob48bbda2020-07-27 19:41:37 -0400533 std::string requestId;
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800534 CertificateRequest certRequest;
535 try {
Suyong Won256c9062020-05-11 02:45:56 -0700536 requestId = readString(request.getName().at(m_config.m_caPrefix.size() + 2));
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700537 }
538 catch (const std::exception& e) {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700539 _LOG_ERROR("Cannot read the request ID out from the request: " << e.what());
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700540 }
541 try {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700542 _LOG_TRACE("Request Id to query the database " << requestId);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800543 certRequest = m_storage->getRequest(requestId);
544 }
545 catch (const std::exception& e) {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700546 _LOG_ERROR("Cannot get certificate request record from the storage: " << e.what());
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800547 }
548 return certRequest;
549}
550
551void
552CaModule::onRegisterFailed(const std::string& reason)
553{
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700554 _LOG_ERROR("Failed to register prefix in local hub's daemon, REASON: " << reason);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800555}
556
557Block
558CaModule::dataContentFromJson(const JsonSection& jsonSection)
559{
560 std::stringstream ss;
561 boost::property_tree::write_json(ss, jsonSection);
562 return makeStringBlock(ndn::tlv::Content, ss.str());
563}
564
565JsonSection
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700566CaModule::jsonFromBlock(const Block& block)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800567{
568 std::string jsonString;
569 try {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700570 jsonString = encoding::readString(block);
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700571 std::istringstream ss(jsonString);
572 JsonSection json;
573 boost::property_tree::json_parser::read_json(ss, json);
574 return json;
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800575 }
576 catch (const std::exception& e) {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700577 _LOG_ERROR("Cannot read JSON string from TLV Value: " << e.what());
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800578 return JsonSection();
579 }
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800580}
581
Zhiyi Zhangaafc55e2020-09-28 17:54:48 -0700582Data
583CaModule::generateErrorDataPacket(const Name& name, ErrorCode error, const std::string& errorInfo)
584{
585 Data result;
586 result.setName(name);
587 result.setFreshnessPeriod(DEFAULT_DATA_FRESHNESS_PERIOD);
588 result.setContent(ErrorTLV::encodeDataContent(error, errorInfo));
589 m_keyChain.sign(result, signingByIdentity(m_config.m_caPrefix));
590 return result;
591}
592
593} // namespace ndncert
594} // namespace ndn