blob: 74985aad41aaefdd93a8854b1e9c63b99aa968e2 [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);
Zhiyi Zhanga1fc6232019-06-13 14:56:59 -0700198 probeToken = io::load<Data>(ss);
Zhiyi Zhang5f749a22019-06-12 17:02:33 -0700199 }
200 catch (const std::exception& e) {
201 _LOG_ERROR("Unrecognized probe token " << e.what());
202 return;
203 }
204 }
Zhiyi Zhanga1fc6232019-06-13 14:56:59 -0700205 if (probeToken == nullptr && m_config.m_probe != "") {
206 // the CA requires PROBE before NEW
207 _LOG_ERROR("CA requires PROBE but no PROBE token is found in NEW Interest.");
208 return;
209 }
210 else if (probeToken != nullptr) {
211 // check whether the carried probe token is a PROBE Data packet
Zhiyi Zhang5f749a22019-06-12 17:02:33 -0700212 Name prefix = m_config.m_caName;
213 prefix.append("CA").append("_PROBE");
214 if (!prefix.isPrefixOf(probeToken->getName())) {
Zhiyi Zhanga1fc6232019-06-13 14:56:59 -0700215 _LOG_ERROR("Carried PROBE token is not a valid PROBE Data packet.");
Zhiyi Zhang5f749a22019-06-12 17:02:33 -0700216 return;
217 }
218 }
219
220 // verify the self-signed certificate, the request, and the token
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700221 if (!m_config.m_caName.isPrefixOf(clientCert->getName()) // under ca prefix
222 || !security::v2::Certificate::isValidName(clientCert->getName()) // is valid cert name
223 || clientCert->getName().size() != m_config.m_caName.size() + IS_SUBNAME_MIN_OFFSET) {
224 _LOG_ERROR("Invalid self-signed certificate name " << clientCert->getName());
225 return;
226 }
227 if (!security::verifySignature(*clientCert, *clientCert)) {
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700228 _LOG_TRACE("Cert request with bad signature.");
229 return;
230 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700231 if (!security::verifySignature(request, *clientCert)) {
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700232 _LOG_TRACE("Interest with bad signature.");
233 return;
234 }
Zhiyi Zhang5f749a22019-06-12 17:02:33 -0700235 if (probeToken != nullptr) {
236 const auto& pib = m_keyChain.getPib();
237 const auto& key = pib.getIdentity(m_config.m_caName).getDefaultKey();
238 const auto& caCert = key.getDefaultCertificate();
239 if (!security::verifySignature(*probeToken, caCert)) {
Zhiyi Zhanga1fc6232019-06-13 14:56:59 -0700240 _LOG_TRACE("PROBE Token with bad signature.");
Zhiyi Zhang5f749a22019-06-12 17:02:33 -0700241 return;
242 }
243 }
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700244
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700245 // create new request instance
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800246 std::string requestId = std::to_string(random::generateWord64());
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700247 CertificateRequest certRequest(m_config.m_caName, requestId, STATUS_BEFORE_CHALLENGE, *clientCert);
Zhiyi Zhang5f749a22019-06-12 17:02:33 -0700248 if (probeToken != nullptr) {
249 certRequest.setProbeToken(probeToken);
250 }
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800251 try {
252 m_storage->addRequest(certRequest);
253 }
254 catch (const std::exception& e) {
Zhiyi Zhang5f749a22019-06-12 17:02:33 -0700255 _LOG_TRACE("Cannot add new request instance into the storage " << e.what());
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800256 return;
257 }
258
259 Data result;
260 result.setName(request.getName());
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700261 result.setContent(dataContentFromJson(genNewResponseJson(myEcdhPubKeyBase64,
262 std::to_string(saltInt),
263 certRequest,
264 m_config.m_supportedChallenges)));
265 m_keyChain.sign(result, signingByIdentity(m_config.m_caName));
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800266 m_face.put(result);
Zhiyi Zhanga63b7372017-05-17 14:14:34 -0700267
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700268 if (m_config.m_statusUpdateCallback) {
269 m_config.m_statusUpdateCallback(certRequest);
Zhiyi Zhang7420cf52017-12-18 18:59:21 +0800270 }
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800271}
272
273void
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700274CaModule::onChallenge(const Interest& request)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800275{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700276 // get certificate request state
277 CertificateRequest certRequest = getCertificateRequest(request);
278 if (certRequest.m_requestId == "") {
279 // cannot get the request state
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800280 return;
281 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700282 // verify signature
283 if (!security::verifySignature(request, certRequest.m_cert)) {
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700284 _LOG_TRACE("Interest with bad signature.");
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800285 return;
286 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700287 // decrypt the parameters
288 auto paramJsonPayload = parseEncBlock(m_ecdh.context->sharedSecret,
289 m_ecdh.context->sharedSecretLen,
290 request.getApplicationParameters());
291 std::string paramJsonStr((const char*)paramJsonPayload.data(), paramJsonPayload.size());
292 std::istringstream ss(paramJsonStr);
293 JsonSection paramJson;
294 boost::property_tree::json_parser::read_json(ss, paramJson);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800295
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700296 // load the corresponding challenge module
297 std::string challengeType = paramJson.get<std::string>(JSON_CLIENT_SELECTED_CHALLENGE);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800298 auto challenge = ChallengeModule::createChallengeModule(challengeType);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700299 JsonSection contentJson;
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800300 if (challenge == nullptr) {
301 _LOG_TRACE("Unrecognized challenge type " << challengeType);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700302 certRequest.m_status = STATUS_FAILURE;
303 certRequest.m_challengeStatus = CHALLENGE_STATUS_UNKNOWN_CHALLENGE;
304 contentJson = genChallengeResponseJson(certRequest);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800305 }
Zhiyi Zhanga9bda732017-05-20 22:58:55 -0700306 else {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700307 _LOG_TRACE("CHALLENGE module to be load: " << challengeType);
308 // let challenge module handle the request
309 challenge->handleChallengeRequest(paramJson, certRequest);
310 if (certRequest.m_status == STATUS_FAILURE) {
311 // if challenge failed
312 m_storage->deleteRequest(certRequest.m_requestId);
313 contentJson = genChallengeResponseJson(certRequest);
314 _LOG_TRACE("Challenge failed");
Zhiyi Zhanga9bda732017-05-20 22:58:55 -0700315 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700316 else if (certRequest.m_status == STATUS_PENDING) {
317 // if challenge succeeded
318 auto issuedCert = issueCertificate(certRequest);
319 certRequest.m_cert = issuedCert;
320 certRequest.m_status = STATUS_SUCCESS;
321 try {
322 m_storage->addCertificate(certRequest.m_requestId, issuedCert);
323 m_storage->deleteRequest(certRequest.m_requestId);
324 _LOG_TRACE("New Certificate Issued " << issuedCert.getName());
325 }
326 catch (const std::exception& e) {
327 _LOG_ERROR("Cannot add issued cert and remove the request " << e.what());
328 return;
329 }
330 if (m_config.m_statusUpdateCallback) {
331 m_config.m_statusUpdateCallback(certRequest);
332 }
333 contentJson = genChallengeResponseJson(certRequest);
334 contentJson.add(JSON_CA_CERT_ID, readString(issuedCert.getName().at(-1)));
335 _LOG_TRACE("Challenge succeeded. Certificate has been issued");
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800336 }
337 else {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700338 try {
339 m_storage->updateRequest(certRequest);
340 }
341 catch (const std::exception& e) {
342 _LOG_TRACE("Cannot update request instance " << e.what());
343 return;
344 }
345 contentJson = genChallengeResponseJson(certRequest);
346 _LOG_TRACE("No failure no success. Challenge moves on");
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800347 }
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800348 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700349
350 Data result;
351 result.setName(request.getName());
352
353 // encrypt the content
354 std::stringstream ss2;
355 boost::property_tree::write_json(ss2, contentJson);
356 auto payload = ss2.str();
357 auto contentBlock = genEncBlock(tlv::Content, m_ecdh.context->sharedSecret,
358 m_ecdh.context->sharedSecretLen,
359 (const uint8_t*)payload.c_str(), payload.size());
360 result.setContent(contentBlock);
361 m_keyChain.sign(result, signingByIdentity(m_config.m_caName));
362 m_face.put(result);
363
364 if (m_config.m_statusUpdateCallback) {
365 m_config.m_statusUpdateCallback(certRequest);
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800366 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700367}
368
369void
370CaModule::onDownload(const Interest& request)
371{
372 auto requestId = readString(request.getName().at(-1));
373 security::v2::Certificate signedCert;
374 try {
375 signedCert = m_storage->getCertificate(requestId);
376 }
377 catch (const std::exception& e) {
378 _LOG_ERROR("Cannot read signed cert " << requestId << " from ca database " << e.what());
379 return;
380 }
381 Data result;
382 result.setName(request.getName());
383 result.setContent(signedCert.wireEncode());
384 m_keyChain.sign(result, signingByIdentity(m_config.m_caName));
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800385 m_face.put(result);
386}
387
Zhiyi Zhang343cdfb2018-01-17 12:04:28 -0800388security::v2::Certificate
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700389CaModule::issueCertificate(const CertificateRequest& certRequest)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800390{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700391 auto expectedPeriod =
392 certRequest.m_cert.getValidityPeriod().getPeriod();
393
394 time::system_clock::TimePoint startingTime, endingTime;
395 if (expectedPeriod.first > time::system_clock::now()
396 && expectedPeriod.first < time::system_clock::now()
397 + m_config.m_validityPeriod)
398 {
399 startingTime = expectedPeriod.first;
400 }
401 else {
402 startingTime = time::system_clock::now();
403 }
404 if (expectedPeriod.second < time::system_clock::now() + m_config.m_validityPeriod) {
405 endingTime = expectedPeriod.second;
406 }
407 else {
408 endingTime = time::system_clock::now() + m_config.m_validityPeriod;
409 }
410 security::ValidityPeriod period(startingTime, endingTime);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800411 security::v2::Certificate newCert;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700412
413 Name certName = certRequest.m_cert.getKeyName();
414 certName.append("NDNCERT").append(std::to_string(random::generateSecureWord64()));
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800415 newCert.setName(certName);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700416 newCert.setContent(certRequest.m_cert.getContent());
417 _LOG_TRACE("cert request content " << certRequest.m_cert);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800418 SignatureInfo signatureInfo;
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800419 signatureInfo.setValidityPeriod(period);
Zhiyi Zhangad6cf932017-10-26 16:19:15 -0700420 security::SigningInfo signingInfo(security::SigningInfo::SIGNER_TYPE_ID,
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700421 m_config.m_caName, signatureInfo);
422 newCert.setFreshnessPeriod(m_config.m_freshnessPeriod);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800423
424 m_keyChain.sign(newCert, signingInfo);
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700425 _LOG_TRACE("new cert got signed" << newCert);
Zhiyi Zhang343cdfb2018-01-17 12:04:28 -0800426 return newCert;
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800427}
428
429CertificateRequest
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700430CaModule::getCertificateRequest(const Interest& request)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800431{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700432 std::string requestId = readString(request.getName().at(m_config.m_caName.size() + 2));
Zhiyi Zhang5f749a22019-06-12 17:02:33 -0700433 _LOG_TRACE("Request Id to query the database " << requestId);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800434 CertificateRequest certRequest;
435 try {
436 certRequest = m_storage->getRequest(requestId);
437 }
438 catch (const std::exception& e) {
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700439 _LOG_ERROR(e.what());
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800440 }
441 return certRequest;
442}
443
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700444/**
445 * @brief Generate JSON file to response PROBE insterest
446 *
447 * PROBE response JSON format:
448 * {
Yufeng Zhang424d0362019-06-12 16:48:27 -0700449 * "name": "@p identifier"
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700450 * }
451 */
452const JsonSection
Yufeng Zhang424d0362019-06-12 16:48:27 -0700453CaModule::genProbeResponseJson(const Name& identifier, const std::string& m_probe, const JsonSection& parameterJson)
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700454{
Yufeng Zhang424d0362019-06-12 16:48:27 -0700455 std::vector<std::string> fields;
456 std::string delimiter = ":";
457 size_t last = 0;
458 size_t next = 0;
459 while ((next = m_probe.find(delimiter, last)) != std::string::npos) {
460 fields.push_back(m_probe.substr(last, next - last));
461 last = next + 1;
462 }
463 fields.push_back(m_probe.substr(last));
464
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700465 JsonSection root;
Yufeng Zhang424d0362019-06-12 16:48:27 -0700466
467 for (size_t i = 0; i < fields.size(); ++i) {
468 root.put(fields.at(i), parameterJson.get(fields.at(i), ""));
469 }
470
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700471 root.put(JSON_CA_NAME, identifier.toUri());
472 return root;
473}
474
475/**
476 * @brief Generate JSON file to response NEW interest
477 *
478 * Target JSON format:
479 * {
480 * "ecdh-pub": "@p echdPub",
481 * "salt": "@p salt"
482 * "request-id": "@p requestId",
483 * "status": "@p status",
484 * "challenges": [
485 * {
486 * "challenge-id": ""
487 * },
488 * {
489 * "challenge-id": ""
490 * },
491 * ...
492 * ]
493 * }
494 */
495const JsonSection
496CaModule::genProbeResponseJson()
497{
498 JsonSection root;
499 // ca-prefix
500 Name caName = m_config.m_caName;
501 root.put("ca-prefix", caName.toUri());
502
503 // ca-info
504 const auto& pib = m_keyChain.getPib();
505 auto identity = pib.getIdentity(m_config.m_caName);
506 auto cert = identity.getDefaultKey().getDefaultCertificate();
507 std::string caInfo = "";
508 if (m_config.m_caInfo == "") {
509 caInfo = "Issued by " + cert.getSignature().getKeyLocator().getName().toUri();
510 }
511 else {
512 caInfo = m_config.m_caInfo;
513 }
514 root.put("ca-info", caInfo);
515
516 // probe
517 root.put("probe", m_config.m_probe);
518
519 // certificate
520 std::stringstream ss;
521 io::save(cert, ss);
522 root.put("certificate", ss.str());
523
524 return root;
525}
526
527const JsonSection
528CaModule::genNewResponseJson(const std::string& ecdhKey, const std::string& salt,
529 const CertificateRequest& request,
530 const std::list<std::string>& challenges)
531{
532 JsonSection root;
533 JsonSection challengesSection;
534 root.put(JSON_CA_ECDH, ecdhKey);
535 root.put(JSON_CA_SALT, salt);
536 root.put(JSON_CA_EQUEST_ID, request.m_requestId);
537 root.put(JSON_CA_STATUS, std::to_string(request.m_status));
538
539 for (const auto& entry : challenges) {
540 JsonSection challenge;
541 challenge.put(JSON_CA_CHALLENGE_ID, entry);
542 challengesSection.push_back(std::make_pair("", challenge));
543 }
544 root.add_child(JSON_CA_CHALLENGES, challengesSection);
545 return root;
546}
547
548const JsonSection
549CaModule::genChallengeResponseJson(const CertificateRequest& request)
550{
551 JsonSection root;
552 JsonSection challengesSection;
553 root.put(JSON_CA_STATUS, request.m_status);
554 root.put(JSON_CHALLENGE_STATUS, request.m_challengeStatus);
555 root.put(JSON_CHALLENGE_REMAINING_TRIES, std::to_string(request.m_remainingTries));
556 root.put(JSON_CHALLENGE_REMAINING_TIME, std::to_string(request.m_remainingTime));
557 return root;
558}
559
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800560void
561CaModule::onRegisterFailed(const std::string& reason)
562{
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700563 _LOG_ERROR("Failed to register prefix in local hub's daemon, REASON: " << reason);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800564}
565
566Block
567CaModule::dataContentFromJson(const JsonSection& jsonSection)
568{
569 std::stringstream ss;
570 boost::property_tree::write_json(ss, jsonSection);
571 return makeStringBlock(ndn::tlv::Content, ss.str());
572}
573
574JsonSection
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700575CaModule::jsonFromBlock(const Block& block)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800576{
577 std::string jsonString;
578 try {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700579 jsonString = encoding::readString(block);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800580 }
581 catch (const std::exception& e) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700582 _LOG_ERROR("Cannot read JSON string from TLV Value" << e.what());
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800583 return JsonSection();
584 }
585 std::istringstream ss(jsonString);
586 JsonSection json;
587 boost::property_tree::json_parser::read_json(ss, json);
588 return json;
589}
590
591} // namespace ndncert
592} // namespace ndn