blob: 20761e0f834597b1ab8b7b99d89dd315c4183e48 [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) {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700142 _LOG_TRACE("Cannot find PROBE input from PROBE parameters: " << e.what());
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700143 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, "");
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700176 if (peerKeyBase64 == "") {
177 _LOG_ERROR("Empty JSON_CLIENT_ECDH obtained from the Interest parameter.");
178 return;
179 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700180
181 // get server's ECDH pub key
182 auto myEcdhPubKeyBase64 = m_ecdh.getBase64PubKey();
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700183 try {
184 m_ecdh.deriveSecret(peerKeyBase64);
185 }
186 catch (const std::exception& e) {
187 _LOG_ERROR("Cannot derive a shared secret using the provided ECDH key: " << e.what());
188 return;
189 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700190 // generate salt for HKDF
191 auto saltInt = random::generateSecureWord64();
192 uint8_t salt[sizeof(saltInt)];
193 std::memcpy(salt, &saltInt, sizeof(saltInt));
194 // hkdf
195 hkdf(m_ecdh.context->sharedSecret, m_ecdh.context->sharedSecretLen,
196 salt, sizeof(saltInt), m_aesKey, 32);
197
198 // parse certificate request
199 std::string certRequestStr = parameterJson.get(JSON_CLIENT_CERT_REQ, "");
200 shared_ptr<security::v2::Certificate> clientCert = nullptr;
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800201 try {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700202 std::stringstream ss(certRequestStr);
203 clientCert = io::load<security::v2::Certificate>(ss);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800204 }
205 catch (const std::exception& e) {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700206 _LOG_ERROR("Unrecognized certificate request: " << e.what());
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800207 return;
208 }
Zhiyi Zhang1a735bc2019-07-04 21:36:49 -0700209 // check the validity period
210 auto expectedPeriod = clientCert->getValidityPeriod().getPeriod();
211 auto currentTime = time::system_clock::now();
212 if (expectedPeriod.first < currentTime - REQUEST_VALIDITY_PERIOD_NOT_BEFORE_GRACE_PERIOD) {
213 _LOG_ERROR("Client requests a too old notBefore timepoint.");
214 return;
215 }
216 if (expectedPeriod.second > currentTime + m_config.m_validityPeriod ||
217 expectedPeriod.second <= expectedPeriod.first) {
218 _LOG_ERROR("Client requests an invalid validity period or a notAfter timepoint beyond the allowed time period.");
219 return;
220 }
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700221
Zhiyi Zhang5f749a22019-06-12 17:02:33 -0700222 // parse probe token if any
223 std::string probeTokenStr = parameterJson.get("probe-token", "");
224 shared_ptr<Data> probeToken = nullptr;
225 if (probeTokenStr != "") {
226 try {
227 std::stringstream ss(probeTokenStr);
Zhiyi Zhanga1fc6232019-06-13 14:56:59 -0700228 probeToken = io::load<Data>(ss);
Zhiyi Zhang5f749a22019-06-12 17:02:33 -0700229 }
230 catch (const std::exception& e) {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700231 _LOG_ERROR("Unrecognized probe token: " << e.what());
Zhiyi Zhang5f749a22019-06-12 17:02:33 -0700232 return;
233 }
234 }
Zhiyi Zhanga1fc6232019-06-13 14:56:59 -0700235 if (probeToken == nullptr && m_config.m_probe != "") {
236 // the CA requires PROBE before NEW
237 _LOG_ERROR("CA requires PROBE but no PROBE token is found in NEW Interest.");
238 return;
239 }
240 else if (probeToken != nullptr) {
241 // check whether the carried probe token is a PROBE Data packet
Zhiyi Zhang5f749a22019-06-12 17:02:33 -0700242 Name prefix = m_config.m_caName;
243 prefix.append("CA").append("_PROBE");
244 if (!prefix.isPrefixOf(probeToken->getName())) {
Zhiyi Zhanga1fc6232019-06-13 14:56:59 -0700245 _LOG_ERROR("Carried PROBE token is not a valid PROBE Data packet.");
Zhiyi Zhang5f749a22019-06-12 17:02:33 -0700246 return;
247 }
248 }
249
250 // verify the self-signed certificate, the request, and the token
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700251 if (!m_config.m_caName.isPrefixOf(clientCert->getName()) // under ca prefix
252 || !security::v2::Certificate::isValidName(clientCert->getName()) // is valid cert name
253 || clientCert->getName().size() != m_config.m_caName.size() + IS_SUBNAME_MIN_OFFSET) {
254 _LOG_ERROR("Invalid self-signed certificate name " << clientCert->getName());
255 return;
256 }
257 if (!security::verifySignature(*clientCert, *clientCert)) {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700258 _LOG_ERROR("Cert request with bad signature.");
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700259 return;
260 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700261 if (!security::verifySignature(request, *clientCert)) {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700262 _LOG_ERROR("Interest with bad signature.");
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700263 return;
264 }
Zhiyi Zhang5f749a22019-06-12 17:02:33 -0700265 if (probeToken != nullptr) {
266 const auto& pib = m_keyChain.getPib();
267 const auto& key = pib.getIdentity(m_config.m_caName).getDefaultKey();
268 const auto& caCert = key.getDefaultCertificate();
269 if (!security::verifySignature(*probeToken, caCert)) {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700270 _LOG_ERROR("PROBE Token with bad signature.");
Zhiyi Zhang5f749a22019-06-12 17:02:33 -0700271 return;
272 }
273 }
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700274
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700275 // create new request instance
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800276 std::string requestId = std::to_string(random::generateWord64());
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700277 CertificateRequest certRequest(m_config.m_caName, requestId, STATUS_BEFORE_CHALLENGE, *clientCert);
Zhiyi Zhang5f749a22019-06-12 17:02:33 -0700278 if (probeToken != nullptr) {
279 certRequest.setProbeToken(probeToken);
280 }
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800281 try {
282 m_storage->addRequest(certRequest);
283 }
284 catch (const std::exception& e) {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700285 _LOG_ERROR("Cannot add new request instance into the storage: " << e.what());
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800286 return;
287 }
288
289 Data result;
290 result.setName(request.getName());
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700291 result.setFreshnessPeriod(DEFAULT_DATA_FRESHNESS_PERIOD);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700292 result.setContent(dataContentFromJson(genNewResponseJson(myEcdhPubKeyBase64,
293 std::to_string(saltInt),
294 certRequest,
295 m_config.m_supportedChallenges)));
296 m_keyChain.sign(result, signingByIdentity(m_config.m_caName));
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800297 m_face.put(result);
Zhiyi Zhanga63b7372017-05-17 14:14:34 -0700298
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700299 if (m_config.m_statusUpdateCallback) {
300 m_config.m_statusUpdateCallback(certRequest);
Zhiyi Zhang7420cf52017-12-18 18:59:21 +0800301 }
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800302}
303
304void
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700305CaModule::onChallenge(const Interest& request)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800306{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700307 // get certificate request state
308 CertificateRequest certRequest = getCertificateRequest(request);
309 if (certRequest.m_requestId == "") {
310 // cannot get the request state
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700311 _LOG_ERROR("Cannot find certificate request state from CA's storage.");
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800312 return;
313 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700314 // verify signature
315 if (!security::verifySignature(request, certRequest.m_cert)) {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700316 _LOG_ERROR("Challenge Interest with bad signature.");
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800317 return;
318 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700319 // decrypt the parameters
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700320 Buffer paramJsonPayload;
321 try {
322 paramJsonPayload = parseEncBlock(m_aesKey, 32,
323 request.getApplicationParameters());
324 }
325 catch (const std::exception& e) {
326 _LOG_ERROR("Cannot successfully decrypt the Interest parameters: " << e.what());
327 return;
328 }
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700329 if (paramJsonPayload.size() == 0) {
330 _LOG_ERROR("Got an empty buffer from content decryption.");
331 return;
332 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700333 std::string paramJsonStr((const char*)paramJsonPayload.data(), paramJsonPayload.size());
334 std::istringstream ss(paramJsonStr);
335 JsonSection paramJson;
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700336 try {
337 boost::property_tree::json_parser::read_json(ss, paramJson);
338 }
339 catch (const std::exception& e) {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700340 _LOG_ERROR("Cannot read JSON from decrypted content: " << e.what());
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700341 return;
342 }
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800343
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700344 // load the corresponding challenge module
345 std::string challengeType = paramJson.get<std::string>(JSON_CLIENT_SELECTED_CHALLENGE);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800346 auto challenge = ChallengeModule::createChallengeModule(challengeType);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700347 JsonSection contentJson;
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800348 if (challenge == nullptr) {
349 _LOG_TRACE("Unrecognized challenge type " << challengeType);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700350 certRequest.m_status = STATUS_FAILURE;
351 certRequest.m_challengeStatus = CHALLENGE_STATUS_UNKNOWN_CHALLENGE;
352 contentJson = genChallengeResponseJson(certRequest);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800353 }
Zhiyi Zhanga9bda732017-05-20 22:58:55 -0700354 else {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700355 _LOG_TRACE("CHALLENGE module to be load: " << challengeType);
356 // let challenge module handle the request
357 challenge->handleChallengeRequest(paramJson, certRequest);
358 if (certRequest.m_status == STATUS_FAILURE) {
359 // if challenge failed
360 m_storage->deleteRequest(certRequest.m_requestId);
361 contentJson = genChallengeResponseJson(certRequest);
362 _LOG_TRACE("Challenge failed");
Zhiyi Zhanga9bda732017-05-20 22:58:55 -0700363 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700364 else if (certRequest.m_status == STATUS_PENDING) {
365 // if challenge succeeded
366 auto issuedCert = issueCertificate(certRequest);
367 certRequest.m_cert = issuedCert;
368 certRequest.m_status = STATUS_SUCCESS;
369 try {
370 m_storage->addCertificate(certRequest.m_requestId, issuedCert);
371 m_storage->deleteRequest(certRequest.m_requestId);
372 _LOG_TRACE("New Certificate Issued " << issuedCert.getName());
373 }
374 catch (const std::exception& e) {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700375 _LOG_ERROR("Cannot add issued cert and remove the request: " << e.what());
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700376 return;
377 }
378 if (m_config.m_statusUpdateCallback) {
379 m_config.m_statusUpdateCallback(certRequest);
380 }
381 contentJson = genChallengeResponseJson(certRequest);
382 contentJson.add(JSON_CA_CERT_ID, readString(issuedCert.getName().at(-1)));
383 _LOG_TRACE("Challenge succeeded. Certificate has been issued");
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800384 }
385 else {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700386 try {
387 m_storage->updateRequest(certRequest);
388 }
389 catch (const std::exception& e) {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700390 _LOG_TRACE("Cannot update request instance: " << e.what());
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700391 return;
392 }
393 contentJson = genChallengeResponseJson(certRequest);
394 _LOG_TRACE("No failure no success. Challenge moves on");
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800395 }
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800396 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700397
398 Data result;
399 result.setName(request.getName());
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700400 result.setFreshnessPeriod(DEFAULT_DATA_FRESHNESS_PERIOD);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700401
402 // encrypt the content
403 std::stringstream ss2;
404 boost::property_tree::write_json(ss2, contentJson);
405 auto payload = ss2.str();
Zhiyi Zhang65e59982019-09-08 12:07:30 -0700406 auto contentBlock = genEncBlock(tlv::Content, m_aesKey, 32,
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700407 (const uint8_t*)payload.c_str(), payload.size());
408 result.setContent(contentBlock);
409 m_keyChain.sign(result, signingByIdentity(m_config.m_caName));
410 m_face.put(result);
411
412 if (m_config.m_statusUpdateCallback) {
413 m_config.m_statusUpdateCallback(certRequest);
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +0800414 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700415}
416
417void
418CaModule::onDownload(const Interest& request)
419{
420 auto requestId = readString(request.getName().at(-1));
421 security::v2::Certificate signedCert;
422 try {
423 signedCert = m_storage->getCertificate(requestId);
424 }
425 catch (const std::exception& e) {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700426 _LOG_ERROR("Cannot read signed cert " << requestId << " from CA's storage: " << e.what());
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700427 return;
428 }
429 Data result;
430 result.setName(request.getName());
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700431 result.setFreshnessPeriod(DEFAULT_DATA_FRESHNESS_PERIOD);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700432 result.setContent(signedCert.wireEncode());
433 m_keyChain.sign(result, signingByIdentity(m_config.m_caName));
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800434 m_face.put(result);
435}
436
Zhiyi Zhang343cdfb2018-01-17 12:04:28 -0800437security::v2::Certificate
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700438CaModule::issueCertificate(const CertificateRequest& certRequest)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800439{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700440 auto expectedPeriod =
441 certRequest.m_cert.getValidityPeriod().getPeriod();
Zhiyi Zhang1a735bc2019-07-04 21:36:49 -0700442 security::ValidityPeriod period(expectedPeriod.first, expectedPeriod.second);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800443 security::v2::Certificate newCert;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700444
445 Name certName = certRequest.m_cert.getKeyName();
446 certName.append("NDNCERT").append(std::to_string(random::generateSecureWord64()));
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800447 newCert.setName(certName);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700448 newCert.setContent(certRequest.m_cert.getContent());
449 _LOG_TRACE("cert request content " << certRequest.m_cert);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800450 SignatureInfo signatureInfo;
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800451 signatureInfo.setValidityPeriod(period);
Zhiyi Zhangad6cf932017-10-26 16:19:15 -0700452 security::SigningInfo signingInfo(security::SigningInfo::SIGNER_TYPE_ID,
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700453 m_config.m_caName, signatureInfo);
454 newCert.setFreshnessPeriod(m_config.m_freshnessPeriod);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800455
456 m_keyChain.sign(newCert, signingInfo);
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700457 _LOG_TRACE("new cert got signed" << newCert);
Zhiyi Zhang343cdfb2018-01-17 12:04:28 -0800458 return newCert;
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800459}
460
461CertificateRequest
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700462CaModule::getCertificateRequest(const Interest& request)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800463{
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700464 std::string requestId = "";
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800465 CertificateRequest certRequest;
466 try {
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700467 requestId = readString(request.getName().at(m_config.m_caName.size() + 2));
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700468 }
469 catch (const std::exception& e) {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700470 _LOG_ERROR("Cannot read the request ID out from the request: " << e.what());
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700471 }
472 try {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700473 _LOG_TRACE("Request Id to query the database " << requestId);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800474 certRequest = m_storage->getRequest(requestId);
475 }
476 catch (const std::exception& e) {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700477 _LOG_ERROR("Cannot get certificate request record from the storage: " << e.what());
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800478 }
479 return certRequest;
480}
481
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700482/**
483 * @brief Generate JSON file to response PROBE insterest
484 *
485 * PROBE response JSON format:
486 * {
Yufeng Zhang424d0362019-06-12 16:48:27 -0700487 * "name": "@p identifier"
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700488 * }
489 */
490const JsonSection
Yufeng Zhang424d0362019-06-12 16:48:27 -0700491CaModule::genProbeResponseJson(const Name& identifier, const std::string& m_probe, const JsonSection& parameterJson)
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700492{
Zhiyi Zhang781a5602019-06-26 19:05:04 -0700493 std::vector<std::string> fields;
494 std::string delimiter = ":";
495 size_t last = 0;
496 size_t next = 0;
497 while ((next = m_probe.find(delimiter, last)) != std::string::npos) {
498 fields.push_back(m_probe.substr(last, next - last));
499 last = next + 1;
500 }
501 fields.push_back(m_probe.substr(last));
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700502 JsonSection root;
Yufeng Zhang424d0362019-06-12 16:48:27 -0700503
504 for (size_t i = 0; i < fields.size(); ++i) {
Zhiyi Zhang781a5602019-06-26 19:05:04 -0700505 root.put(fields.at(i), parameterJson.get(fields.at(i), ""));
Yufeng Zhang424d0362019-06-12 16:48:27 -0700506 }
507
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700508 root.put(JSON_CA_NAME, identifier.toUri());
509 return root;
510}
511
512/**
513 * @brief Generate JSON file to response NEW interest
514 *
515 * Target JSON format:
516 * {
517 * "ecdh-pub": "@p echdPub",
518 * "salt": "@p salt"
519 * "request-id": "@p requestId",
520 * "status": "@p status",
521 * "challenges": [
522 * {
523 * "challenge-id": ""
524 * },
525 * {
526 * "challenge-id": ""
527 * },
528 * ...
529 * ]
530 * }
531 */
532const JsonSection
533CaModule::genProbeResponseJson()
534{
535 JsonSection root;
536 // ca-prefix
537 Name caName = m_config.m_caName;
538 root.put("ca-prefix", caName.toUri());
539
540 // ca-info
541 const auto& pib = m_keyChain.getPib();
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700542 const auto& identity = pib.getIdentity(m_config.m_caName);
543 const auto& cert = identity.getDefaultKey().getDefaultCertificate();
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700544 std::string caInfo = "";
545 if (m_config.m_caInfo == "") {
546 caInfo = "Issued by " + cert.getSignature().getKeyLocator().getName().toUri();
547 }
548 else {
549 caInfo = m_config.m_caInfo;
550 }
551 root.put("ca-info", caInfo);
552
553 // probe
554 root.put("probe", m_config.m_probe);
555
556 // certificate
557 std::stringstream ss;
558 io::save(cert, ss);
559 root.put("certificate", ss.str());
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700560 return root;
561}
562
563const JsonSection
564CaModule::genNewResponseJson(const std::string& ecdhKey, const std::string& salt,
565 const CertificateRequest& request,
566 const std::list<std::string>& challenges)
567{
568 JsonSection root;
569 JsonSection challengesSection;
570 root.put(JSON_CA_ECDH, ecdhKey);
571 root.put(JSON_CA_SALT, salt);
Zhiyi Zhangff4bcb62019-09-08 12:57:42 -0700572 root.put(JSON_CA_REQUEST_ID, request.m_requestId);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700573 root.put(JSON_CA_STATUS, std::to_string(request.m_status));
574
575 for (const auto& entry : challenges) {
576 JsonSection challenge;
577 challenge.put(JSON_CA_CHALLENGE_ID, entry);
578 challengesSection.push_back(std::make_pair("", challenge));
579 }
580 root.add_child(JSON_CA_CHALLENGES, challengesSection);
581 return root;
582}
583
584const JsonSection
585CaModule::genChallengeResponseJson(const CertificateRequest& request)
586{
587 JsonSection root;
588 JsonSection challengesSection;
589 root.put(JSON_CA_STATUS, request.m_status);
590 root.put(JSON_CHALLENGE_STATUS, request.m_challengeStatus);
591 root.put(JSON_CHALLENGE_REMAINING_TRIES, std::to_string(request.m_remainingTries));
592 root.put(JSON_CHALLENGE_REMAINING_TIME, std::to_string(request.m_remainingTime));
593 return root;
594}
595
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800596void
597CaModule::onRegisterFailed(const std::string& reason)
598{
Zhiyi Zhang693c1272017-05-20 22:58:55 -0700599 _LOG_ERROR("Failed to register prefix in local hub's daemon, REASON: " << reason);
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800600}
601
602Block
603CaModule::dataContentFromJson(const JsonSection& jsonSection)
604{
605 std::stringstream ss;
606 boost::property_tree::write_json(ss, jsonSection);
607 return makeStringBlock(ndn::tlv::Content, ss.str());
608}
609
610JsonSection
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700611CaModule::jsonFromBlock(const Block& block)
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800612{
613 std::string jsonString;
614 try {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700615 jsonString = encoding::readString(block);
Zhiyi Zhang42e1cf32019-06-22 17:11:42 -0700616 std::istringstream ss(jsonString);
617 JsonSection json;
618 boost::property_tree::json_parser::read_json(ss, json);
619 return json;
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800620 }
621 catch (const std::exception& e) {
Zhiyi Zhangbc2d4122019-09-10 12:10:54 -0700622 _LOG_ERROR("Cannot read JSON string from TLV Value: " << e.what());
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800623 return JsonSection();
624 }
Zhiyi Zhangf5246c42017-01-26 09:39:20 -0800625}
626
627} // namespace ndncert
628} // namespace ndn