blob: 17945285c4dfd8855a5630dc05a29779df147015 [file] [log] [blame]
Zhiyi Zhangf5246c42017-01-26 09:39:20 -08001/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2/**
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -07003 * Copyright (c) 2017-2019, 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"
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +080025#include <ndn-cxx/util/io.hpp>
Zhiyi Zhangf5246c42017-01-26 09:39:20 -080026#include <ndn-cxx/security/verification-helpers.hpp>
27#include <ndn-cxx/security/signing-helpers.hpp>
Junxiao Shi7c068032017-05-28 13:40:47 +000028#include <ndn-cxx/util/random.hpp>
Zhiyi Zhangf5246c42017-01-26 09:39:20 -080029
30namespace ndn {
31namespace ndncert {
32
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070033static const int IS_SUBNAME_MIN_OFFSET = 5;
34
Zhiyi Zhangf5246c42017-01-26 09:39:20 -080035_LOG_INIT(ndncert.ca);
36
37CaModule::CaModule(Face& face, security::v2::KeyChain& keyChain,
38 const std::string& configPath, const std::string& storageType)
39 : m_face(face)
40 , m_keyChain(keyChain)
41{
Zhiyi Zhanga63b7372017-05-17 14:14:34 -070042 // load the config and create storage
Zhiyi Zhangf5246c42017-01-26 09:39:20 -080043 m_config.load(configPath);
44 m_storage = CaStorage::createCaStorage(storageType);
45
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +080046 registerPrefix();
Zhiyi Zhangf5246c42017-01-26 09:39:20 -080047}
48
49CaModule::~CaModule()
50{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070051 for (auto handle : m_interestFilterHandles) {
52 handle.cancel();
Zhiyi Zhangf5246c42017-01-26 09:39:20 -080053 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070054 for (auto handle : m_registeredPrefixHandles) {
55 handle.unregister();
Zhiyi Zhangf5246c42017-01-26 09:39:20 -080056 }
57}
58
59void
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +080060CaModule::registerPrefix()
61{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070062 // register localhop discovery prefix
63 Name localhopProbePrefix("/localhop/CA/PROBE/INFO");
64 auto prefixId = m_face.setInterestFilter(InterestFilter(localhopProbePrefix),
65 bind(&CaModule::onProbe, this, _2),
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +080066 bind(&CaModule::onRegisterFailed, this, _2));
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070067 m_registeredPrefixHandles.push_back(prefixId);
68 _LOG_TRACE("Prefix " << localhopProbePrefix << " got registered");
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +080069
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070070 // register prefixes
71 Name prefix = m_config.m_caName;
72 prefix.append("CA");
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +080073
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070074 prefixId = m_face.registerPrefix(prefix,
75 [&] (const Name& name) {
76 // register PROBE prefix
77 auto filterId = m_face.setInterestFilter(Name(name).append("_PROBE"),
78 bind(&CaModule::onProbe, this, _2));
79 m_interestFilterHandles.push_back(filterId);
80
81 // register NEW prefix
82 filterId = m_face.setInterestFilter(Name(name).append("_NEW"),
83 bind(&CaModule::onNew, this, _2));
84 m_interestFilterHandles.push_back(filterId);
85
86 // register SELECT prefix
87 filterId = m_face.setInterestFilter(Name(name).append("_CHALLENGE"),
88 bind(&CaModule::onChallenge, this, _2));
89 m_interestFilterHandles.push_back(filterId);
90
91 // register DOWNLOAD prefix
92 filterId = m_face.setInterestFilter(Name(name).append("_DOWNLOAD"),
93 bind(&CaModule::onDownload, this, _2));
94 m_interestFilterHandles.push_back(filterId);
95 _LOG_TRACE("Prefix " << name << " got registered");
96 },
97 bind(&CaModule::onRegisterFailed, this, _2));
98 m_registeredPrefixHandles.push_back(prefixId);
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +080099}
100
Zhiyi Zhang343cdfb2018-01-17 12:04:28 -0800101bool
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700102CaModule::setProbeHandler(const ProbeHandler& handler)
Zhiyi Zhang7420cf52017-12-18 18:59:21 +0800103{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700104 m_config.m_probeHandler = handler;
Zhiyi Zhang343cdfb2018-01-17 12:04:28 -0800105 return false;
Zhiyi Zhang7420cf52017-12-18 18:59:21 +0800106}
107
Zhiyi Zhang343cdfb2018-01-17 12:04:28 -0800108bool
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700109CaModule::setStatusUpdateCallback(const StatusUpdateCallback& onUpdateCallback)
Zhiyi Zhang7420cf52017-12-18 18:59:21 +0800110{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700111 m_config.m_statusUpdateCallback = onUpdateCallback;
Zhiyi Zhang343cdfb2018-01-17 12:04:28 -0800112 return false;
Zhiyi Zhang7420cf52017-12-18 18:59:21 +0800113}
114
115void
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700116CaModule::onProbe(const Interest& request)
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800117{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700118 // PROBE Naming Convention: /<CA-Prefix>/CA/PROBE/[ParametersSha256DigestComponent|INFO]
119 _LOG_TRACE("Receive PROBE request");
120 JsonSection contentJson;
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800121
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700122 // process PROBE INFO requests
123 if (readString(request.getName().at(-1)) == "INFO") {
124 contentJson = genProbeResponseJson();
125 }
126 else {
127 // if not a PROBE INFO, find an available name
128 std::string availableId = "";
129 const auto& parameterJson = jsonFromBlock(request.getApplicationParameters());
Yufeng Zhang424d0362019-06-12 16:48:27 -0700130 //m_config.m_probe
131
132 //std::string probeInfoStr = parameterJson.get(JSON_CLIENT_PROBE_INFO, "");
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700133 if (m_config.m_probeHandler) {
134 try {
Yufeng Zhang424d0362019-06-12 16:48:27 -0700135 availableId = m_config.m_probeHandler(parameterJson);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700136 }
137 catch (const std::exception& e) {
138 _LOG_TRACE("Cannot find PROBE input from PROBE parameters " << e.what());
139 return;
140 }
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800141 }
142 else {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700143 // if there is no app-specified name lookup, use a random name id
144 availableId = std::to_string(random::generateSecureWord64());
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800145 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700146 Name newIdentityName = m_config.m_caName;
147 _LOG_TRACE("Handle PROBE: generate an identity " << newIdentityName);
148 newIdentityName.append(availableId);
Yufeng Zhang424d0362019-06-12 16:48:27 -0700149 contentJson = genProbeResponseJson(newIdentityName.toUri(), m_config.m_probe, parameterJson);
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800150 }
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800151
152 Data result;
153 result.setName(request.getName());
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700154 result.setContent(dataContentFromJson(contentJson));
155 m_keyChain.sign(result, signingByIdentity(m_config.m_caName));
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800156 m_face.put(result);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700157 _LOG_TRACE("Handle PROBE: send out the PROBE response");
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800158}
159
160void
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700161CaModule::onNew(const Interest& request)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800162{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700163 // NEW Naming Convention: /<CA-prefix>/CA/NEW/[SignedInterestParameters_Digest]
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800164
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700165 // get ECDH pub key and cert request
166 const auto& parameterJson = jsonFromBlock(request.getApplicationParameters());
167 std::string peerKeyBase64 = parameterJson.get(JSON_CLIENT_ECDH, "");
168
169 // get server's ECDH pub key
170 auto myEcdhPubKeyBase64 = m_ecdh.getBase64PubKey();
171 m_ecdh.deriveSecret(peerKeyBase64);
172 // generate salt for HKDF
173 auto saltInt = random::generateSecureWord64();
174 uint8_t salt[sizeof(saltInt)];
175 std::memcpy(salt, &saltInt, sizeof(saltInt));
176 // hkdf
177 hkdf(m_ecdh.context->sharedSecret, m_ecdh.context->sharedSecretLen,
178 salt, sizeof(saltInt), m_aesKey, 32);
179
180 // parse certificate request
181 std::string certRequestStr = parameterJson.get(JSON_CLIENT_CERT_REQ, "");
182 shared_ptr<security::v2::Certificate> clientCert = nullptr;
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800183 try {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700184 std::stringstream ss(certRequestStr);
185 clientCert = io::load<security::v2::Certificate>(ss);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800186 }
187 catch (const std::exception& e) {
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700188 _LOG_ERROR("Unrecognized certificate request " << e.what());
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800189 return;
190 }
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700191
Zhiyi Zhang5f749a22019-06-12 17:02:33 -0700192 // parse probe token if any
193 std::string probeTokenStr = parameterJson.get("probe-token", "");
194 shared_ptr<Data> probeToken = nullptr;
195 if (probeTokenStr != "") {
196 try {
197 std::stringstream ss(probeTokenStr);
198 probeToken = io::load<security::v2::Certificate>(ss);
199 }
200 catch (const std::exception& e) {
201 _LOG_ERROR("Unrecognized probe token " << e.what());
202 return;
203 }
204 }
205 if (probeToken != nullptr) {
206 Name prefix = m_config.m_caName;
207 prefix.append("CA").append("_PROBE");
208 if (!prefix.isPrefixOf(probeToken->getName())) {
209 // the carried probe token is not a Probe Data packet
210 return;
211 }
212 }
213
214 // verify the self-signed certificate, the request, and the token
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700215 if (!m_config.m_caName.isPrefixOf(clientCert->getName()) // under ca prefix
216 || !security::v2::Certificate::isValidName(clientCert->getName()) // is valid cert name
217 || clientCert->getName().size() != m_config.m_caName.size() + IS_SUBNAME_MIN_OFFSET) {
218 _LOG_ERROR("Invalid self-signed certificate name " << clientCert->getName());
219 return;
220 }
221 if (!security::verifySignature(*clientCert, *clientCert)) {
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700222 _LOG_TRACE("Cert request with bad signature.");
223 return;
224 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700225 if (!security::verifySignature(request, *clientCert)) {
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700226 _LOG_TRACE("Interest with bad signature.");
227 return;
228 }
Zhiyi Zhang5f749a22019-06-12 17:02:33 -0700229 if (probeToken != nullptr) {
230 const auto& pib = m_keyChain.getPib();
231 const auto& key = pib.getIdentity(m_config.m_caName).getDefaultKey();
232 const auto& caCert = key.getDefaultCertificate();
233 if (!security::verifySignature(*probeToken, caCert)) {
234 _LOG_TRACE("Token with bad signature.");
235 return;
236 }
237 }
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700238
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700239 // create new request instance
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800240 std::string requestId = std::to_string(random::generateWord64());
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700241 CertificateRequest certRequest(m_config.m_caName, requestId, STATUS_BEFORE_CHALLENGE, *clientCert);
Zhiyi Zhang5f749a22019-06-12 17:02:33 -0700242 if (probeToken != nullptr) {
243 certRequest.setProbeToken(probeToken);
244 }
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800245 try {
246 m_storage->addRequest(certRequest);
247 }
248 catch (const std::exception& e) {
Zhiyi Zhang5f749a22019-06-12 17:02:33 -0700249 _LOG_TRACE("Cannot add new request instance into the storage " << e.what());
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800250 return;
251 }
252
253 Data result;
254 result.setName(request.getName());
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700255 result.setContent(dataContentFromJson(genNewResponseJson(myEcdhPubKeyBase64,
256 std::to_string(saltInt),
257 certRequest,
258 m_config.m_supportedChallenges)));
259 m_keyChain.sign(result, signingByIdentity(m_config.m_caName));
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800260 m_face.put(result);
Zhiyi Zhanga63b7372017-05-17 14:14:34 -0700261
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700262 if (m_config.m_statusUpdateCallback) {
263 m_config.m_statusUpdateCallback(certRequest);
Zhiyi Zhang7420cf52017-12-18 18:59:21 +0800264 }
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800265}
266
267void
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700268CaModule::onChallenge(const Interest& request)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800269{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700270 // get certificate request state
271 CertificateRequest certRequest = getCertificateRequest(request);
272 if (certRequest.m_requestId == "") {
273 // cannot get the request state
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800274 return;
275 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700276 // verify signature
277 if (!security::verifySignature(request, certRequest.m_cert)) {
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700278 _LOG_TRACE("Interest with bad signature.");
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800279 return;
280 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700281 // decrypt the parameters
282 auto paramJsonPayload = parseEncBlock(m_ecdh.context->sharedSecret,
283 m_ecdh.context->sharedSecretLen,
284 request.getApplicationParameters());
285 std::string paramJsonStr((const char*)paramJsonPayload.data(), paramJsonPayload.size());
286 std::istringstream ss(paramJsonStr);
287 JsonSection paramJson;
288 boost::property_tree::json_parser::read_json(ss, paramJson);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800289
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700290 // load the corresponding challenge module
291 std::string challengeType = paramJson.get<std::string>(JSON_CLIENT_SELECTED_CHALLENGE);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800292 auto challenge = ChallengeModule::createChallengeModule(challengeType);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700293 JsonSection contentJson;
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800294 if (challenge == nullptr) {
295 _LOG_TRACE("Unrecognized challenge type " << challengeType);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700296 certRequest.m_status = STATUS_FAILURE;
297 certRequest.m_challengeStatus = CHALLENGE_STATUS_UNKNOWN_CHALLENGE;
298 contentJson = genChallengeResponseJson(certRequest);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800299 }
Zhiyi Zhanga9bda732017-05-20 22:58:55 -0700300 else {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700301 _LOG_TRACE("CHALLENGE module to be load: " << challengeType);
302 // let challenge module handle the request
303 challenge->handleChallengeRequest(paramJson, certRequest);
304 if (certRequest.m_status == STATUS_FAILURE) {
305 // if challenge failed
306 m_storage->deleteRequest(certRequest.m_requestId);
307 contentJson = genChallengeResponseJson(certRequest);
308 _LOG_TRACE("Challenge failed");
Zhiyi Zhanga9bda732017-05-20 22:58:55 -0700309 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700310 else if (certRequest.m_status == STATUS_PENDING) {
311 // if challenge succeeded
312 auto issuedCert = issueCertificate(certRequest);
313 certRequest.m_cert = issuedCert;
314 certRequest.m_status = STATUS_SUCCESS;
315 try {
316 m_storage->addCertificate(certRequest.m_requestId, issuedCert);
317 m_storage->deleteRequest(certRequest.m_requestId);
318 _LOG_TRACE("New Certificate Issued " << issuedCert.getName());
319 }
320 catch (const std::exception& e) {
321 _LOG_ERROR("Cannot add issued cert and remove the request " << e.what());
322 return;
323 }
324 if (m_config.m_statusUpdateCallback) {
325 m_config.m_statusUpdateCallback(certRequest);
326 }
327 contentJson = genChallengeResponseJson(certRequest);
328 contentJson.add(JSON_CA_CERT_ID, readString(issuedCert.getName().at(-1)));
329 _LOG_TRACE("Challenge succeeded. Certificate has been issued");
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800330 }
331 else {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700332 try {
333 m_storage->updateRequest(certRequest);
334 }
335 catch (const std::exception& e) {
336 _LOG_TRACE("Cannot update request instance " << e.what());
337 return;
338 }
339 contentJson = genChallengeResponseJson(certRequest);
340 _LOG_TRACE("No failure no success. Challenge moves on");
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800341 }
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800342 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700343
344 Data result;
345 result.setName(request.getName());
346
347 // encrypt the content
348 std::stringstream ss2;
349 boost::property_tree::write_json(ss2, contentJson);
350 auto payload = ss2.str();
351 auto contentBlock = genEncBlock(tlv::Content, m_ecdh.context->sharedSecret,
352 m_ecdh.context->sharedSecretLen,
353 (const uint8_t*)payload.c_str(), payload.size());
354 result.setContent(contentBlock);
355 m_keyChain.sign(result, signingByIdentity(m_config.m_caName));
356 m_face.put(result);
357
358 if (m_config.m_statusUpdateCallback) {
359 m_config.m_statusUpdateCallback(certRequest);
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800360 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700361}
362
363void
364CaModule::onDownload(const Interest& request)
365{
366 auto requestId = readString(request.getName().at(-1));
367 security::v2::Certificate signedCert;
368 try {
369 signedCert = m_storage->getCertificate(requestId);
370 }
371 catch (const std::exception& e) {
372 _LOG_ERROR("Cannot read signed cert " << requestId << " from ca database " << e.what());
373 return;
374 }
375 Data result;
376 result.setName(request.getName());
377 result.setContent(signedCert.wireEncode());
378 m_keyChain.sign(result, signingByIdentity(m_config.m_caName));
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800379 m_face.put(result);
380}
381
Zhiyi Zhang343cdfb2018-01-17 12:04:28 -0800382security::v2::Certificate
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700383CaModule::issueCertificate(const CertificateRequest& certRequest)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800384{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700385 auto expectedPeriod =
386 certRequest.m_cert.getValidityPeriod().getPeriod();
387
388 time::system_clock::TimePoint startingTime, endingTime;
389 if (expectedPeriod.first > time::system_clock::now()
390 && expectedPeriod.first < time::system_clock::now()
391 + m_config.m_validityPeriod)
392 {
393 startingTime = expectedPeriod.first;
394 }
395 else {
396 startingTime = time::system_clock::now();
397 }
398 if (expectedPeriod.second < time::system_clock::now() + m_config.m_validityPeriod) {
399 endingTime = expectedPeriod.second;
400 }
401 else {
402 endingTime = time::system_clock::now() + m_config.m_validityPeriod;
403 }
404 security::ValidityPeriod period(startingTime, endingTime);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800405 security::v2::Certificate newCert;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700406
407 Name certName = certRequest.m_cert.getKeyName();
408 certName.append("NDNCERT").append(std::to_string(random::generateSecureWord64()));
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800409 newCert.setName(certName);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700410 newCert.setContent(certRequest.m_cert.getContent());
411 _LOG_TRACE("cert request content " << certRequest.m_cert);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800412 SignatureInfo signatureInfo;
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800413 signatureInfo.setValidityPeriod(period);
Zhiyi Zhangad6cf932017-10-26 16:19:15 -0700414 security::SigningInfo signingInfo(security::SigningInfo::SIGNER_TYPE_ID,
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700415 m_config.m_caName, signatureInfo);
416 newCert.setFreshnessPeriod(m_config.m_freshnessPeriod);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800417
418 m_keyChain.sign(newCert, signingInfo);
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700419 _LOG_TRACE("new cert got signed" << newCert);
Zhiyi Zhang343cdfb2018-01-17 12:04:28 -0800420 return newCert;
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800421}
422
423CertificateRequest
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700424CaModule::getCertificateRequest(const Interest& request)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800425{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700426 std::string requestId = readString(request.getName().at(m_config.m_caName.size() + 2));
Zhiyi Zhang5f749a22019-06-12 17:02:33 -0700427 _LOG_TRACE("Request Id to query the database " << requestId);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800428 CertificateRequest certRequest;
429 try {
430 certRequest = m_storage->getRequest(requestId);
431 }
432 catch (const std::exception& e) {
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700433 _LOG_ERROR(e.what());
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800434 }
435 return certRequest;
436}
437
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700438/**
439 * @brief Generate JSON file to response PROBE insterest
440 *
441 * PROBE response JSON format:
442 * {
Yufeng Zhang424d0362019-06-12 16:48:27 -0700443 * "name": "@p identifier"
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700444 * }
445 */
446const JsonSection
Yufeng Zhang424d0362019-06-12 16:48:27 -0700447CaModule::genProbeResponseJson(const Name& identifier, const std::string& m_probe, const JsonSection& parameterJson)
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700448{
Yufeng Zhang424d0362019-06-12 16:48:27 -0700449 std::vector<std::string> fields;
450 std::string delimiter = ":";
451 size_t last = 0;
452 size_t next = 0;
453 while ((next = m_probe.find(delimiter, last)) != std::string::npos) {
454 fields.push_back(m_probe.substr(last, next - last));
455 last = next + 1;
456 }
457 fields.push_back(m_probe.substr(last));
458
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700459 JsonSection root;
Yufeng Zhang424d0362019-06-12 16:48:27 -0700460
461 for (size_t i = 0; i < fields.size(); ++i) {
462 root.put(fields.at(i), parameterJson.get(fields.at(i), ""));
463 }
464
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700465 root.put(JSON_CA_NAME, identifier.toUri());
466 return root;
467}
468
469/**
470 * @brief Generate JSON file to response NEW interest
471 *
472 * Target JSON format:
473 * {
474 * "ecdh-pub": "@p echdPub",
475 * "salt": "@p salt"
476 * "request-id": "@p requestId",
477 * "status": "@p status",
478 * "challenges": [
479 * {
480 * "challenge-id": ""
481 * },
482 * {
483 * "challenge-id": ""
484 * },
485 * ...
486 * ]
487 * }
488 */
489const JsonSection
490CaModule::genProbeResponseJson()
491{
492 JsonSection root;
493 // ca-prefix
494 Name caName = m_config.m_caName;
495 root.put("ca-prefix", caName.toUri());
496
497 // ca-info
498 const auto& pib = m_keyChain.getPib();
499 auto identity = pib.getIdentity(m_config.m_caName);
500 auto cert = identity.getDefaultKey().getDefaultCertificate();
501 std::string caInfo = "";
502 if (m_config.m_caInfo == "") {
503 caInfo = "Issued by " + cert.getSignature().getKeyLocator().getName().toUri();
504 }
505 else {
506 caInfo = m_config.m_caInfo;
507 }
508 root.put("ca-info", caInfo);
509
510 // probe
511 root.put("probe", m_config.m_probe);
512
513 // certificate
514 std::stringstream ss;
515 io::save(cert, ss);
516 root.put("certificate", ss.str());
517
518 return root;
519}
520
521const JsonSection
522CaModule::genNewResponseJson(const std::string& ecdhKey, const std::string& salt,
523 const CertificateRequest& request,
524 const std::list<std::string>& challenges)
525{
526 JsonSection root;
527 JsonSection challengesSection;
528 root.put(JSON_CA_ECDH, ecdhKey);
529 root.put(JSON_CA_SALT, salt);
530 root.put(JSON_CA_EQUEST_ID, request.m_requestId);
531 root.put(JSON_CA_STATUS, std::to_string(request.m_status));
532
533 for (const auto& entry : challenges) {
534 JsonSection challenge;
535 challenge.put(JSON_CA_CHALLENGE_ID, entry);
536 challengesSection.push_back(std::make_pair("", challenge));
537 }
538 root.add_child(JSON_CA_CHALLENGES, challengesSection);
539 return root;
540}
541
542const JsonSection
543CaModule::genChallengeResponseJson(const CertificateRequest& request)
544{
545 JsonSection root;
546 JsonSection challengesSection;
547 root.put(JSON_CA_STATUS, request.m_status);
548 root.put(JSON_CHALLENGE_STATUS, request.m_challengeStatus);
549 root.put(JSON_CHALLENGE_REMAINING_TRIES, std::to_string(request.m_remainingTries));
550 root.put(JSON_CHALLENGE_REMAINING_TIME, std::to_string(request.m_remainingTime));
551 return root;
552}
553
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800554void
555CaModule::onRegisterFailed(const std::string& reason)
556{
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700557 _LOG_ERROR("Failed to register prefix in local hub's daemon, REASON: " << reason);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800558}
559
560Block
561CaModule::dataContentFromJson(const JsonSection& jsonSection)
562{
563 std::stringstream ss;
564 boost::property_tree::write_json(ss, jsonSection);
565 return makeStringBlock(ndn::tlv::Content, ss.str());
566}
567
568JsonSection
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700569CaModule::jsonFromBlock(const Block& block)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800570{
571 std::string jsonString;
572 try {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700573 jsonString = encoding::readString(block);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800574 }
575 catch (const std::exception& e) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700576 _LOG_ERROR("Cannot read JSON string from TLV Value" << e.what());
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800577 return JsonSection();
578 }
579 std::istringstream ss(jsonString);
580 JsonSection json;
581 boost::property_tree::json_parser::read_json(ss, json);
582 return json;
583}
584
585} // namespace ndncert
586} // namespace ndn