blob: 403736b51f9dd6ee4e2efe76fda6d46adb3143d0 [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 return std::list<std::string>();
183 }
184 processIfError(reply);
185
186 auto contentTLV = reply.getContent();
tylerliu0790bdb2020-10-02 00:50:51 -0700187 const auto content = NEW_RENEW_REVOKE::decodeDataContent(contentTLV);
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700188
189 // ECDH
tylerliu0790bdb2020-10-02 00:50:51 -0700190 uint64_t saltInt = std::stoull(content.salt);
191 state.m_ecdh.deriveSecret(content.ecdhKey);
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700192
193 // HKDF
194 hkdf(state.m_ecdh.context->sharedSecret, state.m_ecdh.context->sharedSecretLen,
195 (uint8_t*)&saltInt, sizeof(saltInt), state.m_aesKey, sizeof(state.m_aesKey));
196
197 // update state
tylerliu0790bdb2020-10-02 00:50:51 -0700198 state.m_status = content.requestStatus;
199 state.m_requestId = content.requestId;
200
201 return content.challenges;
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700202}
203
204std::vector<std::tuple<std::string, std::string>>
205Requester::selectOrContinueChallenge(RequesterState& state, const std::string& challengeSelected)
206{
207 auto challenge = ChallengeModule::createChallengeModule(challengeSelected);
208 if (challenge == nullptr) {
209 BOOST_THROW_EXCEPTION(std::runtime_error("The challenge selected is not supported by your current version of NDNCERT."));
210 }
211 state.m_challengeType = challengeSelected;
212 return challenge->getRequestedParameterList(state.m_status, state.m_challengeStatus);
213}
214
215shared_ptr<Interest>
216Requester::genChallengeInterest(const RequesterState& state,
217 std::vector<std::tuple<std::string, std::string>>&& parameters)
218{
219 if (state.m_challengeType == "") {
220 BOOST_THROW_EXCEPTION(std::runtime_error("The challenge has not been selected."));
221 }
222 auto challenge = ChallengeModule::createChallengeModule(state.m_challengeType);
223 if (challenge == nullptr) {
224 BOOST_THROW_EXCEPTION(std::runtime_error("The challenge selected is not supported by your current version of NDNCERT."));
225 }
226 auto challengeParams = challenge->genChallengeRequestTLV(state.m_status, state.m_challengeStatus, std::move(parameters));
227
228 Name interestName = state.m_caItem.m_caPrefix;
229 interestName.append("CA").append("CHALLENGE").append(state.m_requestId);
230 auto interest = make_shared<Interest>(interestName);
231 interest->setMustBeFresh(true);
232 interest->setCanBePrefix(false);
233
234 // encrypt the Interest parameters
235 auto paramBlock = encodeBlockWithAesGcm128(tlv::ApplicationParameters, state.m_aesKey,
236 challengeParams.value(), challengeParams.value_size(),
237 (const uint8_t*)"test", strlen("test"));
238 interest->setApplicationParameters(paramBlock);
239 state.m_keyChain.sign(*interest, signingByKey(state.m_keyPair.getName()));
240 return interest;
241}
242
243void
244Requester::onChallengeResponse(RequesterState& state, const Data& reply)
245{
246 if (!security::verifySignature(reply, *state.m_caItem.m_cert)) {
247 _LOG_ERROR("Cannot verify replied Data packet signature.");
tylerliu2f5d28f2020-06-23 10:18:15 -0700248 BOOST_THROW_EXCEPTION(std::runtime_error("Cannot verify replied Data packet signature."));
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700249 return;
250 }
251 processIfError(reply);
252 auto result = decodeBlockWithAesGcm128(reply.getContent(), state.m_aesKey, (const uint8_t*)"test", strlen("test"));
253 Block contentTLV = makeBinaryBlock(tlv_encrypted_payload, result.data(), result.size());
tylerliu0790bdb2020-10-02 00:50:51 -0700254 auto decoded = CHALLENGE::decodeDataPayload(contentTLV);
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700255
256 // update state
tylerliu0790bdb2020-10-02 00:50:51 -0700257 state.m_status = decoded.status;
258 state.m_challengeStatus = decoded.challengeStatus;
259 state.m_remainingTries = decoded.remainingTries;
260 state.m_freshBefore = time::system_clock::now() + decoded.remainingTime;
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700261
tylerliu0790bdb2020-10-02 00:50:51 -0700262 if (decoded.issuedCertName) {
263 state.m_issuedCertName = *decoded.issuedCertName;
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700264 }
265}
266
267shared_ptr<Interest>
268Requester::genCertFetchInterest(const RequesterState& state)
269{
270 Name interestName = state.m_issuedCertName;
271 auto interest = make_shared<Interest>(interestName);
272 interest->setMustBeFresh(false);
273 interest->setCanBePrefix(false);
274 return interest;
275}
276
277shared_ptr<security::v2::Certificate>
278Requester::onCertFetchResponse(const Data& reply)
279{
280 try {
281 return std::make_shared<security::v2::Certificate>(reply.getContent().blockFromValue());
282 }
283 catch (const std::exception& e) {
284 _LOG_ERROR("Cannot parse replied certificate ");
tylerliu2f5d28f2020-06-23 10:18:15 -0700285 BOOST_THROW_EXCEPTION(std::runtime_error("Cannot parse replied certificate "));
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700286 return nullptr;
287 }
288}
289
290void
291Requester::endSession(RequesterState& state)
292{
293 if (state.m_status == Status::SUCCESS || state.m_status == Status::ENDED) {
294 return;
295 }
296 if (state.m_isNewlyCreatedIdentity) {
297 // put the identity into the if scope is because it may cause an error
298 // outside since when endSession is called, identity may not have been created yet.
299 auto identity = state.m_keyChain.getPib().getIdentity(state.m_identityName);
300 state.m_keyChain.deleteIdentity(identity);
301 }
302 else if (state.m_isNewlyCreatedKey) {
303 auto identity = state.m_keyChain.getPib().getIdentity(state.m_identityName);
304 state.m_keyChain.deleteKey(identity, state.m_keyPair);
305 }
306 state.m_status = Status::ENDED;
307}
308
309void
310Requester::processIfError(const Data& data)
311{
312 auto errorInfo = ErrorTLV::decodefromDataContent(data.getContent());
313 if (std::get<0>(errorInfo) == ErrorCode::NO_ERROR) {
314 return;
315 }
tylerliu2f5d28f2020-06-23 10:18:15 -0700316 _LOG_ERROR("Error info replied from the CA with Error code: " +
317 errorCodeToString(std::get<0>(errorInfo)) +
318 " and Error Info: " + std::get<1>(errorInfo));
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700319 BOOST_THROW_EXCEPTION(std::runtime_error("Error info replied from the CA with Error code: " +
320 errorCodeToString(std::get<0>(errorInfo)) +
321 " and Error Info: " + std::get<1>(errorInfo)));
322}
323
324} // namespace ndncert
325} // namespace ndn