blob: c7b42914455b5e0a6ec26346ad588a3af42bf79f [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
309 auto paramJsonPayload = parseEncBlock(m_ecdh.context->sharedSecret,
310 m_ecdh.context->sharedSecretLen,
311 request.getApplicationParameters());
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700312 if (paramJsonPayload.size() == 0) {
313 _LOG_ERROR("Got an empty buffer from content decryption.");
314 return;
315 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700316 std::string paramJsonStr((const char*)paramJsonPayload.data(), paramJsonPayload.size());
317 std::istringstream ss(paramJsonStr);
318 JsonSection paramJson;
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700319 try {
320 boost::property_tree::json_parser::read_json(ss, paramJson);
321 }
322 catch (const std::exception& e) {
323 _LOG_ERROR("Cannot read JSON from decrypted content " << e.what());
324 return;
325 }
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800326
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700327 // load the corresponding challenge module
328 std::string challengeType = paramJson.get<std::string>(JSON_CLIENT_SELECTED_CHALLENGE);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800329 auto challenge = ChallengeModule::createChallengeModule(challengeType);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700330 JsonSection contentJson;
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800331 if (challenge == nullptr) {
332 _LOG_TRACE("Unrecognized challenge type " << challengeType);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700333 certRequest.m_status = STATUS_FAILURE;
334 certRequest.m_challengeStatus = CHALLENGE_STATUS_UNKNOWN_CHALLENGE;
335 contentJson = genChallengeResponseJson(certRequest);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800336 }
Zhiyi Zhanga9bda732017-05-20 22:58:55 -0700337 else {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700338 _LOG_TRACE("CHALLENGE module to be load: " << challengeType);
339 // let challenge module handle the request
340 challenge->handleChallengeRequest(paramJson, certRequest);
341 if (certRequest.m_status == STATUS_FAILURE) {
342 // if challenge failed
343 m_storage->deleteRequest(certRequest.m_requestId);
344 contentJson = genChallengeResponseJson(certRequest);
345 _LOG_TRACE("Challenge failed");
Zhiyi Zhanga9bda732017-05-20 22:58:55 -0700346 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700347 else if (certRequest.m_status == STATUS_PENDING) {
348 // if challenge succeeded
349 auto issuedCert = issueCertificate(certRequest);
350 certRequest.m_cert = issuedCert;
351 certRequest.m_status = STATUS_SUCCESS;
352 try {
353 m_storage->addCertificate(certRequest.m_requestId, issuedCert);
354 m_storage->deleteRequest(certRequest.m_requestId);
355 _LOG_TRACE("New Certificate Issued " << issuedCert.getName());
356 }
357 catch (const std::exception& e) {
358 _LOG_ERROR("Cannot add issued cert and remove the request " << e.what());
359 return;
360 }
361 if (m_config.m_statusUpdateCallback) {
362 m_config.m_statusUpdateCallback(certRequest);
363 }
364 contentJson = genChallengeResponseJson(certRequest);
365 contentJson.add(JSON_CA_CERT_ID, readString(issuedCert.getName().at(-1)));
366 _LOG_TRACE("Challenge succeeded. Certificate has been issued");
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800367 }
368 else {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700369 try {
370 m_storage->updateRequest(certRequest);
371 }
372 catch (const std::exception& e) {
373 _LOG_TRACE("Cannot update request instance " << e.what());
374 return;
375 }
376 contentJson = genChallengeResponseJson(certRequest);
377 _LOG_TRACE("No failure no success. Challenge moves on");
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800378 }
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800379 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700380
381 Data result;
382 result.setName(request.getName());
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700383 result.setFreshnessPeriod(DEFAULT_DATA_FRESHNESS_PERIOD);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700384
385 // encrypt the content
386 std::stringstream ss2;
387 boost::property_tree::write_json(ss2, contentJson);
388 auto payload = ss2.str();
389 auto contentBlock = genEncBlock(tlv::Content, m_ecdh.context->sharedSecret,
390 m_ecdh.context->sharedSecretLen,
391 (const uint8_t*)payload.c_str(), payload.size());
392 result.setContent(contentBlock);
393 m_keyChain.sign(result, signingByIdentity(m_config.m_caName));
394 m_face.put(result);
395
396 if (m_config.m_statusUpdateCallback) {
397 m_config.m_statusUpdateCallback(certRequest);
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800398 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700399}
400
401void
402CaModule::onDownload(const Interest& request)
403{
404 auto requestId = readString(request.getName().at(-1));
405 security::v2::Certificate signedCert;
406 try {
407 signedCert = m_storage->getCertificate(requestId);
408 }
409 catch (const std::exception& e) {
410 _LOG_ERROR("Cannot read signed cert " << requestId << " from ca database " << e.what());
411 return;
412 }
413 Data result;
414 result.setName(request.getName());
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700415 result.setFreshnessPeriod(DEFAULT_DATA_FRESHNESS_PERIOD);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700416 result.setContent(signedCert.wireEncode());
417 m_keyChain.sign(result, signingByIdentity(m_config.m_caName));
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800418 m_face.put(result);
419}
420
Zhiyi Zhang343cdfb2018-01-17 12:04:28 -0800421security::v2::Certificate
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700422CaModule::issueCertificate(const CertificateRequest& certRequest)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800423{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700424 auto expectedPeriod =
425 certRequest.m_cert.getValidityPeriod().getPeriod();
Zhiyi Zhang1a735bc2019-07-04 21:36:49 -0700426 security::ValidityPeriod period(expectedPeriod.first, expectedPeriod.second);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800427 security::v2::Certificate newCert;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700428
429 Name certName = certRequest.m_cert.getKeyName();
430 certName.append("NDNCERT").append(std::to_string(random::generateSecureWord64()));
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800431 newCert.setName(certName);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700432 newCert.setContent(certRequest.m_cert.getContent());
433 _LOG_TRACE("cert request content " << certRequest.m_cert);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800434 SignatureInfo signatureInfo;
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800435 signatureInfo.setValidityPeriod(period);
Zhiyi Zhangad6cf932017-10-26 16:19:15 -0700436 security::SigningInfo signingInfo(security::SigningInfo::SIGNER_TYPE_ID,
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700437 m_config.m_caName, signatureInfo);
438 newCert.setFreshnessPeriod(m_config.m_freshnessPeriod);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800439
440 m_keyChain.sign(newCert, signingInfo);
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700441 _LOG_TRACE("new cert got signed" << newCert);
Zhiyi Zhang343cdfb2018-01-17 12:04:28 -0800442 return newCert;
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800443}
444
445CertificateRequest
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700446CaModule::getCertificateRequest(const Interest& request)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800447{
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700448 std::string requestId = "";
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800449 CertificateRequest certRequest;
450 try {
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700451 requestId = readString(request.getName().at(m_config.m_caName.size() + 2));
452 _LOG_TRACE("Request Id to query the database " << requestId);
453 }
454 catch (const std::exception& e) {
455 _LOG_ERROR(e.what());
456 }
457 try {
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800458 certRequest = m_storage->getRequest(requestId);
459 }
460 catch (const std::exception& e) {
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700461 _LOG_ERROR(e.what());
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800462 }
463 return certRequest;
464}
465
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700466/**
467 * @brief Generate JSON file to response PROBE insterest
468 *
469 * PROBE response JSON format:
470 * {
Yufeng Zhang424d0362019-06-12 16:48:27 -0700471 * "name": "@p identifier"
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700472 * }
473 */
474const JsonSection
Yufeng Zhang424d0362019-06-12 16:48:27 -0700475CaModule::genProbeResponseJson(const Name& identifier, const std::string& m_probe, const JsonSection& parameterJson)
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700476{
Zhiyi Zhang781a5602019-06-26 19:05:04 -0700477 std::vector<std::string> fields;
478 std::string delimiter = ":";
479 size_t last = 0;
480 size_t next = 0;
481 while ((next = m_probe.find(delimiter, last)) != std::string::npos) {
482 fields.push_back(m_probe.substr(last, next - last));
483 last = next + 1;
484 }
485 fields.push_back(m_probe.substr(last));
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700486 JsonSection root;
Yufeng Zhang424d0362019-06-12 16:48:27 -0700487
488 for (size_t i = 0; i < fields.size(); ++i) {
Zhiyi Zhang781a5602019-06-26 19:05:04 -0700489 root.put(fields.at(i), parameterJson.get(fields.at(i), ""));
Yufeng Zhang424d0362019-06-12 16:48:27 -0700490 }
491
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700492 root.put(JSON_CA_NAME, identifier.toUri());
493 return root;
494}
495
496/**
497 * @brief Generate JSON file to response NEW interest
498 *
499 * Target JSON format:
500 * {
501 * "ecdh-pub": "@p echdPub",
502 * "salt": "@p salt"
503 * "request-id": "@p requestId",
504 * "status": "@p status",
505 * "challenges": [
506 * {
507 * "challenge-id": ""
508 * },
509 * {
510 * "challenge-id": ""
511 * },
512 * ...
513 * ]
514 * }
515 */
516const JsonSection
517CaModule::genProbeResponseJson()
518{
519 JsonSection root;
520 // ca-prefix
521 Name caName = m_config.m_caName;
522 root.put("ca-prefix", caName.toUri());
523
524 // ca-info
525 const auto& pib = m_keyChain.getPib();
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700526 const auto& identity = pib.getIdentity(m_config.m_caName);
527 const auto& cert = identity.getDefaultKey().getDefaultCertificate();
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700528 std::string caInfo = "";
529 if (m_config.m_caInfo == "") {
530 caInfo = "Issued by " + cert.getSignature().getKeyLocator().getName().toUri();
531 }
532 else {
533 caInfo = m_config.m_caInfo;
534 }
535 root.put("ca-info", caInfo);
536
537 // probe
538 root.put("probe", m_config.m_probe);
539
540 // certificate
541 std::stringstream ss;
542 io::save(cert, ss);
543 root.put("certificate", ss.str());
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700544 return root;
545}
546
547const JsonSection
548CaModule::genNewResponseJson(const std::string& ecdhKey, const std::string& salt,
549 const CertificateRequest& request,
550 const std::list<std::string>& challenges)
551{
552 JsonSection root;
553 JsonSection challengesSection;
554 root.put(JSON_CA_ECDH, ecdhKey);
555 root.put(JSON_CA_SALT, salt);
556 root.put(JSON_CA_EQUEST_ID, request.m_requestId);
557 root.put(JSON_CA_STATUS, std::to_string(request.m_status));
558
559 for (const auto& entry : challenges) {
560 JsonSection challenge;
561 challenge.put(JSON_CA_CHALLENGE_ID, entry);
562 challengesSection.push_back(std::make_pair("", challenge));
563 }
564 root.add_child(JSON_CA_CHALLENGES, challengesSection);
565 return root;
566}
567
568const JsonSection
569CaModule::genChallengeResponseJson(const CertificateRequest& request)
570{
571 JsonSection root;
572 JsonSection challengesSection;
573 root.put(JSON_CA_STATUS, request.m_status);
574 root.put(JSON_CHALLENGE_STATUS, request.m_challengeStatus);
575 root.put(JSON_CHALLENGE_REMAINING_TRIES, std::to_string(request.m_remainingTries));
576 root.put(JSON_CHALLENGE_REMAINING_TIME, std::to_string(request.m_remainingTime));
577 return root;
578}
579
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800580void
581CaModule::onRegisterFailed(const std::string& reason)
582{
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700583 _LOG_ERROR("Failed to register prefix in local hub's daemon, REASON: " << reason);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800584}
585
586Block
587CaModule::dataContentFromJson(const JsonSection& jsonSection)
588{
589 std::stringstream ss;
590 boost::property_tree::write_json(ss, jsonSection);
591 return makeStringBlock(ndn::tlv::Content, ss.str());
592}
593
594JsonSection
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700595CaModule::jsonFromBlock(const Block& block)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800596{
597 std::string jsonString;
598 try {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700599 jsonString = encoding::readString(block);
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700600 std::istringstream ss(jsonString);
601 JsonSection json;
602 boost::property_tree::json_parser::read_json(ss, json);
603 return json;
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800604 }
605 catch (const std::exception& e) {
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700606 _LOG_ERROR("Cannot read JSON string from TLV Value " << e.what());
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800607 return JsonSection();
608 }
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800609}
610
611} // namespace ndncert
612} // namespace ndn