blob: 47ab755a497552a26c9986f90319fc01dd943b84 [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 Zhangf6c5d272020-09-28 10:17:32 -0700114void
115CaModule::setNameAssignmentFunction(const NameAssignmentFunc& handler)
Zhiyi Zhang7420cf52017-12-18 18:59:21 +0800116{
Zhiyi Zhangf6c5d272020-09-28 10:17:32 -0700117 m_config.m_nameAssignmentFunc = handler;
Zhiyi Zhang7420cf52017-12-18 18:59:21 +0800118}
119
Zhiyi Zhang343cdfb2018-01-17 12:04:28 -0800120bool
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700121CaModule::setStatusUpdateCallback(const StatusUpdateCallback& onUpdateCallback)
Zhiyi Zhang7420cf52017-12-18 18:59:21 +0800122{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700123 m_config.m_statusUpdateCallback = onUpdateCallback;
Zhiyi Zhang343cdfb2018-01-17 12:04:28 -0800124 return false;
Zhiyi Zhang7420cf52017-12-18 18:59:21 +0800125}
126
Zhiyi Zhangfc1678a2020-05-12 16:52:14 -0700127shared_ptr<Data>
128CaModule::generateCaConfigMetaData()
swa77020643ac2020-03-26 02:24:45 -0700129{
Zhiyi Zhangfc1678a2020-05-12 16:52:14 -0700130 // @TODO
131 // make metadata a class member variable m_infoMetadata
132 // check whether the m_infoMetadata has the latest versioned name, if not, then generate a new one
133 // otherwise, directly reply m_infoMetadata.makeData
134
135 auto infoPacket = generateCaConfigData();
136 MetadataObject metadata;
137 metadata.setVersionedName(infoPacket->getName().getPrefix(-1));
138 Name discoveryInterestName(infoPacket->getName().getPrefix(-2));
139 name::Component metadataComponent(32, reinterpret_cast<const uint8_t*>("metadata"), std::strlen("metadata"));
140 discoveryInterestName.append(metadataComponent);
141 auto metadataData = metadata.makeData(discoveryInterestName, m_keyChain, signingByIdentity(m_config.m_caPrefix));
142 return make_shared<Data>(metadataData);
143}
144
145shared_ptr<Data>
146CaModule::generateCaConfigData()
147{
148 // @TODO
149 // make CaInfo Data packet a class member variable m_infoData
150 // check whether the m_infoData is still valid, if not, then generate a new one
151 // otherwise, directly reply m_infoData
Suyong Won19fba4d2020-05-09 13:39:46 -0700152
153 const auto& pib = m_keyChain.getPib();
Suyong Won256c9062020-05-11 02:45:56 -0700154 const auto& identity = pib.getIdentity(m_config.m_caPrefix);
Suyong Won19fba4d2020-05-09 13:39:46 -0700155 const auto& cert = identity.getDefaultKey().getDefaultCertificate();
156 Block contentTLV = INFO::encodeContentFromCAConfig(m_config, cert);
swa77020643ac2020-03-26 02:24:45 -0700157
Zhiyi Zhangfc1678a2020-05-12 16:52:14 -0700158 Name infoPacketName(m_config.m_caPrefix);
159 infoPacketName.append("CA").append("INFO").appendVersion().appendSegment(0);
160 Data infoData(infoPacketName);
161 infoData.setContent(contentTLV);
162 infoData.setFreshnessPeriod(DEFAULT_DATA_FRESHNESS_PERIOD);
163 m_keyChain.sign(infoData, signingByIdentity(m_config.m_caPrefix));
164 return make_shared<Data>(infoData);
165}
swa77020643ac2020-03-26 02:24:45 -0700166
Zhiyi Zhangfc1678a2020-05-12 16:52:14 -0700167void
168CaModule::onInfo(const Interest& request)
169{
170 _LOG_TRACE("Received INFO request");
171
172 if (request.getName().get(-1).type() == 32) {
173 m_face.put(*generateCaConfigMetaData());
174 }
175 else {
176 m_face.put(*generateCaConfigData());
177 }
swa77020643ac2020-03-26 02:24:45 -0700178
179 _LOG_TRACE("Handle INFO: send out the INFO response");
180}
181
182void
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700183CaModule::onProbe(const Interest& request)
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800184{
swa77020643ac2020-03-26 02:24:45 -0700185 // PROBE Naming Convention: /<CA-Prefix>/CA/PROBE/[ParametersSha256DigestComponent]
186 _LOG_TRACE("Received PROBE request");
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800187
swa77020643ac2020-03-26 02:24:45 -0700188 // process PROBE requests: find an available name
Zhiyi Zhangf6c5d272020-09-28 10:17:32 -0700189 std::string availableId = "";
Suyong Won19fba4d2020-05-09 13:39:46 -0700190 const auto& parameterTLV = request.getApplicationParameters();
Suyong Won44d0cce2020-05-10 04:07:43 -0700191 parameterTLV.parse();
Suyong Won19fba4d2020-05-09 13:39:46 -0700192 if (!parameterTLV.hasValue()) {
193 _LOG_ERROR("Empty TLV obtained from the Interest parameter.");
swa77020643ac2020-03-26 02:24:45 -0700194 return;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700195 }
Suyong Won44d0cce2020-05-10 04:07:43 -0700196
Zhiyi Zhangf6c5d272020-09-28 10:17:32 -0700197 // if (m_config.m_nameAssignmentFunc) {
198 // try {
199 // availableId = m_config.m_nameAssignmentFunc(parameterTLV);
200 // }
201 // catch (const std::exception& e) {
202 // _LOG_TRACE("Cannot find PROBE input from PROBE parameters: " << e.what());
203 // return;
204 // }
205 // }
206 // else {
207 // // if there is no app-specified name lookup, use a random name id
208 // availableId = std::to_string(random::generateSecureWord64());
209 // }
210 // Name newIdentityName = m_config.m_caPrefix;
211 // newIdentityName.append(availableId);
212 // _LOG_TRACE("Handle PROBE: generate an identity " << newIdentityName);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800213
Zhiyi Zhangf6c5d272020-09-28 10:17:32 -0700214 // Block contentTLV = PROBE::encodeDataContent(newIdentityName.toUri(), m_config.m_probe, parameterTLV);
215
216 // Data result;
217 // result.setName(request.getName());
218 // result.setContent(contentTLV);
219 // result.setFreshnessPeriod(DEFAULT_DATA_FRESHNESS_PERIOD);
220 // m_keyChain.sign(result, signingByIdentity(m_config.m_caPrefix));
221 // m_face.put(result);
222 // _LOG_TRACE("Handle PROBE: send out the PROBE response");
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800223}
224
225void
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700226CaModule::onNew(const Interest& request)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800227{
tylerliu4a00aad2020-09-26 02:03:17 -0700228 // NEW Naming Convention: /<CA-prefix>/CA/NEW/[SignedInterestParameters_Digest]
229 onRequestInit(request, REQUEST_TYPE_NEW);
230}
231
232void
233CaModule::onRevoke(const Interest& request)
234{
235 // REVOKE Naming Convention: /<CA-prefix>/CA/REVOKE/[SignedInterestParameters_Digest]
236 onRequestInit(request, REQUEST_TYPE_REVOKE);
237}
238
239void
240CaModule::onRequestInit(const Interest& request, int requestType)
241{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700242 // get ECDH pub key and cert request
Suyong Won19fba4d2020-05-09 13:39:46 -0700243 const auto& parameterTLV = request.getApplicationParameters();
Suyong Won7968f7a2020-05-12 01:01:25 -0700244 parameterTLV.parse();
245
Suyong Won19fba4d2020-05-09 13:39:46 -0700246 if (!parameterTLV.hasValue()) {
247 _LOG_ERROR("Empty TLV obtained from the Interest parameter.");
Zhiyi Zhang547c8512019-06-18 23:46:14 -0700248 return;
249 }
Suyong Won19fba4d2020-05-09 13:39:46 -0700250
251 std::string peerKeyBase64 = readString(parameterTLV.get(tlv_ecdh_pub));
252
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700253 if (peerKeyBase64 == "") {
Suyong Won19fba4d2020-05-09 13:39:46 -0700254 _LOG_ERROR("Empty ECDH PUB obtained from the Interest parameter.");
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700255 return;
256 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700257
258 // get server's ECDH pub key
259 auto myEcdhPubKeyBase64 = m_ecdh.getBase64PubKey();
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700260 try {
261 m_ecdh.deriveSecret(peerKeyBase64);
262 }
263 catch (const std::exception& e) {
264 _LOG_ERROR("Cannot derive a shared secret using the provided ECDH key: " << e.what());
265 return;
266 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700267 // generate salt for HKDF
268 auto saltInt = random::generateSecureWord64();
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700269 // hkdf
270 hkdf(m_ecdh.context->sharedSecret, m_ecdh.context->sharedSecretLen,
Zhiyi Zhang36706832019-07-04 21:33:03 -0700271 (uint8_t*)&saltInt, sizeof(saltInt), m_aesKey, sizeof(m_aesKey));
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700272
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700273 shared_ptr<security::v2::Certificate> clientCert = nullptr;
Suyong Won7968f7a2020-05-12 01:01:25 -0700274
tylerliu4a00aad2020-09-26 02:03:17 -0700275 if (requestType == REQUEST_TYPE_NEW) {
276 // parse certificate request
277 Block cert_req = parameterTLV.get(tlv_cert_request);
278 cert_req.parse();
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700279
tylerliu4a00aad2020-09-26 02:03:17 -0700280 try {
281 security::v2::Certificate cert = security::v2::Certificate(cert_req.get(tlv::Data));
282 clientCert = make_shared<security::v2::Certificate>(cert);
283 }
284 catch (const std::exception &e) {
285 _LOG_ERROR("Unrecognized certificate request: " << e.what());
286 return;
287 }
288 // check the validity period
289 auto expectedPeriod = clientCert->getValidityPeriod().getPeriod();
290 auto currentTime = time::system_clock::now();
291 if (expectedPeriod.first < currentTime - REQUEST_VALIDITY_PERIOD_NOT_BEFORE_GRACE_PERIOD) {
292 _LOG_ERROR("Client requests a too old notBefore timepoint.");
293 return;
294 }
295 if (expectedPeriod.second > currentTime + m_config.m_maxValidityPeriod ||
296 expectedPeriod.second <= expectedPeriod.first) {
297 _LOG_ERROR("Client requests an invalid validity period or a notAfter timepoint beyond the allowed time period.");
298 return;
299 }
300
301 // verify the self-signed certificate, the request, and the token
302 if (!m_config.m_caPrefix.isPrefixOf(clientCert->getName()) // under ca prefix
303 || !security::v2::Certificate::isValidName(clientCert->getName()) // is valid cert name
Zhiyi Zhangf6c5d272020-09-28 10:17:32 -0700304 || clientCert->getName().size() < m_config.m_caPrefix.size() + IS_SUBNAME_MIN_OFFSET) {
tylerliu4a00aad2020-09-26 02:03:17 -0700305 _LOG_ERROR("Invalid self-signed certificate name " << clientCert->getName());
306 return;
307 }
308 if (!security::verifySignature(*clientCert, *clientCert)) {
309 _LOG_ERROR("Cert request with bad signature.");
310 return;
311 }
312 if (!security::verifySignature(request, *clientCert)) {
313 _LOG_ERROR("Interest with bad signature.");
314 return;
315 }
316 } else if (requestType == REQUEST_TYPE_REVOKE) {
317 // parse certificate request
318 Block cert_revoke = parameterTLV.get(tlv_cert_to_revoke);
319 cert_revoke.parse();
320
321 try {
322 security::v2::Certificate cert = security::v2::Certificate(cert_revoke.get(tlv::Data));
323 clientCert = make_shared<security::v2::Certificate>(cert);
324 }
325 catch (const std::exception &e) {
326 _LOG_ERROR("Unrecognized certificate: " << e.what());
327 return;
328 }
329
330 // verify the certificate
Zhiyi Zhangf6c5d272020-09-28 10:17:32 -0700331 if (!m_config.m_caPrefix.isPrefixOf(clientCert->getName()) // under ca prefix
tylerliu4a00aad2020-09-26 02:03:17 -0700332 || !security::v2::Certificate::isValidName(clientCert->getName()) // is valid cert name
Zhiyi Zhangf6c5d272020-09-28 10:17:32 -0700333 || clientCert->getName().size() < m_config.m_caPrefix.size() + IS_SUBNAME_MIN_OFFSET) {
tylerliu4a00aad2020-09-26 02:03:17 -0700334 _LOG_ERROR("Invalid certificate name " << clientCert->getName());
335 return;
336 }
Zhiyi Zhangf6c5d272020-09-28 10:17:32 -0700337 const auto& cert = m_keyChain.getPib().getIdentity(m_config.m_caPrefix).getDefaultKey().getDefaultCertificate();
tylerliu4a00aad2020-09-26 02:03:17 -0700338 if (!security::verifySignature(*clientCert, cert)) {
339 _LOG_ERROR("Cert request with bad signature.");
340 return;
341 }
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700342 }
343
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700344 // create new request instance
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800345 std::string requestId = std::to_string(random::generateWord64());
tylerliu4a00aad2020-09-26 02:03:17 -0700346 CertificateRequest certRequest(m_config.m_caPrefix, requestId, requestType, STATUS_BEFORE_CHALLENGE, *clientCert);
Suyong Won19fba4d2020-05-09 13:39:46 -0700347
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800348 try {
349 m_storage->addRequest(certRequest);
350 }
351 catch (const std::exception& e) {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700352 _LOG_ERROR("Cannot add new request instance into the storage: " << e.what());
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800353 return;
354 }
355
356 Data result;
357 result.setName(request.getName());
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700358 result.setFreshnessPeriod(DEFAULT_DATA_FRESHNESS_PERIOD);
tylerliu4a00aad2020-09-26 02:03:17 -0700359 if (requestType == REQUEST_TYPE_NEW) {
360 result.setContent(NEW::encodeDataContent(myEcdhPubKeyBase64,
361 std::to_string(saltInt),
362 certRequest,
363 m_config.m_supportedChallenges));
364 } else if (requestType == REQUEST_TYPE_REVOKE) {
365 result.setContent(REVOKE::encodeDataContent(myEcdhPubKeyBase64,
366 std::to_string(saltInt),
367 certRequest,
368 m_config.m_supportedChallenges));
369 }
Suyong Won256c9062020-05-11 02:45:56 -0700370 m_keyChain.sign(result, signingByIdentity(m_config.m_caPrefix));
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800371 m_face.put(result);
Zhiyi Zhanga63b7372017-05-17 14:14:34 -0700372
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700373 if (m_config.m_statusUpdateCallback) {
374 m_config.m_statusUpdateCallback(certRequest);
Zhiyi Zhang7420cf52017-12-18 18:59:21 +0800375 }
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800376}
377
378void
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700379CaModule::onChallenge(const Interest& request)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800380{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700381 // get certificate request state
382 CertificateRequest certRequest = getCertificateRequest(request);
383 if (certRequest.m_requestId == "") {
384 // cannot get the request state
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700385 _LOG_ERROR("Cannot find certificate request state from CA's storage.");
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800386 return;
387 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700388 // verify signature
389 if (!security::verifySignature(request, certRequest.m_cert)) {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700390 _LOG_ERROR("Challenge Interest with bad signature.");
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800391 return;
392 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700393 // decrypt the parameters
Suyong Won19fba4d2020-05-09 13:39:46 -0700394 Buffer paramTLVPayload;
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700395 try {
Suyong Won19fba4d2020-05-09 13:39:46 -0700396 paramTLVPayload = decodeBlockWithAesGcm128(request.getApplicationParameters(), m_aesKey,
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -0700397 (uint8_t*)"test", strlen("test"));
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700398 }
399 catch (const std::exception& e) {
400 _LOG_ERROR("Cannot successfully decrypt the Interest parameters: " << e.what());
401 return;
402 }
Suyong Won19fba4d2020-05-09 13:39:46 -0700403 if (paramTLVPayload.size() == 0) {
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700404 _LOG_ERROR("Got an empty buffer from content decryption.");
405 return;
406 }
Suyong Won19fba4d2020-05-09 13:39:46 -0700407
Suyong Won44d0cce2020-05-10 04:07:43 -0700408 Block paramTLV = makeBinaryBlock(tlv_encrypted_payload, paramTLVPayload.data(), paramTLVPayload.size());
409 paramTLV.parse();
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800410
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700411 // load the corresponding challenge module
Suyong Won19fba4d2020-05-09 13:39:46 -0700412 std::string challengeType = readString(paramTLV.get(tlv_selected_challenge));
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800413 auto challenge = ChallengeModule::createChallengeModule(challengeType);
Suyong Won19fba4d2020-05-09 13:39:46 -0700414
Suyong Won44d0cce2020-05-10 04:07:43 -0700415 Block payload;
Suyong Won19fba4d2020-05-09 13:39:46 -0700416
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800417 if (challenge == nullptr) {
418 _LOG_TRACE("Unrecognized challenge type " << challengeType);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700419 certRequest.m_status = STATUS_FAILURE;
420 certRequest.m_challengeStatus = CHALLENGE_STATUS_UNKNOWN_CHALLENGE;
Suyong Won44d0cce2020-05-10 04:07:43 -0700421 payload = CHALLENGE::encodeDataPayload(certRequest);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800422 }
Zhiyi Zhanga9bda732017-05-20 22:58:55 -0700423 else {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700424 _LOG_TRACE("CHALLENGE module to be load: " << challengeType);
425 // let challenge module handle the request
Suyong Won19fba4d2020-05-09 13:39:46 -0700426 challenge->handleChallengeRequest(paramTLV, certRequest);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700427 if (certRequest.m_status == STATUS_FAILURE) {
428 // if challenge failed
429 m_storage->deleteRequest(certRequest.m_requestId);
Suyong Won44d0cce2020-05-10 04:07:43 -0700430 payload = CHALLENGE::encodeDataPayload(certRequest);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700431 _LOG_TRACE("Challenge failed");
Zhiyi Zhanga9bda732017-05-20 22:58:55 -0700432 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700433 else if (certRequest.m_status == STATUS_PENDING) {
434 // if challenge succeeded
tylerliu182bc532020-09-25 01:54:45 -0700435 if (certRequest.m_requestType == REQUEST_TYPE_NEW) {
436 auto issuedCert = issueCertificate(certRequest);
437 certRequest.m_cert = issuedCert;
438 certRequest.m_status = STATUS_SUCCESS;
439 try {
440 m_storage->addCertificate(certRequest.m_requestId, issuedCert);
441 m_storage->deleteRequest(certRequest.m_requestId);
442 _LOG_TRACE("New Certificate Issued " << issuedCert.getName());
443 }
444 catch (const std::exception& e) {
445 _LOG_ERROR("Cannot add issued cert and remove the request: " << e.what());
446 return;
447 }
Suyong Won19fba4d2020-05-09 13:39:46 -0700448
tylerliu182bc532020-09-25 01:54:45 -0700449 payload = CHALLENGE::encodeDataPayload(certRequest);
450 payload.parse();
451 payload.push_back(makeNestedBlock(tlv_issued_cert_name, issuedCert.getName()));
452 payload.encode();
Suyong Won19fba4d2020-05-09 13:39:46 -0700453
tylerliu182bc532020-09-25 01:54:45 -0700454 //contentJson.add(JSON_CA_CERT_ID, readString(issuedCert.getName().at(-1)));
455 _LOG_TRACE("Challenge succeeded. Certificate has been issued");
456 }
457 else if (certRequest.m_requestType == REQUEST_TYPE_REVOKE) {
458 certRequest.m_status = STATUS_SUCCESS;
459 try {
460 m_storage->deleteRequest(certRequest.m_requestId);
461 _LOG_TRACE("Certificate Revoked");
462 }
463 catch (const std::exception& e) {
464 _LOG_ERROR("Cannot add issued cert and remove the request: " << e.what());
465 return;
466 }
467
468 payload = CHALLENGE::encodeDataPayload(certRequest);
469 payload.parse();
470 _LOG_TRACE("Challenge succeeded. Certificate has been revoked");
471 }
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800472 }
473 else {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700474 try {
475 m_storage->updateRequest(certRequest);
476 }
477 catch (const std::exception& e) {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700478 _LOG_TRACE("Cannot update request instance: " << e.what());
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700479 return;
480 }
Suyong Won44d0cce2020-05-10 04:07:43 -0700481 payload = CHALLENGE::encodeDataPayload(certRequest);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700482 _LOG_TRACE("No failure no success. Challenge moves on");
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800483 }
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800484 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700485
486 Data result;
487 result.setName(request.getName());
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700488 result.setFreshnessPeriod(DEFAULT_DATA_FRESHNESS_PERIOD);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700489
490 // encrypt the content
Suyong Won7968f7a2020-05-12 01:01:25 -0700491 auto contentBlock = encodeBlockWithAesGcm128(tlv::Content, m_aesKey, payload.value(),
492 payload.value_size(), (uint8_t*)"test", strlen("test"));
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700493 result.setContent(contentBlock);
Suyong Won256c9062020-05-11 02:45:56 -0700494 m_keyChain.sign(result, signingByIdentity(m_config.m_caPrefix));
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700495 m_face.put(result);
496
497 if (m_config.m_statusUpdateCallback) {
498 m_config.m_statusUpdateCallback(certRequest);
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800499 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700500}
501
Zhiyi Zhang343cdfb2018-01-17 12:04:28 -0800502security::v2::Certificate
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700503CaModule::issueCertificate(const CertificateRequest& certRequest)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800504{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700505 auto expectedPeriod =
506 certRequest.m_cert.getValidityPeriod().getPeriod();
Zhiyi Zhang1a735bc2019-07-04 21:36:49 -0700507 security::ValidityPeriod period(expectedPeriod.first, expectedPeriod.second);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800508 security::v2::Certificate newCert;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700509
510 Name certName = certRequest.m_cert.getKeyName();
511 certName.append("NDNCERT").append(std::to_string(random::generateSecureWord64()));
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800512 newCert.setName(certName);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700513 newCert.setContent(certRequest.m_cert.getContent());
514 _LOG_TRACE("cert request content " << certRequest.m_cert);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800515 SignatureInfo signatureInfo;
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800516 signatureInfo.setValidityPeriod(period);
Zhiyi Zhangad6cf932017-10-26 16:19:15 -0700517 security::SigningInfo signingInfo(security::SigningInfo::SIGNER_TYPE_ID,
Suyong Won256c9062020-05-11 02:45:56 -0700518 m_config.m_caPrefix, signatureInfo);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800519
520 m_keyChain.sign(newCert, signingInfo);
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700521 _LOG_TRACE("new cert got signed" << newCert);
Zhiyi Zhang343cdfb2018-01-17 12:04:28 -0800522 return newCert;
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800523}
524
525CertificateRequest
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700526CaModule::getCertificateRequest(const Interest& request)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800527{
Davide Pesaventob48bbda2020-07-27 19:41:37 -0400528 std::string requestId;
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800529 CertificateRequest certRequest;
530 try {
Suyong Won256c9062020-05-11 02:45:56 -0700531 requestId = readString(request.getName().at(m_config.m_caPrefix.size() + 2));
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700532 }
533 catch (const std::exception& e) {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700534 _LOG_ERROR("Cannot read the request ID out from the request: " << e.what());
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700535 }
536 try {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700537 _LOG_TRACE("Request Id to query the database " << requestId);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800538 certRequest = m_storage->getRequest(requestId);
539 }
540 catch (const std::exception& e) {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700541 _LOG_ERROR("Cannot get certificate request record from the storage: " << e.what());
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800542 }
543 return certRequest;
544}
545
546void
547CaModule::onRegisterFailed(const std::string& reason)
548{
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700549 _LOG_ERROR("Failed to register prefix in local hub's daemon, REASON: " << reason);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800550}
551
552Block
553CaModule::dataContentFromJson(const JsonSection& jsonSection)
554{
555 std::stringstream ss;
556 boost::property_tree::write_json(ss, jsonSection);
557 return makeStringBlock(ndn::tlv::Content, ss.str());
558}
559
560JsonSection
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700561CaModule::jsonFromBlock(const Block& block)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800562{
563 std::string jsonString;
564 try {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700565 jsonString = encoding::readString(block);
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700566 std::istringstream ss(jsonString);
567 JsonSection json;
568 boost::property_tree::json_parser::read_json(ss, json);
569 return json;
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800570 }
571 catch (const std::exception& e) {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700572 _LOG_ERROR("Cannot read JSON string from TLV Value: " << e.what());
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800573 return JsonSection();
574 }
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800575}
576
577} // namespace ndncert
578} // namespace ndn