blob: d10711476807f5c20e7f0347266b1abe5f3a7658 [file] [log] [blame]
Zhiyi Zhang23564c82017-03-01 10:22:22 -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 Zhang23564c82017-03-01 10:22:22 -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 "client-module.hpp"
22#include "logging.hpp"
Zhiyi Zhanga9bda732017-05-20 22:58:55 -070023#include "challenge-module.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 Zhang23564c82017-03-01 10:22:22 -080026#include <ndn-cxx/security/signing-helpers.hpp>
27#include <ndn-cxx/security/verification-helpers.hpp>
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070028#include <ndn-cxx/util/random.hpp>
29#include <ndn-cxx/security/transform/base64-encode.hpp>
30#include <ndn-cxx/security/transform/buffer-source.hpp>
31#include <ndn-cxx/security/transform/stream-sink.hpp>
Zhiyi Zhang23564c82017-03-01 10:22:22 -080032
33namespace ndn {
34namespace ndncert {
35
36_LOG_INIT(ndncert.client);
37
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070038ClientModule::ClientModule(security::v2::KeyChain& keyChain)
39 : m_keyChain(keyChain)
Zhiyi Zhang23564c82017-03-01 10:22:22 -080040{
41}
42
Davide Pesavento08994782018-01-22 12:13:41 -050043ClientModule::~ClientModule() = default;
44
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070045shared_ptr<Interest>
46ClientModule::generateProbeInfoInterest(const Name& caName)
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +080047{
48 Name interestName = caName;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070049 if (readString(caName.at(-1)) != "CA")
50 interestName.append("CA");
51 interestName.append("_PROBE").append("INFO");
52 auto interest = make_shared<Interest>(interestName);
53 interest->setMustBeFresh(true);
54 interest->setCanBePrefix(false);
55 return interest;
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +080056}
57
58void
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070059ClientModule::onProbeInfoResponse(const Data& reply)
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +080060{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070061 // parse the ca item
62 auto contentJson = getJsonFromData(reply);
63 auto caItem = ClientConfig::extractCaItem(contentJson);
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +080064
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070065 // update the local config
66 bool findItem = false;
67 for (auto& item : m_config.m_caItems) {
68 if (item.m_caName == caItem.m_caName) {
69 findItem = true;
70 item = caItem;
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +080071 }
72 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070073 if (!findItem) {
74 m_config.m_caItems.push_back(caItem);
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +080075 }
Zhiyi Zhang1c0bd372017-12-18 18:32:55 +080076
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070077 // verify the probe Data's sig
78 if (!security::verifySignature(reply, caItem.m_anchor)) {
79 _LOG_ERROR("Cannot verify data signature from " << m_ca.m_caName.toUri());
Zhiyi Zhang23564c82017-03-01 10:22:22 -080080 return;
81 }
82}
83
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070084shared_ptr<Interest>
85ClientModule::generateProbeInterest(const ClientCaItem& ca, const std::string& probeInfo)
Zhiyi Zhang23564c82017-03-01 10:22:22 -080086{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070087 Name interestName = ca.m_caName;
88 interestName.append("CA").append("_PROBE");
89 auto interest = make_shared<Interest>(interestName);
90 interest->setMustBeFresh(true);
91 interest->setCanBePrefix(false);
Yufeng Zhang424d0362019-06-12 16:48:27 -070092 auto paramJson = genProbeRequestJson(ca, probeInfo);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070093 interest->setApplicationParameters(paramFromJson(paramJson));
94
95 // update local state
96 m_ca = ca;
97 return interest;
98}
99
100void
101ClientModule::onProbeResponse(const Data& reply)
102{
103 if (!security::verifySignature(reply, m_ca.m_anchor)) {
104 _LOG_ERROR("Cannot verify data signature from " << m_ca.m_caName.toUri());
105 return;
106 }
107 auto contentJson = getJsonFromData(reply);
108
109 // read the available name and put it into the state
110 auto nameUri = contentJson.get<std::string>(JSON_CA_NAME, "");
111 if (nameUri != "") {
112 m_identityName = Name(nameUri);
113 }
114}
115
116shared_ptr<Interest>
117ClientModule::generateNewInterest(const time::system_clock::TimePoint& notBefore,
118 const time::system_clock::TimePoint& notAfter,
Zhiyi Zhang5f749a22019-06-12 17:02:33 -0700119 const Name& identityName, const shared_ptr<Data>& probeToken)
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700120{
121 // Name requestedName = identityName;
122 if (!identityName.empty()) { // if identityName is not empty, find the corresponding CA
123 bool findCa = false;
124 for (const auto& caItem : m_config.m_caItems) {
125 if (caItem.m_caName.isPrefixOf(identityName)) {
126 m_ca = caItem;
127 findCa = true;
128 }
129 }
130 if (!findCa) { // if cannot find, cannot proceed
131 return nullptr;
132 }
133 m_identityName = identityName;
134 }
135 else { // if identityName is empty, check m_identityName or generate a random name
136 if (!m_identityName.empty()) {
137 // do nothing
138 }
139 else {
140 auto id = std::to_string(random::generateSecureWord64());
141 m_identityName = m_ca.m_caName;
142 m_identityName.append(id);
143 }
144 }
145
146 // generate a newly key pair or use an existing key
Zhiyi Zhang10130782018-02-01 18:28:49 -0800147 const auto& pib = m_keyChain.getPib();
Zhiyi Zhang10130782018-02-01 18:28:49 -0800148 try {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700149 auto identity = pib.getIdentity(m_identityName);
150 m_key = m_keyChain.createKey(identity);
Zhiyi Zhang10130782018-02-01 18:28:49 -0800151 }
152 catch (const security::Pib::Error& e) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700153 auto identity = m_keyChain.createIdentity(m_identityName);
154 m_key = identity.getDefaultKey();
Zhiyi Zhang10130782018-02-01 18:28:49 -0800155 }
Zhiyi Zhang23564c82017-03-01 10:22:22 -0800156
157 // generate certificate request
158 security::v2::Certificate certRequest;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700159 certRequest.setName(Name(m_key.getName()).append("cert-request").appendVersion());
Zhiyi Zhang23564c82017-03-01 10:22:22 -0800160 certRequest.setContentType(tlv::ContentType_Key);
161 certRequest.setFreshnessPeriod(time::hours(24));
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700162 certRequest.setContent(m_key.getPublicKey().data(), m_key.getPublicKey().size());
Zhiyi Zhang23564c82017-03-01 10:22:22 -0800163 SignatureInfo signatureInfo;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700164 signatureInfo.setValidityPeriod(security::ValidityPeriod(notBefore, notAfter));
165 m_keyChain.sign(certRequest, signingByKey(m_key.getName()).setSignatureInfo(signatureInfo));
Zhiyi Zhang23564c82017-03-01 10:22:22 -0800166
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700167 // generate Interest packet
168 Name interestName = m_ca.m_caName;
169 interestName.append("CA").append("_NEW");
170 auto interest = make_shared<Interest>(interestName);
171 interest->setMustBeFresh(true);
172 interest->setCanBePrefix(false);
Zhiyi Zhang5f749a22019-06-12 17:02:33 -0700173 interest->setApplicationParameters(paramFromJson(genNewRequestJson(m_ecdh.getBase64PubKey(), certRequest, probeToken)));
Zhiyi Zhang23564c82017-03-01 10:22:22 -0800174
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700175 // sign the Interest packet
176 m_keyChain.sign(*interest, signingByKey(m_key.getName()));
177 return interest;
Zhiyi Zhang23564c82017-03-01 10:22:22 -0800178}
179
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700180std::list<std::string>
181ClientModule::onNewResponse(const Data& reply)
Zhiyi Zhang23564c82017-03-01 10:22:22 -0800182{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700183 if (!security::verifySignature(reply, m_ca.m_anchor)) {
184 _LOG_ERROR("Cannot verify data signature from " << m_ca.m_caName.toUri());
185 return std::list<std::string>();
Zhiyi Zhang23564c82017-03-01 10:22:22 -0800186 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700187 auto contentJson = getJsonFromData(reply);
Zhiyi Zhang23564c82017-03-01 10:22:22 -0800188
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700189 // ECDH
190 const auto& peerKeyBase64Str = contentJson.get<std::string>(JSON_CA_ECDH, "");
191 const auto& saltStr = contentJson.get<std::string>(JSON_CA_SALT, "");
192 uint64_t saltInt = std::stoull(saltStr);
193 uint8_t salt[sizeof(saltInt)];
194 std::memcpy(salt, &saltInt, sizeof(saltInt));
195 m_ecdh.deriveSecret(peerKeyBase64Str);
Zhiyi Zhang23564c82017-03-01 10:22:22 -0800196
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700197 // HKDF
198 hkdf(m_ecdh.context->sharedSecret, m_ecdh.context->sharedSecretLen, salt, sizeof(saltInt), m_aesKey, 32);
Zhiyi Zhang23564c82017-03-01 10:22:22 -0800199
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700200 // update state
201 m_status = contentJson.get<int>(JSON_CA_STATUS);
202 m_requestId = contentJson.get<std::string>(JSON_CA_EQUEST_ID, "");
203
204 auto challengesJson = contentJson.get_child(JSON_CA_CHALLENGES);
205 m_challengeList.clear();
Zhiyi Zhang23564c82017-03-01 10:22:22 -0800206 for (const auto& challengeJson : challengesJson) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700207 m_challengeList.push_back(challengeJson.second.get<std::string>(JSON_CA_CHALLENGE_ID, ""));
Zhiyi Zhang23564c82017-03-01 10:22:22 -0800208 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700209 return m_challengeList;
210}
Zhiyi Zhang23564c82017-03-01 10:22:22 -0800211
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700212shared_ptr<Interest>
213ClientModule::generateChallengeInterest(const JsonSection& paramJson)
214{
215 m_challengeType = paramJson.get<std::string>(JSON_CLIENT_SELECTED_CHALLENGE);
Zhiyi Zhang23564c82017-03-01 10:22:22 -0800216
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700217 Name interestName = m_ca.m_caName;
218 interestName.append("CA").append("_CHALLENGE").append(m_requestId);
219 auto interest = make_shared<Interest>(interestName);
220 interest->setMustBeFresh(true);
221 interest->setCanBePrefix(false);
222
223 // encrypt the Interest parameters
224 std::stringstream ss;
225 boost::property_tree::write_json(ss, paramJson);
226 auto payload = ss.str();
227 auto paramBlock = genEncBlock(tlv::ApplicationParameters, m_ecdh.context->sharedSecret, m_ecdh.context->sharedSecretLen,
228 (const uint8_t*)payload.c_str(), payload.size());
229 interest->setApplicationParameters(paramBlock);
230
231 m_keyChain.sign(*interest, signingByKey(m_key.getName()));
232 return interest;
Zhiyi Zhang23564c82017-03-01 10:22:22 -0800233}
234
235void
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700236ClientModule::onChallengeResponse(const Data& reply)
Zhiyi Zhang23564c82017-03-01 10:22:22 -0800237{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700238 if (!security::verifySignature(reply, m_ca.m_anchor)) {
239 _LOG_ERROR("Cannot verify data signature from " << m_ca.m_caName.toUri());
Zhiyi Zhang23564c82017-03-01 10:22:22 -0800240 return;
241 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700242 auto result = parseEncBlock(m_ecdh.context->sharedSecret, m_ecdh.context->sharedSecretLen, reply.getContent());
243 std::string payload((const char*)result.data(), result.size());
244 std::istringstream ss(payload);
245 JsonSection contentJson;
246 boost::property_tree::json_parser::read_json(ss, contentJson);
Zhiyi Zhang23564c82017-03-01 10:22:22 -0800247
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700248 // update state
249 m_status = contentJson.get<int>(JSON_CA_STATUS);
250 m_challengeStatus = contentJson.get<std::string>(JSON_CHALLENGE_STATUS);
251 m_remainingTries = contentJson.get<int>(JSON_CHALLENGE_REMAINING_TRIES);
252 m_freshBefore = time::system_clock::now() + time::seconds(contentJson.get<int>(JSON_CHALLENGE_REMAINING_TIME));
253}
Zhiyi Zhange30eb352017-04-13 15:26:14 -0700254
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700255shared_ptr<Interest>
256ClientModule::generateDownloadInterest()
257{
258 Name interestName = m_ca.m_caName;
259 interestName.append("CA").append("_DOWNLOAD").append(m_requestId);
260 auto interest = make_shared<Interest>(interestName);
261 interest->setMustBeFresh(true);
262 interest->setCanBePrefix(false);
263 return interest;
264}
Zhiyi Zhange30eb352017-04-13 15:26:14 -0700265
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700266shared_ptr<Interest>
267ClientModule::generateCertFetchInterest()
268{
269 Name interestName = m_identityName;
270 interestName.append("KEY").append(m_certId);
271 auto interest = make_shared<Interest>(interestName);
272 interest->setMustBeFresh(true);
273 interest->setCanBePrefix(false);
274 return interest;
Zhiyi Zhang23564c82017-03-01 10:22:22 -0800275}
276
277void
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700278ClientModule::onDownloadResponse(const Data& reply)
Zhiyi Zhang23564c82017-03-01 10:22:22 -0800279{
Zhiyi Zhang23564c82017-03-01 10:22:22 -0800280 try {
281 security::v2::Certificate cert(reply.getContent().blockFromValue());
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700282 m_keyChain.addCertificate(m_key, cert);
Zhiyi Zhang23564c82017-03-01 10:22:22 -0800283 _LOG_TRACE("Got DOWNLOAD response and installed the cert " << cert.getName());
284 }
285 catch (const std::exception& e) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700286 _LOG_ERROR("Cannot add replied certificate into the keychain " << e.what());
Zhiyi Zhang23564c82017-03-01 10:22:22 -0800287 return;
288 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700289 m_isCertInstalled = true;
Zhiyi Zhang23564c82017-03-01 10:22:22 -0800290}
291
292void
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700293ClientModule::onCertFetchResponse(const Data& reply)
Zhiyi Zhang23564c82017-03-01 10:22:22 -0800294{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700295 onDownloadResponse(reply);
Zhiyi Zhang23564c82017-03-01 10:22:22 -0800296}
297
298JsonSection
299ClientModule::getJsonFromData(const Data& data)
300{
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700301 std::istringstream ss(encoding::readString(data.getContent()));
Zhiyi Zhang23564c82017-03-01 10:22:22 -0800302 JsonSection json;
303 boost::property_tree::json_parser::read_json(ss, json);
304 return json;
305}
306
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700307const JsonSection
Yufeng Zhang424d0362019-06-12 16:48:27 -0700308ClientModule::genProbeRequestJson(const ClientCaItem& ca, const std::string& probeInfo)
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700309{
Yufeng Zhang424d0362019-06-12 16:48:27 -0700310 std::string delimiter = ":";
311 size_t last = 0;
312 size_t next = 0;
313
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700314 JsonSection root;
Yufeng Zhang424d0362019-06-12 16:48:27 -0700315
316 std::vector<std::string> fields;
317 while ((next = ca.m_probe.find(delimiter, last)) != std::string::npos) {
318 fields.push_back(ca.m_probe.substr(last, next - last));
319 last = next + 1;
320 }
321 fields.push_back(ca.m_probe.substr(last));
322
323 std::vector<std::string> arguments;
324 last = 0;
325 next = 0;
326 while ((next = probeInfo.find(delimiter, last)) != std::string::npos) {
327 arguments.push_back(probeInfo.substr(last, next - last));
328 last = next + 1;
329 }
330 arguments.push_back(probeInfo.substr(last));
331
332 if (arguments.size() != fields.size()) {
333 BOOST_THROW_EXCEPTION(Error("Error in genProbeRequestJson: argument list does not match field list in the config file."));
334 }
335
336 for (size_t i = 0; i < fields.size(); ++i) {
337 root.put(fields.at(i), arguments.at(i));
338 }
339
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700340 return root;
341}
342
343const JsonSection
Zhiyi Zhang5f749a22019-06-12 17:02:33 -0700344ClientModule::genNewRequestJson(const std::string& ecdhPub, const security::v2::Certificate& certRequest,
345 const shared_ptr<Data>& probeToken)
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700346{
347 JsonSection root;
348 std::stringstream ss;
349 try {
350 security::transform::bufferSource(certRequest.wireEncode().wire(), certRequest.wireEncode().size())
351 >> security::transform::base64Encode(true)
352 >> security::transform::streamSink(ss);
353 }
354 catch (const security::transform::Error& e) {
355 _LOG_ERROR("Cannot convert self-signed cert into BASE64 string " << e.what());
356 return root;
357 }
358 root.put(JSON_CLIENT_ECDH, ecdhPub);
359 root.put(JSON_CLIENT_CERT_REQ, ss.str());
Zhiyi Zhang5f749a22019-06-12 17:02:33 -0700360 if (probeToken != nullptr) {
361 // clear the stringstream
362 ss.str("");
363 ss.clear();
364 // transform the probe data into a base64 string
365 try {
366 security::transform::bufferSource(probeToken->wireEncode().wire(), probeToken->wireEncode().size())
367 >> security::transform::base64Encode(true)
368 >> security::transform::streamSink(ss);
369 }
370 catch (const security::transform::Error& e) {
371 _LOG_ERROR("Cannot convert self-signed cert into BASE64 string " << e.what());
372 return root;
373 }
374 // add the token into the JSON
375 root.put("probe-token", ss.str());
376 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700377 return root;
378}
379
Zhiyi Zhang23564c82017-03-01 10:22:22 -0800380Block
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700381ClientModule::paramFromJson(const JsonSection& json)
Zhiyi Zhang23564c82017-03-01 10:22:22 -0800382{
383 std::stringstream ss;
384 boost::property_tree::write_json(ss, json);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700385 return makeStringBlock(ndn::tlv::ApplicationParameters, ss.str());
Zhiyi Zhang23564c82017-03-01 10:22:22 -0800386}
387
388} // namespace ndncert
389} // namespace ndn