blob: a6855db09de3237a00fffc4be3d64853bbf8136b [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;
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -070034static const time::seconds DEFAULT_DATA_FRESHNESS_PERIOD = 1_s;
Zhiyi Zhang1a735bc2019-07-04 21:36:49 -070035static const time::seconds REQUEST_VALIDITY_PERIOD_NOT_BEFORE_GRACE_PERIOD = 120_s;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070036
Zhiyi Zhangf5246c42017-01-26 09:39:20 -080037_LOG_INIT(ndncert.ca);
38
39CaModule::CaModule(Face& face, security::v2::KeyChain& keyChain,
40 const std::string& configPath, const std::string& storageType)
41 : m_face(face)
42 , m_keyChain(keyChain)
43{
Zhiyi Zhanga63b7372017-05-17 14:14:34 -070044 // load the config and create storage
Zhiyi Zhangf5246c42017-01-26 09:39:20 -080045 m_config.load(configPath);
46 m_storage = CaStorage::createCaStorage(storageType);
47
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +080048 registerPrefix();
Zhiyi Zhangf5246c42017-01-26 09:39:20 -080049}
50
51CaModule::~CaModule()
52{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070053 for (auto handle : m_interestFilterHandles) {
54 handle.cancel();
Zhiyi Zhangf5246c42017-01-26 09:39:20 -080055 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070056 for (auto handle : m_registeredPrefixHandles) {
57 handle.unregister();
Zhiyi Zhangf5246c42017-01-26 09:39:20 -080058 }
59}
60
61void
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +080062CaModule::registerPrefix()
63{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070064 // register localhop discovery prefix
65 Name localhopProbePrefix("/localhop/CA/PROBE/INFO");
66 auto prefixId = m_face.setInterestFilter(InterestFilter(localhopProbePrefix),
67 bind(&CaModule::onProbe, this, _2),
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +080068 bind(&CaModule::onRegisterFailed, this, _2));
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070069 m_registeredPrefixHandles.push_back(prefixId);
70 _LOG_TRACE("Prefix " << localhopProbePrefix << " got registered");
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +080071
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070072 // register prefixes
73 Name prefix = m_config.m_caName;
74 prefix.append("CA");
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +080075
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070076 prefixId = m_face.registerPrefix(prefix,
77 [&] (const Name& name) {
78 // register PROBE prefix
79 auto filterId = m_face.setInterestFilter(Name(name).append("_PROBE"),
80 bind(&CaModule::onProbe, this, _2));
81 m_interestFilterHandles.push_back(filterId);
82
83 // register NEW prefix
84 filterId = m_face.setInterestFilter(Name(name).append("_NEW"),
85 bind(&CaModule::onNew, this, _2));
86 m_interestFilterHandles.push_back(filterId);
87
88 // register SELECT prefix
89 filterId = m_face.setInterestFilter(Name(name).append("_CHALLENGE"),
90 bind(&CaModule::onChallenge, this, _2));
91 m_interestFilterHandles.push_back(filterId);
92
93 // register DOWNLOAD prefix
94 filterId = m_face.setInterestFilter(Name(name).append("_DOWNLOAD"),
95 bind(&CaModule::onDownload, this, _2));
96 m_interestFilterHandles.push_back(filterId);
97 _LOG_TRACE("Prefix " << name << " got registered");
98 },
99 bind(&CaModule::onRegisterFailed, this, _2));
100 m_registeredPrefixHandles.push_back(prefixId);
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800101}
102
Zhiyi Zhang343cdfb2018-01-17 12:04:28 -0800103bool
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700104CaModule::setProbeHandler(const ProbeHandler& handler)
Zhiyi Zhang7420cf52017-12-18 18:59:21 +0800105{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700106 m_config.m_probeHandler = handler;
Zhiyi Zhang343cdfb2018-01-17 12:04:28 -0800107 return false;
Zhiyi Zhang7420cf52017-12-18 18:59:21 +0800108}
109
Zhiyi Zhang343cdfb2018-01-17 12:04:28 -0800110bool
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700111CaModule::setStatusUpdateCallback(const StatusUpdateCallback& onUpdateCallback)
Zhiyi Zhang7420cf52017-12-18 18:59:21 +0800112{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700113 m_config.m_statusUpdateCallback = onUpdateCallback;
Zhiyi Zhang343cdfb2018-01-17 12:04:28 -0800114 return false;
Zhiyi Zhang7420cf52017-12-18 18:59:21 +0800115}
116
117void
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700118CaModule::onProbe(const Interest& request)
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800119{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700120 // PROBE Naming Convention: /<CA-Prefix>/CA/PROBE/[ParametersSha256DigestComponent|INFO]
121 _LOG_TRACE("Receive PROBE request");
122 JsonSection contentJson;
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800123
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700124 // process PROBE INFO requests
125 if (readString(request.getName().at(-1)) == "INFO") {
126 contentJson = genProbeResponseJson();
127 }
128 else {
129 // if not a PROBE INFO, find an available name
130 std::string availableId = "";
131 const auto& parameterJson = jsonFromBlock(request.getApplicationParameters());
Zhiyi Zhang547c8512019-06-18 23:46:14 -0700132 if (parameterJson.empty()) {
133 _LOG_ERROR("Empty JSON obtained from the Interest parameter.");
134 return;
135 }
Yufeng Zhang424d0362019-06-12 16:48:27 -0700136 //std::string probeInfoStr = parameterJson.get(JSON_CLIENT_PROBE_INFO, "");
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700137 if (m_config.m_probeHandler) {
138 try {
Yufeng Zhang424d0362019-06-12 16:48:27 -0700139 availableId = m_config.m_probeHandler(parameterJson);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700140 }
141 catch (const std::exception& e) {
142 _LOG_TRACE("Cannot find PROBE input from PROBE parameters " << e.what());
143 return;
144 }
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800145 }
146 else {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700147 // if there is no app-specified name lookup, use a random name id
148 availableId = std::to_string(random::generateSecureWord64());
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800149 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700150 Name newIdentityName = m_config.m_caName;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700151 newIdentityName.append(availableId);
Zhiyi Zhang547c8512019-06-18 23:46:14 -0700152 _LOG_TRACE("Handle PROBE: generate an identity " << newIdentityName);
Yufeng Zhang424d0362019-06-12 16:48:27 -0700153 contentJson = genProbeResponseJson(newIdentityName.toUri(), m_config.m_probe, parameterJson);
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800154 }
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800155
156 Data result;
157 result.setName(request.getName());
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700158 result.setContent(dataContentFromJson(contentJson));
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700159 result.setFreshnessPeriod(DEFAULT_DATA_FRESHNESS_PERIOD);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700160 m_keyChain.sign(result, signingByIdentity(m_config.m_caName));
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800161 m_face.put(result);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700162 _LOG_TRACE("Handle PROBE: send out the PROBE response");
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800163}
164
165void
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700166CaModule::onNew(const Interest& request)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800167{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700168 // NEW Naming Convention: /<CA-prefix>/CA/NEW/[SignedInterestParameters_Digest]
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700169 // get ECDH pub key and cert request
170 const auto& parameterJson = jsonFromBlock(request.getApplicationParameters());
Zhiyi Zhang547c8512019-06-18 23:46:14 -0700171 if (parameterJson.empty()) {
172 _LOG_ERROR("Empty JSON obtained from the Interest parameter.");
173 return;
174 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700175 std::string peerKeyBase64 = parameterJson.get(JSON_CLIENT_ECDH, "");
176
177 // get server's ECDH pub key
178 auto myEcdhPubKeyBase64 = m_ecdh.getBase64PubKey();
179 m_ecdh.deriveSecret(peerKeyBase64);
180 // generate salt for HKDF
181 auto saltInt = random::generateSecureWord64();
182 uint8_t salt[sizeof(saltInt)];
183 std::memcpy(salt, &saltInt, sizeof(saltInt));
184 // hkdf
185 hkdf(m_ecdh.context->sharedSecret, m_ecdh.context->sharedSecretLen,
186 salt, sizeof(saltInt), m_aesKey, 32);
187
188 // parse certificate request
189 std::string certRequestStr = parameterJson.get(JSON_CLIENT_CERT_REQ, "");
190 shared_ptr<security::v2::Certificate> clientCert = nullptr;
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800191 try {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700192 std::stringstream ss(certRequestStr);
193 clientCert = io::load<security::v2::Certificate>(ss);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800194 }
195 catch (const std::exception& e) {
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700196 _LOG_ERROR("Unrecognized certificate request " << e.what());
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800197 return;
198 }
Zhiyi Zhang1a735bc2019-07-04 21:36:49 -0700199 // check the validity period
200 auto expectedPeriod = clientCert->getValidityPeriod().getPeriod();
201 auto currentTime = time::system_clock::now();
202 if (expectedPeriod.first < currentTime - REQUEST_VALIDITY_PERIOD_NOT_BEFORE_GRACE_PERIOD) {
203 _LOG_ERROR("Client requests a too old notBefore timepoint.");
204 return;
205 }
206 if (expectedPeriod.second > currentTime + m_config.m_validityPeriod ||
207 expectedPeriod.second <= expectedPeriod.first) {
208 _LOG_ERROR("Client requests an invalid validity period or a notAfter timepoint beyond the allowed time period.");
209 return;
210 }
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700211
Zhiyi Zhang5f749a22019-06-12 17:02:33 -0700212 // parse probe token if any
213 std::string probeTokenStr = parameterJson.get("probe-token", "");
214 shared_ptr<Data> probeToken = nullptr;
215 if (probeTokenStr != "") {
216 try {
217 std::stringstream ss(probeTokenStr);
Zhiyi Zhanga1fc6232019-06-13 14:56:59 -0700218 probeToken = io::load<Data>(ss);
Zhiyi Zhang5f749a22019-06-12 17:02:33 -0700219 }
220 catch (const std::exception& e) {
221 _LOG_ERROR("Unrecognized probe token " << e.what());
222 return;
223 }
224 }
Zhiyi Zhanga1fc6232019-06-13 14:56:59 -0700225 if (probeToken == nullptr && m_config.m_probe != "") {
226 // the CA requires PROBE before NEW
227 _LOG_ERROR("CA requires PROBE but no PROBE token is found in NEW Interest.");
228 return;
229 }
230 else if (probeToken != nullptr) {
231 // check whether the carried probe token is a PROBE Data packet
Zhiyi Zhang5f749a22019-06-12 17:02:33 -0700232 Name prefix = m_config.m_caName;
233 prefix.append("CA").append("_PROBE");
234 if (!prefix.isPrefixOf(probeToken->getName())) {
Zhiyi Zhanga1fc6232019-06-13 14:56:59 -0700235 _LOG_ERROR("Carried PROBE token is not a valid PROBE Data packet.");
Zhiyi Zhang5f749a22019-06-12 17:02:33 -0700236 return;
237 }
238 }
239
240 // verify the self-signed certificate, the request, and the token
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700241 if (!m_config.m_caName.isPrefixOf(clientCert->getName()) // under ca prefix
242 || !security::v2::Certificate::isValidName(clientCert->getName()) // is valid cert name
243 || clientCert->getName().size() != m_config.m_caName.size() + IS_SUBNAME_MIN_OFFSET) {
244 _LOG_ERROR("Invalid self-signed certificate name " << clientCert->getName());
245 return;
246 }
247 if (!security::verifySignature(*clientCert, *clientCert)) {
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700248 _LOG_TRACE("Cert request with bad signature.");
249 return;
250 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700251 if (!security::verifySignature(request, *clientCert)) {
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700252 _LOG_TRACE("Interest with bad signature.");
253 return;
254 }
Zhiyi Zhang5f749a22019-06-12 17:02:33 -0700255 if (probeToken != nullptr) {
256 const auto& pib = m_keyChain.getPib();
257 const auto& key = pib.getIdentity(m_config.m_caName).getDefaultKey();
258 const auto& caCert = key.getDefaultCertificate();
259 if (!security::verifySignature(*probeToken, caCert)) {
Zhiyi Zhanga1fc6232019-06-13 14:56:59 -0700260 _LOG_TRACE("PROBE Token with bad signature.");
Zhiyi Zhang5f749a22019-06-12 17:02:33 -0700261 return;
262 }
263 }
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700264
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700265 // create new request instance
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800266 std::string requestId = std::to_string(random::generateWord64());
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700267 CertificateRequest certRequest(m_config.m_caName, requestId, STATUS_BEFORE_CHALLENGE, *clientCert);
Zhiyi Zhang5f749a22019-06-12 17:02:33 -0700268 if (probeToken != nullptr) {
269 certRequest.setProbeToken(probeToken);
270 }
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800271 try {
272 m_storage->addRequest(certRequest);
273 }
274 catch (const std::exception& e) {
Zhiyi Zhang5f749a22019-06-12 17:02:33 -0700275 _LOG_TRACE("Cannot add new request instance into the storage " << e.what());
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800276 return;
277 }
278
279 Data result;
280 result.setName(request.getName());
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700281 result.setFreshnessPeriod(DEFAULT_DATA_FRESHNESS_PERIOD);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700282 result.setContent(dataContentFromJson(genNewResponseJson(myEcdhPubKeyBase64,
283 std::to_string(saltInt),
284 certRequest,
285 m_config.m_supportedChallenges)));
286 m_keyChain.sign(result, signingByIdentity(m_config.m_caName));
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800287 m_face.put(result);
Zhiyi Zhanga63b7372017-05-17 14:14:34 -0700288
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700289 if (m_config.m_statusUpdateCallback) {
290 m_config.m_statusUpdateCallback(certRequest);
Zhiyi Zhang7420cf52017-12-18 18:59:21 +0800291 }
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800292}
293
294void
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700295CaModule::onChallenge(const Interest& request)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800296{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700297 // get certificate request state
298 CertificateRequest certRequest = getCertificateRequest(request);
299 if (certRequest.m_requestId == "") {
300 // cannot get the request state
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800301 return;
302 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700303 // verify signature
304 if (!security::verifySignature(request, certRequest.m_cert)) {
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700305 _LOG_TRACE("Interest with bad signature.");
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800306 return;
307 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700308 // decrypt the parameters
Zhiyi Zhang65e59982019-09-08 12:07:30 -0700309 auto paramJsonPayload = parseEncBlock(m_aesKey, 32,
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700310 request.getApplicationParameters());
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700311 if (paramJsonPayload.size() == 0) {
312 _LOG_ERROR("Got an empty buffer from content decryption.");
313 return;
314 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700315 std::string paramJsonStr((const char*)paramJsonPayload.data(), paramJsonPayload.size());
316 std::istringstream ss(paramJsonStr);
317 JsonSection paramJson;
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700318 try {
319 boost::property_tree::json_parser::read_json(ss, paramJson);
320 }
321 catch (const std::exception& e) {
322 _LOG_ERROR("Cannot read JSON from decrypted content " << e.what());
323 return;
324 }
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800325
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700326 // load the corresponding challenge module
327 std::string challengeType = paramJson.get<std::string>(JSON_CLIENT_SELECTED_CHALLENGE);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800328 auto challenge = ChallengeModule::createChallengeModule(challengeType);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700329 JsonSection contentJson;
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800330 if (challenge == nullptr) {
331 _LOG_TRACE("Unrecognized challenge type " << challengeType);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700332 certRequest.m_status = STATUS_FAILURE;
333 certRequest.m_challengeStatus = CHALLENGE_STATUS_UNKNOWN_CHALLENGE;
334 contentJson = genChallengeResponseJson(certRequest);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800335 }
Zhiyi Zhanga9bda732017-05-20 22:58:55 -0700336 else {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700337 _LOG_TRACE("CHALLENGE module to be load: " << challengeType);
338 // let challenge module handle the request
339 challenge->handleChallengeRequest(paramJson, certRequest);
340 if (certRequest.m_status == STATUS_FAILURE) {
341 // if challenge failed
342 m_storage->deleteRequest(certRequest.m_requestId);
343 contentJson = genChallengeResponseJson(certRequest);
344 _LOG_TRACE("Challenge failed");
Zhiyi Zhanga9bda732017-05-20 22:58:55 -0700345 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700346 else if (certRequest.m_status == STATUS_PENDING) {
347 // if challenge succeeded
348 auto issuedCert = issueCertificate(certRequest);
349 certRequest.m_cert = issuedCert;
350 certRequest.m_status = STATUS_SUCCESS;
351 try {
352 m_storage->addCertificate(certRequest.m_requestId, issuedCert);
353 m_storage->deleteRequest(certRequest.m_requestId);
354 _LOG_TRACE("New Certificate Issued " << issuedCert.getName());
355 }
356 catch (const std::exception& e) {
357 _LOG_ERROR("Cannot add issued cert and remove the request " << e.what());
358 return;
359 }
360 if (m_config.m_statusUpdateCallback) {
361 m_config.m_statusUpdateCallback(certRequest);
362 }
363 contentJson = genChallengeResponseJson(certRequest);
364 contentJson.add(JSON_CA_CERT_ID, readString(issuedCert.getName().at(-1)));
365 _LOG_TRACE("Challenge succeeded. Certificate has been issued");
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800366 }
367 else {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700368 try {
369 m_storage->updateRequest(certRequest);
370 }
371 catch (const std::exception& e) {
372 _LOG_TRACE("Cannot update request instance " << e.what());
373 return;
374 }
375 contentJson = genChallengeResponseJson(certRequest);
376 _LOG_TRACE("No failure no success. Challenge moves on");
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800377 }
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800378 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700379
380 Data result;
381 result.setName(request.getName());
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700382 result.setFreshnessPeriod(DEFAULT_DATA_FRESHNESS_PERIOD);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700383
384 // encrypt the content
385 std::stringstream ss2;
386 boost::property_tree::write_json(ss2, contentJson);
387 auto payload = ss2.str();
Zhiyi Zhang65e59982019-09-08 12:07:30 -0700388 auto contentBlock = genEncBlock(tlv::Content, m_aesKey, 32,
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700389 (const uint8_t*)payload.c_str(), payload.size());
390 result.setContent(contentBlock);
391 m_keyChain.sign(result, signingByIdentity(m_config.m_caName));
392 m_face.put(result);
393
394 if (m_config.m_statusUpdateCallback) {
395 m_config.m_statusUpdateCallback(certRequest);
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800396 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700397}
398
399void
400CaModule::onDownload(const Interest& request)
401{
402 auto requestId = readString(request.getName().at(-1));
403 security::v2::Certificate signedCert;
404 try {
405 signedCert = m_storage->getCertificate(requestId);
406 }
407 catch (const std::exception& e) {
408 _LOG_ERROR("Cannot read signed cert " << requestId << " from ca database " << e.what());
409 return;
410 }
411 Data result;
412 result.setName(request.getName());
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700413 result.setFreshnessPeriod(DEFAULT_DATA_FRESHNESS_PERIOD);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700414 result.setContent(signedCert.wireEncode());
415 m_keyChain.sign(result, signingByIdentity(m_config.m_caName));
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800416 m_face.put(result);
417}
418
Zhiyi Zhang343cdfb2018-01-17 12:04:28 -0800419security::v2::Certificate
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700420CaModule::issueCertificate(const CertificateRequest& certRequest)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800421{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700422 auto expectedPeriod =
423 certRequest.m_cert.getValidityPeriod().getPeriod();
Zhiyi Zhang1a735bc2019-07-04 21:36:49 -0700424 security::ValidityPeriod period(expectedPeriod.first, expectedPeriod.second);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800425 security::v2::Certificate newCert;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700426
427 Name certName = certRequest.m_cert.getKeyName();
428 certName.append("NDNCERT").append(std::to_string(random::generateSecureWord64()));
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800429 newCert.setName(certName);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700430 newCert.setContent(certRequest.m_cert.getContent());
431 _LOG_TRACE("cert request content " << certRequest.m_cert);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800432 SignatureInfo signatureInfo;
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800433 signatureInfo.setValidityPeriod(period);
Zhiyi Zhangad6cf932017-10-26 16:19:15 -0700434 security::SigningInfo signingInfo(security::SigningInfo::SIGNER_TYPE_ID,
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700435 m_config.m_caName, signatureInfo);
436 newCert.setFreshnessPeriod(m_config.m_freshnessPeriod);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800437
438 m_keyChain.sign(newCert, signingInfo);
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700439 _LOG_TRACE("new cert got signed" << newCert);
Zhiyi Zhang343cdfb2018-01-17 12:04:28 -0800440 return newCert;
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800441}
442
443CertificateRequest
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700444CaModule::getCertificateRequest(const Interest& request)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800445{
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700446 std::string requestId = "";
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800447 CertificateRequest certRequest;
448 try {
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700449 requestId = readString(request.getName().at(m_config.m_caName.size() + 2));
450 _LOG_TRACE("Request Id to query the database " << requestId);
451 }
452 catch (const std::exception& e) {
453 _LOG_ERROR(e.what());
454 }
455 try {
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800456 certRequest = m_storage->getRequest(requestId);
457 }
458 catch (const std::exception& e) {
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700459 _LOG_ERROR(e.what());
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800460 }
461 return certRequest;
462}
463
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700464/**
465 * @brief Generate JSON file to response PROBE insterest
466 *
467 * PROBE response JSON format:
468 * {
Yufeng Zhang424d0362019-06-12 16:48:27 -0700469 * "name": "@p identifier"
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700470 * }
471 */
472const JsonSection
Yufeng Zhang424d0362019-06-12 16:48:27 -0700473CaModule::genProbeResponseJson(const Name& identifier, const std::string& m_probe, const JsonSection& parameterJson)
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700474{
Zhiyi Zhang781a5602019-06-26 19:05:04 -0700475 std::vector<std::string> fields;
476 std::string delimiter = ":";
477 size_t last = 0;
478 size_t next = 0;
479 while ((next = m_probe.find(delimiter, last)) != std::string::npos) {
480 fields.push_back(m_probe.substr(last, next - last));
481 last = next + 1;
482 }
483 fields.push_back(m_probe.substr(last));
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700484 JsonSection root;
Yufeng Zhang424d0362019-06-12 16:48:27 -0700485
486 for (size_t i = 0; i < fields.size(); ++i) {
Zhiyi Zhang781a5602019-06-26 19:05:04 -0700487 root.put(fields.at(i), parameterJson.get(fields.at(i), ""));
Yufeng Zhang424d0362019-06-12 16:48:27 -0700488 }
489
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700490 root.put(JSON_CA_NAME, identifier.toUri());
491 return root;
492}
493
494/**
495 * @brief Generate JSON file to response NEW interest
496 *
497 * Target JSON format:
498 * {
499 * "ecdh-pub": "@p echdPub",
500 * "salt": "@p salt"
501 * "request-id": "@p requestId",
502 * "status": "@p status",
503 * "challenges": [
504 * {
505 * "challenge-id": ""
506 * },
507 * {
508 * "challenge-id": ""
509 * },
510 * ...
511 * ]
512 * }
513 */
514const JsonSection
515CaModule::genProbeResponseJson()
516{
517 JsonSection root;
518 // ca-prefix
519 Name caName = m_config.m_caName;
520 root.put("ca-prefix", caName.toUri());
521
522 // ca-info
523 const auto& pib = m_keyChain.getPib();
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700524 const auto& identity = pib.getIdentity(m_config.m_caName);
525 const auto& cert = identity.getDefaultKey().getDefaultCertificate();
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700526 std::string caInfo = "";
527 if (m_config.m_caInfo == "") {
528 caInfo = "Issued by " + cert.getSignature().getKeyLocator().getName().toUri();
529 }
530 else {
531 caInfo = m_config.m_caInfo;
532 }
533 root.put("ca-info", caInfo);
534
535 // probe
536 root.put("probe", m_config.m_probe);
537
538 // certificate
539 std::stringstream ss;
540 io::save(cert, ss);
541 root.put("certificate", ss.str());
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700542 return root;
543}
544
545const JsonSection
546CaModule::genNewResponseJson(const std::string& ecdhKey, const std::string& salt,
547 const CertificateRequest& request,
548 const std::list<std::string>& challenges)
549{
550 JsonSection root;
551 JsonSection challengesSection;
552 root.put(JSON_CA_ECDH, ecdhKey);
553 root.put(JSON_CA_SALT, salt);
554 root.put(JSON_CA_EQUEST_ID, request.m_requestId);
555 root.put(JSON_CA_STATUS, std::to_string(request.m_status));
556
557 for (const auto& entry : challenges) {
558 JsonSection challenge;
559 challenge.put(JSON_CA_CHALLENGE_ID, entry);
560 challengesSection.push_back(std::make_pair("", challenge));
561 }
562 root.add_child(JSON_CA_CHALLENGES, challengesSection);
563 return root;
564}
565
566const JsonSection
567CaModule::genChallengeResponseJson(const CertificateRequest& request)
568{
569 JsonSection root;
570 JsonSection challengesSection;
571 root.put(JSON_CA_STATUS, request.m_status);
572 root.put(JSON_CHALLENGE_STATUS, request.m_challengeStatus);
573 root.put(JSON_CHALLENGE_REMAINING_TRIES, std::to_string(request.m_remainingTries));
574 root.put(JSON_CHALLENGE_REMAINING_TIME, std::to_string(request.m_remainingTime));
575 return root;
576}
577
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800578void
579CaModule::onRegisterFailed(const std::string& reason)
580{
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700581 _LOG_ERROR("Failed to register prefix in local hub's daemon, REASON: " << reason);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800582}
583
584Block
585CaModule::dataContentFromJson(const JsonSection& jsonSection)
586{
587 std::stringstream ss;
588 boost::property_tree::write_json(ss, jsonSection);
589 return makeStringBlock(ndn::tlv::Content, ss.str());
590}
591
592JsonSection
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700593CaModule::jsonFromBlock(const Block& block)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800594{
595 std::string jsonString;
596 try {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700597 jsonString = encoding::readString(block);
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700598 std::istringstream ss(jsonString);
599 JsonSection json;
600 boost::property_tree::json_parser::read_json(ss, json);
601 return json;
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800602 }
603 catch (const std::exception& e) {
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700604 _LOG_ERROR("Cannot read JSON string from TLV Value " << e.what());
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800605 return JsonSection();
606 }
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800607}
608
609} // namespace ndncert
610} // namespace ndn