blob: 7530821fcae7fb8604f093eb335bd3d09fefe3f8 [file] [log] [blame]
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -07001/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2/**
3 * Copyright (c) 2017-2020, Regents of the University of California.
4 *
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 "requester.hpp"
22#include "challenge-module.hpp"
23#include "crypto-support/enc-tlv.hpp"
24#include "protocol-detail/challenge.hpp"
25#include "protocol-detail/error.hpp"
26#include "protocol-detail/info.hpp"
27#include "protocol-detail/new-renew-revoke.hpp"
28#include "protocol-detail/probe.hpp"
29#include <ndn-cxx/security/signing-helpers.hpp>
30#include <ndn-cxx/security/transform/base64-encode.hpp>
31#include <ndn-cxx/security/transform/buffer-source.hpp>
32#include <ndn-cxx/security/transform/stream-sink.hpp>
33#include <ndn-cxx/security/verification-helpers.hpp>
34#include <ndn-cxx/util/io.hpp>
35#include <ndn-cxx/util/random.hpp>
36
37namespace ndn {
38namespace ndncert {
39
40_LOG_INIT(ndncert.client);
41
42RequesterState::RequesterState(security::v2::KeyChain& keyChain, const CaProfile& caItem, RequestType requestType)
43 : m_caItem(caItem)
44 , m_keyChain(keyChain)
45 , m_type(requestType)
46{
47}
48
49shared_ptr<Interest>
50Requester::genCaProfileInterest(const Name& caName)
51{
52 Name interestName = caName;
53 if (readString(caName.at(-1)) != "CA")
54 interestName.append("CA");
55 interestName.append("INFO");
56 auto interest = make_shared<Interest>(interestName);
57 interest->setMustBeFresh(true);
58 interest->setCanBePrefix(false);
59 return interest;
60}
61
62boost::optional<CaProfile>
63Requester::onCaProfileResponse(const Data& reply)
64{
65 auto caItem = INFO::decodeDataContent(reply.getContent());
66 if (!security::verifySignature(reply, *caItem.m_cert)) {
67 _LOG_ERROR("Cannot verify replied Data packet signature.");
tylerliu2f5d28f2020-06-23 10:18:15 -070068 BOOST_THROW_EXCEPTION(std::runtime_error("Cannot verify replied Data packet signature."));
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -070069 return boost::none;
70 }
71 return caItem;
72}
73
74shared_ptr<Interest>
75Requester::genProbeInterest(const CaProfile& ca, std::vector<std::tuple<std::string, std::string>>&& probeInfo)
76{
77 Name interestName = ca.m_caPrefix;
78 interestName.append("CA").append("PROBE");
79 auto interest = make_shared<Interest>(interestName);
80 interest->setMustBeFresh(true);
81 interest->setCanBePrefix(false);
82 interest->setApplicationParameters(PROBE::encodeApplicationParameters(std::move(probeInfo)));
83 return interest;
84}
85
86void
87Requester::onProbeResponse(const Data& reply, const CaProfile& ca,
88 std::vector<Name>& identityNames, std::vector<Name>& otherCas)
89{
90 if (!security::verifySignature(reply, *ca.m_cert)) {
91 _LOG_ERROR("Cannot verify replied Data packet signature.");
tylerliu2f5d28f2020-06-23 10:18:15 -070092 BOOST_THROW_EXCEPTION(std::runtime_error("Cannot verify replied Data packet signature."));
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -070093 return;
94 }
95 processIfError(reply);
96 PROBE::decodeDataContent(reply.getContent(), identityNames, otherCas);
97}
98
99shared_ptr<Interest>
100Requester::genNewInterest(RequesterState& state, const Name& identityName,
101 const time::system_clock::TimePoint& notBefore,
102 const time::system_clock::TimePoint& notAfter)
103{
104 if (!state.m_caItem.m_caPrefix.isPrefixOf(identityName)) {
105 return nullptr;
106 }
107 if (identityName.empty()) {
108 NDN_LOG_TRACE("Randomly create a new name because identityName is empty and the param is empty.");
109 state.m_identityName = state.m_caItem.m_caPrefix;
110 state.m_identityName.append(std::to_string(random::generateSecureWord64()));
111 }
112 else {
113 state.m_identityName = identityName;
114 }
115
116 // generate a newly key pair or use an existing key
117 const auto& pib = state.m_keyChain.getPib();
118 security::pib::Identity identity;
119 try {
120 identity = pib.getIdentity(state.m_identityName);
121 }
122 catch (const security::Pib::Error& e) {
123 identity = state.m_keyChain.createIdentity(state.m_identityName);
124 state.m_isNewlyCreatedIdentity = true;
125 state.m_isNewlyCreatedKey = true;
126 }
127 try {
128 state.m_keyPair = identity.getDefaultKey();
129 }
130 catch (const security::Pib::Error& e) {
131 state.m_keyPair = state.m_keyChain.createKey(identity);
132 state.m_isNewlyCreatedKey = true;
133 }
134 auto& keyName = state.m_keyPair.getName();
135
136 // generate certificate request
137 security::v2::Certificate certRequest;
138 certRequest.setName(Name(keyName).append("cert-request").appendVersion());
139 certRequest.setContentType(tlv::ContentType_Key);
140 certRequest.setContent(state.m_keyPair.getPublicKey().data(), state.m_keyPair.getPublicKey().size());
141 SignatureInfo signatureInfo;
142 signatureInfo.setValidityPeriod(security::ValidityPeriod(notBefore, notAfter));
143 state.m_keyChain.sign(certRequest, signingByKey(keyName).setSignatureInfo(signatureInfo));
144
145 // generate Interest packet
146 Name interestName = state.m_caItem.m_caPrefix;
147 interestName.append("CA").append("NEW");
148 auto interest = make_shared<Interest>(interestName);
149 interest->setMustBeFresh(true);
150 interest->setCanBePrefix(false);
151 interest->setApplicationParameters(
152 NEW_RENEW_REVOKE::encodeApplicationParameters(RequestType::NEW, state.m_ecdh.getBase64PubKey(), certRequest));
153
154 // sign the Interest packet
155 state.m_keyChain.sign(*interest, signingByKey(keyName));
156 return interest;
157}
158
159shared_ptr<Interest>
160Requester::genRevokeInterest(RequesterState& state, const security::v2::Certificate& certificate)
161{
162 if (!state.m_caItem.m_caPrefix.isPrefixOf(certificate.getName())) {
163 return nullptr;
164 }
165 // generate Interest packet
166 Name interestName = state.m_caItem.m_caPrefix;
167 interestName.append("CA").append("REVOKE");
168 auto interest = make_shared<Interest>(interestName);
169 interest->setMustBeFresh(true);
170 interest->setCanBePrefix(false);
171 interest->setApplicationParameters(
172 NEW_RENEW_REVOKE::encodeApplicationParameters(RequestType::REVOKE, state.m_ecdh.getBase64PubKey(), certificate));
173 return interest;
174}
175
176std::list<std::string>
177Requester::onNewRenewRevokeResponse(RequesterState& state, const Data& reply)
178{
179 if (!security::verifySignature(reply, *state.m_caItem.m_cert)) {
180 _LOG_ERROR("Cannot verify replied Data packet signature.");
tylerliu2f5d28f2020-06-23 10:18:15 -0700181 BOOST_THROW_EXCEPTION(std::runtime_error("Cannot verify replied Data packet signature."));
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700182 }
183 processIfError(reply);
184
185 auto contentTLV = reply.getContent();
Zhiyi Zhang91f86ab2020-10-05 15:36:35 -0700186 const auto& content = NEW_RENEW_REVOKE::decodeDataContent(contentTLV);
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700187
Zhiyi Zhang91f86ab2020-10-05 15:36:35 -0700188 // ECDH and HKDF
tylerliu0790bdb2020-10-02 00:50:51 -0700189 state.m_ecdh.deriveSecret(content.ecdhKey);
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700190 hkdf(state.m_ecdh.context->sharedSecret, state.m_ecdh.context->sharedSecretLen,
Zhiyi Zhang91f86ab2020-10-05 15:36:35 -0700191 (uint8_t*)&content.salt, sizeof(content.salt), state.m_aesKey, sizeof(state.m_aesKey));
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700192
193 // update state
tylerliu0790bdb2020-10-02 00:50:51 -0700194 state.m_status = content.requestStatus;
195 state.m_requestId = content.requestId;
tylerliu0790bdb2020-10-02 00:50:51 -0700196 return content.challenges;
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700197}
198
199std::vector<std::tuple<std::string, std::string>>
200Requester::selectOrContinueChallenge(RequesterState& state, const std::string& challengeSelected)
201{
202 auto challenge = ChallengeModule::createChallengeModule(challengeSelected);
203 if (challenge == nullptr) {
204 BOOST_THROW_EXCEPTION(std::runtime_error("The challenge selected is not supported by your current version of NDNCERT."));
205 }
206 state.m_challengeType = challengeSelected;
207 return challenge->getRequestedParameterList(state.m_status, state.m_challengeStatus);
208}
209
210shared_ptr<Interest>
211Requester::genChallengeInterest(const RequesterState& state,
212 std::vector<std::tuple<std::string, std::string>>&& parameters)
213{
214 if (state.m_challengeType == "") {
215 BOOST_THROW_EXCEPTION(std::runtime_error("The challenge has not been selected."));
216 }
217 auto challenge = ChallengeModule::createChallengeModule(state.m_challengeType);
218 if (challenge == nullptr) {
219 BOOST_THROW_EXCEPTION(std::runtime_error("The challenge selected is not supported by your current version of NDNCERT."));
220 }
221 auto challengeParams = challenge->genChallengeRequestTLV(state.m_status, state.m_challengeStatus, std::move(parameters));
222
223 Name interestName = state.m_caItem.m_caPrefix;
224 interestName.append("CA").append("CHALLENGE").append(state.m_requestId);
225 auto interest = make_shared<Interest>(interestName);
226 interest->setMustBeFresh(true);
227 interest->setCanBePrefix(false);
228
229 // encrypt the Interest parameters
230 auto paramBlock = encodeBlockWithAesGcm128(tlv::ApplicationParameters, state.m_aesKey,
231 challengeParams.value(), challengeParams.value_size(),
232 (const uint8_t*)"test", strlen("test"));
233 interest->setApplicationParameters(paramBlock);
234 state.m_keyChain.sign(*interest, signingByKey(state.m_keyPair.getName()));
235 return interest;
236}
237
238void
239Requester::onChallengeResponse(RequesterState& state, const Data& reply)
240{
241 if (!security::verifySignature(reply, *state.m_caItem.m_cert)) {
242 _LOG_ERROR("Cannot verify replied Data packet signature.");
tylerliu2f5d28f2020-06-23 10:18:15 -0700243 BOOST_THROW_EXCEPTION(std::runtime_error("Cannot verify replied Data packet signature."));
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700244 }
245 processIfError(reply);
246 auto result = decodeBlockWithAesGcm128(reply.getContent(), state.m_aesKey, (const uint8_t*)"test", strlen("test"));
247 Block contentTLV = makeBinaryBlock(tlv_encrypted_payload, result.data(), result.size());
tylerliu0790bdb2020-10-02 00:50:51 -0700248 auto decoded = CHALLENGE::decodeDataPayload(contentTLV);
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700249
250 // update state
tylerliu0790bdb2020-10-02 00:50:51 -0700251 state.m_status = decoded.status;
252 state.m_challengeStatus = decoded.challengeStatus;
253 state.m_remainingTries = decoded.remainingTries;
254 state.m_freshBefore = time::system_clock::now() + decoded.remainingTime;
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700255
tylerliu0790bdb2020-10-02 00:50:51 -0700256 if (decoded.issuedCertName) {
257 state.m_issuedCertName = *decoded.issuedCertName;
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700258 }
259}
260
261shared_ptr<Interest>
262Requester::genCertFetchInterest(const RequesterState& state)
263{
264 Name interestName = state.m_issuedCertName;
265 auto interest = make_shared<Interest>(interestName);
266 interest->setMustBeFresh(false);
267 interest->setCanBePrefix(false);
268 return interest;
269}
270
271shared_ptr<security::v2::Certificate>
272Requester::onCertFetchResponse(const Data& reply)
273{
274 try {
275 return std::make_shared<security::v2::Certificate>(reply.getContent().blockFromValue());
276 }
277 catch (const std::exception& e) {
278 _LOG_ERROR("Cannot parse replied certificate ");
tylerliu2f5d28f2020-06-23 10:18:15 -0700279 BOOST_THROW_EXCEPTION(std::runtime_error("Cannot parse replied certificate "));
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700280 return nullptr;
281 }
282}
283
284void
285Requester::endSession(RequesterState& state)
286{
287 if (state.m_status == Status::SUCCESS || state.m_status == Status::ENDED) {
288 return;
289 }
290 if (state.m_isNewlyCreatedIdentity) {
291 // put the identity into the if scope is because it may cause an error
292 // outside since when endSession is called, identity may not have been created yet.
293 auto identity = state.m_keyChain.getPib().getIdentity(state.m_identityName);
294 state.m_keyChain.deleteIdentity(identity);
295 }
296 else if (state.m_isNewlyCreatedKey) {
297 auto identity = state.m_keyChain.getPib().getIdentity(state.m_identityName);
298 state.m_keyChain.deleteKey(identity, state.m_keyPair);
299 }
300 state.m_status = Status::ENDED;
301}
302
303void
304Requester::processIfError(const Data& data)
305{
306 auto errorInfo = ErrorTLV::decodefromDataContent(data.getContent());
307 if (std::get<0>(errorInfo) == ErrorCode::NO_ERROR) {
308 return;
309 }
tylerliu2f5d28f2020-06-23 10:18:15 -0700310 _LOG_ERROR("Error info replied from the CA with Error code: " +
311 errorCodeToString(std::get<0>(errorInfo)) +
312 " and Error Info: " + std::get<1>(errorInfo));
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700313 BOOST_THROW_EXCEPTION(std::runtime_error("Error info replied from the CA with Error code: " +
314 errorCodeToString(std::get<0>(errorInfo)) +
315 " and Error Info: " + std::get<1>(errorInfo)));
316}
317
318} // namespace ndncert
319} // namespace ndn