blob: 9e9bf61c117f53ef001d1e72a4aa1d4ac342cc28 [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"
22#include "challenge-module.hpp"
23#include "logging.hpp"
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070024#include "crypto-support/enc-tlv.hpp"
Suyong Won19fba4d2020-05-09 13:39:46 -070025#include "protocol-detail/info.hpp"
26#include "protocol-detail/probe.hpp"
27#include "protocol-detail/new.hpp"
28#include "protocol-detail/challenge.hpp"
tylerliu182bc532020-09-25 01:54:45 -070029#include "protocol-detail/revoke.hpp"
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +080030#include <ndn-cxx/util/io.hpp>
Zhiyi Zhangf5246c42017-01-26 09:39:20 -080031#include <ndn-cxx/security/verification-helpers.hpp>
32#include <ndn-cxx/security/signing-helpers.hpp>
Junxiao Shi7c068032017-05-28 13:40:47 +000033#include <ndn-cxx/util/random.hpp>
Zhiyi Zhangfc1678a2020-05-12 16:52:14 -070034#include <ndn-cxx/metadata-object.hpp>
Zhiyi Zhangf5246c42017-01-26 09:39:20 -080035
36namespace ndn {
37namespace ndncert {
38
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070039static const int IS_SUBNAME_MIN_OFFSET = 5;
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -070040static const time::seconds DEFAULT_DATA_FRESHNESS_PERIOD = 1_s;
Zhiyi Zhang1a735bc2019-07-04 21:36:49 -070041static const time::seconds REQUEST_VALIDITY_PERIOD_NOT_BEFORE_GRACE_PERIOD = 120_s;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070042
Zhiyi Zhangf5246c42017-01-26 09:39:20 -080043_LOG_INIT(ndncert.ca);
44
45CaModule::CaModule(Face& face, security::v2::KeyChain& keyChain,
46 const std::string& configPath, const std::string& storageType)
47 : m_face(face)
48 , m_keyChain(keyChain)
49{
Zhiyi Zhanga63b7372017-05-17 14:14:34 -070050 // load the config and create storage
Zhiyi Zhangf5246c42017-01-26 09:39:20 -080051 m_config.load(configPath);
52 m_storage = CaStorage::createCaStorage(storageType);
53
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +080054 registerPrefix();
Zhiyi Zhangf5246c42017-01-26 09:39:20 -080055}
56
57CaModule::~CaModule()
58{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070059 for (auto handle : m_interestFilterHandles) {
60 handle.cancel();
Zhiyi Zhangf5246c42017-01-26 09:39:20 -080061 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070062 for (auto handle : m_registeredPrefixHandles) {
63 handle.unregister();
Zhiyi Zhangf5246c42017-01-26 09:39:20 -080064 }
65}
66
67void
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +080068CaModule::registerPrefix()
69{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070070 // register localhop discovery prefix
swa77020643ac2020-03-26 02:24:45 -070071 Name localhopInfoPrefix("/localhop/CA/INFO");
72 auto prefixId = m_face.setInterestFilter(InterestFilter(localhopInfoPrefix),
73 bind(&CaModule::onInfo, this, _2),
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +080074 bind(&CaModule::onRegisterFailed, this, _2));
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070075 m_registeredPrefixHandles.push_back(prefixId);
swa77020643ac2020-03-26 02:24:45 -070076 _LOG_TRACE("Prefix " << localhopInfoPrefix << " got registered");
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +080077
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070078 // register prefixes
Suyong Won256c9062020-05-11 02:45:56 -070079 Name prefix = m_config.m_caPrefix;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070080 prefix.append("CA");
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +080081
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070082 prefixId = m_face.registerPrefix(prefix,
83 [&] (const Name& name) {
swa77020643ac2020-03-26 02:24:45 -070084 // register INFO prefix
85 auto filterId = m_face.setInterestFilter(Name(name).append("INFO"),
86 bind(&CaModule::onInfo, this, _2));
87 m_interestFilterHandles.push_back(filterId);
88
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070089 // register PROBE prefix
swa77020643ac2020-03-26 02:24:45 -070090 filterId = m_face.setInterestFilter(Name(name).append("PROBE"),
91 bind(&CaModule::onProbe, this, _2));
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070092 m_interestFilterHandles.push_back(filterId);
93
94 // register NEW prefix
swa770de007bc2020-03-24 21:26:21 -070095 filterId = m_face.setInterestFilter(Name(name).append("NEW"),
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070096 bind(&CaModule::onNew, this, _2));
97 m_interestFilterHandles.push_back(filterId);
98
99 // register SELECT prefix
swa770de007bc2020-03-24 21:26:21 -0700100 filterId = m_face.setInterestFilter(Name(name).append("CHALLENGE"),
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700101 bind(&CaModule::onChallenge, this, _2));
102 m_interestFilterHandles.push_back(filterId);
103
tylerliu182bc532020-09-25 01:54:45 -0700104 // register REVOKE prefix
105 filterId = m_face.setInterestFilter(Name(name).append("REVOKE"),
106 bind(&CaModule::onRevoke, this, _2));
107 m_interestFilterHandles.push_back(filterId);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700108 _LOG_TRACE("Prefix " << name << " got registered");
109 },
110 bind(&CaModule::onRegisterFailed, this, _2));
111 m_registeredPrefixHandles.push_back(prefixId);
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800112}
113
Zhiyi Zhang343cdfb2018-01-17 12:04:28 -0800114bool
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700115CaModule::setProbeHandler(const ProbeHandler& handler)
Zhiyi Zhang7420cf52017-12-18 18:59:21 +0800116{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700117 m_config.m_probeHandler = handler;
Zhiyi Zhang343cdfb2018-01-17 12:04:28 -0800118 return false;
Zhiyi Zhang7420cf52017-12-18 18:59:21 +0800119}
120
Zhiyi Zhang343cdfb2018-01-17 12:04:28 -0800121bool
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700122CaModule::setStatusUpdateCallback(const StatusUpdateCallback& onUpdateCallback)
Zhiyi Zhang7420cf52017-12-18 18:59:21 +0800123{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700124 m_config.m_statusUpdateCallback = onUpdateCallback;
Zhiyi Zhang343cdfb2018-01-17 12:04:28 -0800125 return false;
Zhiyi Zhang7420cf52017-12-18 18:59:21 +0800126}
127
Zhiyi Zhangfc1678a2020-05-12 16:52:14 -0700128shared_ptr<Data>
129CaModule::generateCaConfigMetaData()
swa77020643ac2020-03-26 02:24:45 -0700130{
Zhiyi Zhangfc1678a2020-05-12 16:52:14 -0700131 // @TODO
132 // make metadata a class member variable m_infoMetadata
133 // check whether the m_infoMetadata has the latest versioned name, if not, then generate a new one
134 // otherwise, directly reply m_infoMetadata.makeData
135
136 auto infoPacket = generateCaConfigData();
137 MetadataObject metadata;
138 metadata.setVersionedName(infoPacket->getName().getPrefix(-1));
139 Name discoveryInterestName(infoPacket->getName().getPrefix(-2));
140 name::Component metadataComponent(32, reinterpret_cast<const uint8_t*>("metadata"), std::strlen("metadata"));
141 discoveryInterestName.append(metadataComponent);
142 auto metadataData = metadata.makeData(discoveryInterestName, m_keyChain, signingByIdentity(m_config.m_caPrefix));
143 return make_shared<Data>(metadataData);
144}
145
146shared_ptr<Data>
147CaModule::generateCaConfigData()
148{
149 // @TODO
150 // make CaInfo Data packet a class member variable m_infoData
151 // check whether the m_infoData is still valid, if not, then generate a new one
152 // otherwise, directly reply m_infoData
Suyong Won19fba4d2020-05-09 13:39:46 -0700153
154 const auto& pib = m_keyChain.getPib();
Suyong Won256c9062020-05-11 02:45:56 -0700155 const auto& identity = pib.getIdentity(m_config.m_caPrefix);
Suyong Won19fba4d2020-05-09 13:39:46 -0700156 const auto& cert = identity.getDefaultKey().getDefaultCertificate();
157 Block contentTLV = INFO::encodeContentFromCAConfig(m_config, cert);
swa77020643ac2020-03-26 02:24:45 -0700158
Zhiyi Zhangfc1678a2020-05-12 16:52:14 -0700159 Name infoPacketName(m_config.m_caPrefix);
160 infoPacketName.append("CA").append("INFO").appendVersion().appendSegment(0);
161 Data infoData(infoPacketName);
162 infoData.setContent(contentTLV);
163 infoData.setFreshnessPeriod(DEFAULT_DATA_FRESHNESS_PERIOD);
164 m_keyChain.sign(infoData, signingByIdentity(m_config.m_caPrefix));
165 return make_shared<Data>(infoData);
166}
swa77020643ac2020-03-26 02:24:45 -0700167
Zhiyi Zhangfc1678a2020-05-12 16:52:14 -0700168void
169CaModule::onInfo(const Interest& request)
170{
171 _LOG_TRACE("Received INFO request");
172
173 if (request.getName().get(-1).type() == 32) {
174 m_face.put(*generateCaConfigMetaData());
175 }
176 else {
177 m_face.put(*generateCaConfigData());
178 }
swa77020643ac2020-03-26 02:24:45 -0700179
180 _LOG_TRACE("Handle INFO: send out the INFO response");
181}
182
183void
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700184CaModule::onProbe(const Interest& request)
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800185{
swa77020643ac2020-03-26 02:24:45 -0700186 // PROBE Naming Convention: /<CA-Prefix>/CA/PROBE/[ParametersSha256DigestComponent]
187 _LOG_TRACE("Received PROBE request");
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800188
swa77020643ac2020-03-26 02:24:45 -0700189 // process PROBE requests: find an available name
190 std::string availableId;
Suyong Won19fba4d2020-05-09 13:39:46 -0700191 const auto& parameterTLV = request.getApplicationParameters();
Suyong Won44d0cce2020-05-10 04:07:43 -0700192 parameterTLV.parse();
Suyong Won19fba4d2020-05-09 13:39:46 -0700193 if (!parameterTLV.hasValue()) {
194 _LOG_ERROR("Empty TLV obtained from the Interest parameter.");
swa77020643ac2020-03-26 02:24:45 -0700195 return;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700196 }
swa77020643ac2020-03-26 02:24:45 -0700197 //std::string probeInfoStr = parameterJson.get(JSON_CLIENT_PROBE_INFO, "");
198 if (m_config.m_probeHandler) {
199 try {
Suyong Won19fba4d2020-05-09 13:39:46 -0700200 availableId = m_config.m_probeHandler(parameterTLV);
swa77020643ac2020-03-26 02:24:45 -0700201 }
202 catch (const std::exception& e) {
203 _LOG_TRACE("Cannot find PROBE input from PROBE parameters: " << e.what());
Zhiyi Zhang547c8512019-06-18 23:46:14 -0700204 return;
205 }
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800206 }
swa77020643ac2020-03-26 02:24:45 -0700207 else {
208 // if there is no app-specified name lookup, use a random name id
209 availableId = std::to_string(random::generateSecureWord64());
210 }
Suyong Won256c9062020-05-11 02:45:56 -0700211 Name newIdentityName = m_config.m_caPrefix;
swa77020643ac2020-03-26 02:24:45 -0700212 newIdentityName.append(availableId);
213 _LOG_TRACE("Handle PROBE: generate an identity " << newIdentityName);
Suyong Won44d0cce2020-05-10 04:07:43 -0700214
Suyong Won19fba4d2020-05-09 13:39:46 -0700215 Block contentTLV = PROBE::encodeDataContent(newIdentityName.toUri(), m_config.m_probe, parameterTLV);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800216
217 Data result;
218 result.setName(request.getName());
Suyong Won19fba4d2020-05-09 13:39:46 -0700219 result.setContent(contentTLV);
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700220 result.setFreshnessPeriod(DEFAULT_DATA_FRESHNESS_PERIOD);
Suyong Won256c9062020-05-11 02:45:56 -0700221 m_keyChain.sign(result, signingByIdentity(m_config.m_caPrefix));
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800222 m_face.put(result);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700223 _LOG_TRACE("Handle PROBE: send out the PROBE response");
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800224}
225
226void
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700227CaModule::onNew(const Interest& request)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800228{
tylerliu4a00aad2020-09-26 02:03:17 -0700229 // NEW Naming Convention: /<CA-prefix>/CA/NEW/[SignedInterestParameters_Digest]
230 onRequestInit(request, REQUEST_TYPE_NEW);
231}
232
233void
234CaModule::onRevoke(const Interest& request)
235{
236 // REVOKE Naming Convention: /<CA-prefix>/CA/REVOKE/[SignedInterestParameters_Digest]
237 onRequestInit(request, REQUEST_TYPE_REVOKE);
238}
239
240void
241CaModule::onRequestInit(const Interest& request, int requestType)
242{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700243 // get ECDH pub key and cert request
Suyong Won19fba4d2020-05-09 13:39:46 -0700244 const auto& parameterTLV = request.getApplicationParameters();
Suyong Won7968f7a2020-05-12 01:01:25 -0700245 parameterTLV.parse();
246
Suyong Won19fba4d2020-05-09 13:39:46 -0700247 if (!parameterTLV.hasValue()) {
248 _LOG_ERROR("Empty TLV obtained from the Interest parameter.");
Zhiyi Zhang547c8512019-06-18 23:46:14 -0700249 return;
250 }
Suyong Won19fba4d2020-05-09 13:39:46 -0700251
252 std::string peerKeyBase64 = readString(parameterTLV.get(tlv_ecdh_pub));
253
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700254 if (peerKeyBase64 == "") {
Suyong Won19fba4d2020-05-09 13:39:46 -0700255 _LOG_ERROR("Empty ECDH PUB obtained from the Interest parameter.");
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700256 return;
257 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700258
259 // get server's ECDH pub key
260 auto myEcdhPubKeyBase64 = m_ecdh.getBase64PubKey();
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700261 try {
262 m_ecdh.deriveSecret(peerKeyBase64);
263 }
264 catch (const std::exception& e) {
265 _LOG_ERROR("Cannot derive a shared secret using the provided ECDH key: " << e.what());
266 return;
267 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700268 // generate salt for HKDF
269 auto saltInt = random::generateSecureWord64();
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700270 // hkdf
271 hkdf(m_ecdh.context->sharedSecret, m_ecdh.context->sharedSecretLen,
Zhiyi Zhang36706832019-07-04 21:33:03 -0700272 (uint8_t*)&saltInt, sizeof(saltInt), m_aesKey, sizeof(m_aesKey));
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700273
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700274 shared_ptr<security::v2::Certificate> clientCert = nullptr;
Suyong Won7968f7a2020-05-12 01:01:25 -0700275
tylerliu4a00aad2020-09-26 02:03:17 -0700276 if (requestType == REQUEST_TYPE_NEW) {
277 // parse certificate request
278 Block cert_req = parameterTLV.get(tlv_cert_request);
279 cert_req.parse();
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700280
tylerliu4a00aad2020-09-26 02:03:17 -0700281 try {
282 security::v2::Certificate cert = security::v2::Certificate(cert_req.get(tlv::Data));
283 clientCert = make_shared<security::v2::Certificate>(cert);
284 }
285 catch (const std::exception &e) {
286 _LOG_ERROR("Unrecognized certificate request: " << e.what());
287 return;
288 }
289 // check the validity period
290 auto expectedPeriod = clientCert->getValidityPeriod().getPeriod();
291 auto currentTime = time::system_clock::now();
292 if (expectedPeriod.first < currentTime - REQUEST_VALIDITY_PERIOD_NOT_BEFORE_GRACE_PERIOD) {
293 _LOG_ERROR("Client requests a too old notBefore timepoint.");
294 return;
295 }
296 if (expectedPeriod.second > currentTime + m_config.m_maxValidityPeriod ||
297 expectedPeriod.second <= expectedPeriod.first) {
298 _LOG_ERROR("Client requests an invalid validity period or a notAfter timepoint beyond the allowed time period.");
299 return;
300 }
301
302 // verify the self-signed certificate, the request, and the token
303 if (!m_config.m_caPrefix.isPrefixOf(clientCert->getName()) // under ca prefix
304 || !security::v2::Certificate::isValidName(clientCert->getName()) // is valid cert name
305 || clientCert->getName().size() < m_config.m_caName.size() + IS_SUBNAME_MIN_OFFSET) {
306 _LOG_ERROR("Invalid self-signed certificate name " << clientCert->getName());
307 return;
308 }
309 if (!security::verifySignature(*clientCert, *clientCert)) {
310 _LOG_ERROR("Cert request with bad signature.");
311 return;
312 }
313 if (!security::verifySignature(request, *clientCert)) {
314 _LOG_ERROR("Interest with bad signature.");
315 return;
316 }
317 } else if (requestType == REQUEST_TYPE_REVOKE) {
318 // parse certificate request
319 Block cert_revoke = parameterTLV.get(tlv_cert_to_revoke);
320 cert_revoke.parse();
321
322 try {
323 security::v2::Certificate cert = security::v2::Certificate(cert_revoke.get(tlv::Data));
324 clientCert = make_shared<security::v2::Certificate>(cert);
325 }
326 catch (const std::exception &e) {
327 _LOG_ERROR("Unrecognized certificate: " << e.what());
328 return;
329 }
330
331 // verify the certificate
332 if (!m_config.m_caName.isPrefixOf(clientCert->getName()) // under ca prefix
333 || !security::v2::Certificate::isValidName(clientCert->getName()) // is valid cert name
334 || clientCert->getName().size() < m_config.m_caName.size() + IS_SUBNAME_MIN_OFFSET) {
335 _LOG_ERROR("Invalid certificate name " << clientCert->getName());
336 return;
337 }
338 const auto& cert = m_keyChain.getPib().getIdentity(m_config.m_caName).getDefaultKey().getDefaultCertificate();
339 if (!security::verifySignature(*clientCert, cert)) {
340 _LOG_ERROR("Cert request with bad signature.");
341 return;
342 }
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700343 }
344
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700345 // create new request instance
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800346 std::string requestId = std::to_string(random::generateWord64());
tylerliu4a00aad2020-09-26 02:03:17 -0700347 CertificateRequest certRequest(m_config.m_caPrefix, requestId, requestType, STATUS_BEFORE_CHALLENGE, *clientCert);
Suyong Won19fba4d2020-05-09 13:39:46 -0700348
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800349 try {
350 m_storage->addRequest(certRequest);
351 }
352 catch (const std::exception& e) {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700353 _LOG_ERROR("Cannot add new request instance into the storage: " << e.what());
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800354 return;
355 }
356
357 Data result;
358 result.setName(request.getName());
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700359 result.setFreshnessPeriod(DEFAULT_DATA_FRESHNESS_PERIOD);
tylerliu4a00aad2020-09-26 02:03:17 -0700360 if (requestType == REQUEST_TYPE_NEW) {
361 result.setContent(NEW::encodeDataContent(myEcdhPubKeyBase64,
362 std::to_string(saltInt),
363 certRequest,
364 m_config.m_supportedChallenges));
365 } else if (requestType == REQUEST_TYPE_REVOKE) {
366 result.setContent(REVOKE::encodeDataContent(myEcdhPubKeyBase64,
367 std::to_string(saltInt),
368 certRequest,
369 m_config.m_supportedChallenges));
370 }
Suyong Won256c9062020-05-11 02:45:56 -0700371 m_keyChain.sign(result, signingByIdentity(m_config.m_caPrefix));
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800372 m_face.put(result);
Zhiyi Zhanga63b7372017-05-17 14:14:34 -0700373
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700374 if (m_config.m_statusUpdateCallback) {
375 m_config.m_statusUpdateCallback(certRequest);
Zhiyi Zhang7420cf52017-12-18 18:59:21 +0800376 }
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800377}
378
379void
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700380CaModule::onChallenge(const Interest& request)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800381{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700382 // get certificate request state
383 CertificateRequest certRequest = getCertificateRequest(request);
384 if (certRequest.m_requestId == "") {
385 // cannot get the request state
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700386 _LOG_ERROR("Cannot find certificate request state from CA's storage.");
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800387 return;
388 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700389 // verify signature
390 if (!security::verifySignature(request, certRequest.m_cert)) {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700391 _LOG_ERROR("Challenge Interest with bad signature.");
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800392 return;
393 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700394 // decrypt the parameters
Suyong Won19fba4d2020-05-09 13:39:46 -0700395 Buffer paramTLVPayload;
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700396 try {
Suyong Won19fba4d2020-05-09 13:39:46 -0700397 paramTLVPayload = decodeBlockWithAesGcm128(request.getApplicationParameters(), m_aesKey,
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -0700398 (uint8_t*)"test", strlen("test"));
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700399 }
400 catch (const std::exception& e) {
401 _LOG_ERROR("Cannot successfully decrypt the Interest parameters: " << e.what());
402 return;
403 }
Suyong Won19fba4d2020-05-09 13:39:46 -0700404 if (paramTLVPayload.size() == 0) {
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700405 _LOG_ERROR("Got an empty buffer from content decryption.");
406 return;
407 }
Suyong Won19fba4d2020-05-09 13:39:46 -0700408
Suyong Won44d0cce2020-05-10 04:07:43 -0700409 Block paramTLV = makeBinaryBlock(tlv_encrypted_payload, paramTLVPayload.data(), paramTLVPayload.size());
410 paramTLV.parse();
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800411
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700412 // load the corresponding challenge module
Suyong Won19fba4d2020-05-09 13:39:46 -0700413 std::string challengeType = readString(paramTLV.get(tlv_selected_challenge));
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800414 auto challenge = ChallengeModule::createChallengeModule(challengeType);
Suyong Won19fba4d2020-05-09 13:39:46 -0700415
Suyong Won44d0cce2020-05-10 04:07:43 -0700416 Block payload;
Suyong Won19fba4d2020-05-09 13:39:46 -0700417
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800418 if (challenge == nullptr) {
419 _LOG_TRACE("Unrecognized challenge type " << challengeType);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700420 certRequest.m_status = STATUS_FAILURE;
421 certRequest.m_challengeStatus = CHALLENGE_STATUS_UNKNOWN_CHALLENGE;
Suyong Won44d0cce2020-05-10 04:07:43 -0700422 payload = CHALLENGE::encodeDataPayload(certRequest);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800423 }
Zhiyi Zhanga9bda732017-05-20 22:58:55 -0700424 else {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700425 _LOG_TRACE("CHALLENGE module to be load: " << challengeType);
426 // let challenge module handle the request
Suyong Won19fba4d2020-05-09 13:39:46 -0700427 challenge->handleChallengeRequest(paramTLV, certRequest);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700428 if (certRequest.m_status == STATUS_FAILURE) {
429 // if challenge failed
430 m_storage->deleteRequest(certRequest.m_requestId);
Suyong Won44d0cce2020-05-10 04:07:43 -0700431 payload = CHALLENGE::encodeDataPayload(certRequest);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700432 _LOG_TRACE("Challenge failed");
Zhiyi Zhanga9bda732017-05-20 22:58:55 -0700433 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700434 else if (certRequest.m_status == STATUS_PENDING) {
435 // if challenge succeeded
tylerliu182bc532020-09-25 01:54:45 -0700436 if (certRequest.m_requestType == REQUEST_TYPE_NEW) {
437 auto issuedCert = issueCertificate(certRequest);
438 certRequest.m_cert = issuedCert;
439 certRequest.m_status = STATUS_SUCCESS;
440 try {
441 m_storage->addCertificate(certRequest.m_requestId, issuedCert);
442 m_storage->deleteRequest(certRequest.m_requestId);
443 _LOG_TRACE("New Certificate Issued " << issuedCert.getName());
444 }
445 catch (const std::exception& e) {
446 _LOG_ERROR("Cannot add issued cert and remove the request: " << e.what());
447 return;
448 }
Suyong Won19fba4d2020-05-09 13:39:46 -0700449
tylerliu182bc532020-09-25 01:54:45 -0700450 payload = CHALLENGE::encodeDataPayload(certRequest);
451 payload.parse();
452 payload.push_back(makeNestedBlock(tlv_issued_cert_name, issuedCert.getName()));
453 payload.encode();
Suyong Won19fba4d2020-05-09 13:39:46 -0700454
tylerliu182bc532020-09-25 01:54:45 -0700455 //contentJson.add(JSON_CA_CERT_ID, readString(issuedCert.getName().at(-1)));
456 _LOG_TRACE("Challenge succeeded. Certificate has been issued");
457 }
458 else if (certRequest.m_requestType == REQUEST_TYPE_REVOKE) {
459 certRequest.m_status = STATUS_SUCCESS;
460 try {
461 m_storage->deleteRequest(certRequest.m_requestId);
462 _LOG_TRACE("Certificate Revoked");
463 }
464 catch (const std::exception& e) {
465 _LOG_ERROR("Cannot add issued cert and remove the request: " << e.what());
466 return;
467 }
468
469 payload = CHALLENGE::encodeDataPayload(certRequest);
470 payload.parse();
471 _LOG_TRACE("Challenge succeeded. Certificate has been revoked");
472 }
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800473 }
474 else {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700475 try {
476 m_storage->updateRequest(certRequest);
477 }
478 catch (const std::exception& e) {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700479 _LOG_TRACE("Cannot update request instance: " << e.what());
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700480 return;
481 }
Suyong Won44d0cce2020-05-10 04:07:43 -0700482 payload = CHALLENGE::encodeDataPayload(certRequest);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700483 _LOG_TRACE("No failure no success. Challenge moves on");
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800484 }
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800485 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700486
487 Data result;
488 result.setName(request.getName());
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700489 result.setFreshnessPeriod(DEFAULT_DATA_FRESHNESS_PERIOD);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700490
491 // encrypt the content
Suyong Won7968f7a2020-05-12 01:01:25 -0700492 auto contentBlock = encodeBlockWithAesGcm128(tlv::Content, m_aesKey, payload.value(),
493 payload.value_size(), (uint8_t*)"test", strlen("test"));
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700494 result.setContent(contentBlock);
Suyong Won256c9062020-05-11 02:45:56 -0700495 m_keyChain.sign(result, signingByIdentity(m_config.m_caPrefix));
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700496 m_face.put(result);
497
498 if (m_config.m_statusUpdateCallback) {
499 m_config.m_statusUpdateCallback(certRequest);
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800500 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700501}
502
Zhiyi Zhang343cdfb2018-01-17 12:04:28 -0800503security::v2::Certificate
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700504CaModule::issueCertificate(const CertificateRequest& certRequest)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800505{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700506 auto expectedPeriod =
507 certRequest.m_cert.getValidityPeriod().getPeriod();
Zhiyi Zhang1a735bc2019-07-04 21:36:49 -0700508 security::ValidityPeriod period(expectedPeriod.first, expectedPeriod.second);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800509 security::v2::Certificate newCert;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700510
511 Name certName = certRequest.m_cert.getKeyName();
512 certName.append("NDNCERT").append(std::to_string(random::generateSecureWord64()));
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800513 newCert.setName(certName);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700514 newCert.setContent(certRequest.m_cert.getContent());
515 _LOG_TRACE("cert request content " << certRequest.m_cert);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800516 SignatureInfo signatureInfo;
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800517 signatureInfo.setValidityPeriod(period);
Zhiyi Zhangad6cf932017-10-26 16:19:15 -0700518 security::SigningInfo signingInfo(security::SigningInfo::SIGNER_TYPE_ID,
Suyong Won256c9062020-05-11 02:45:56 -0700519 m_config.m_caPrefix, signatureInfo);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800520
521 m_keyChain.sign(newCert, signingInfo);
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700522 _LOG_TRACE("new cert got signed" << newCert);
Zhiyi Zhang343cdfb2018-01-17 12:04:28 -0800523 return newCert;
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800524}
525
526CertificateRequest
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700527CaModule::getCertificateRequest(const Interest& request)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800528{
Davide Pesaventob48bbda2020-07-27 19:41:37 -0400529 std::string requestId;
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800530 CertificateRequest certRequest;
531 try {
Suyong Won256c9062020-05-11 02:45:56 -0700532 requestId = readString(request.getName().at(m_config.m_caPrefix.size() + 2));
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700533 }
534 catch (const std::exception& e) {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700535 _LOG_ERROR("Cannot read the request ID out from the request: " << e.what());
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700536 }
537 try {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700538 _LOG_TRACE("Request Id to query the database " << requestId);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800539 certRequest = m_storage->getRequest(requestId);
540 }
541 catch (const std::exception& e) {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700542 _LOG_ERROR("Cannot get certificate request record from the storage: " << e.what());
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800543 }
544 return certRequest;
545}
546
547void
548CaModule::onRegisterFailed(const std::string& reason)
549{
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700550 _LOG_ERROR("Failed to register prefix in local hub's daemon, REASON: " << reason);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800551}
552
553Block
554CaModule::dataContentFromJson(const JsonSection& jsonSection)
555{
556 std::stringstream ss;
557 boost::property_tree::write_json(ss, jsonSection);
558 return makeStringBlock(ndn::tlv::Content, ss.str());
559}
560
561JsonSection
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700562CaModule::jsonFromBlock(const Block& block)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800563{
564 std::string jsonString;
565 try {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700566 jsonString = encoding::readString(block);
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700567 std::istringstream ss(jsonString);
568 JsonSection json;
569 boost::property_tree::json_parser::read_json(ss, json);
570 return json;
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800571 }
572 catch (const std::exception& e) {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700573 _LOG_ERROR("Cannot read JSON string from TLV Value: " << e.what());
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800574 return JsonSection();
575 }
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800576}
577
578} // namespace ndncert
579} // namespace ndn