blob: 165ad9384997c616dcb4569c4bee735235a1c15f [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.");
68 return boost::none;
69 }
70 return caItem;
71}
72
73shared_ptr<Interest>
74Requester::genProbeInterest(const CaProfile& ca, std::vector<std::tuple<std::string, std::string>>&& probeInfo)
75{
76 Name interestName = ca.m_caPrefix;
77 interestName.append("CA").append("PROBE");
78 auto interest = make_shared<Interest>(interestName);
79 interest->setMustBeFresh(true);
80 interest->setCanBePrefix(false);
81 interest->setApplicationParameters(PROBE::encodeApplicationParameters(std::move(probeInfo)));
82 return interest;
83}
84
85void
86Requester::onProbeResponse(const Data& reply, const CaProfile& ca,
87 std::vector<Name>& identityNames, std::vector<Name>& otherCas)
88{
89 if (!security::verifySignature(reply, *ca.m_cert)) {
90 _LOG_ERROR("Cannot verify replied Data packet signature.");
91 return;
92 }
93 processIfError(reply);
94 PROBE::decodeDataContent(reply.getContent(), identityNames, otherCas);
95}
96
97shared_ptr<Interest>
98Requester::genNewInterest(RequesterState& state, const Name& identityName,
99 const time::system_clock::TimePoint& notBefore,
100 const time::system_clock::TimePoint& notAfter)
101{
102 if (!state.m_caItem.m_caPrefix.isPrefixOf(identityName)) {
103 return nullptr;
104 }
105 if (identityName.empty()) {
106 NDN_LOG_TRACE("Randomly create a new name because identityName is empty and the param is empty.");
107 state.m_identityName = state.m_caItem.m_caPrefix;
108 state.m_identityName.append(std::to_string(random::generateSecureWord64()));
109 }
110 else {
111 state.m_identityName = identityName;
112 }
113
114 // generate a newly key pair or use an existing key
115 const auto& pib = state.m_keyChain.getPib();
116 security::pib::Identity identity;
117 try {
118 identity = pib.getIdentity(state.m_identityName);
119 }
120 catch (const security::Pib::Error& e) {
121 identity = state.m_keyChain.createIdentity(state.m_identityName);
122 state.m_isNewlyCreatedIdentity = true;
123 state.m_isNewlyCreatedKey = true;
124 }
125 try {
126 state.m_keyPair = identity.getDefaultKey();
127 }
128 catch (const security::Pib::Error& e) {
129 state.m_keyPair = state.m_keyChain.createKey(identity);
130 state.m_isNewlyCreatedKey = true;
131 }
132 auto& keyName = state.m_keyPair.getName();
133
134 // generate certificate request
135 security::v2::Certificate certRequest;
136 certRequest.setName(Name(keyName).append("cert-request").appendVersion());
137 certRequest.setContentType(tlv::ContentType_Key);
138 certRequest.setContent(state.m_keyPair.getPublicKey().data(), state.m_keyPair.getPublicKey().size());
139 SignatureInfo signatureInfo;
140 signatureInfo.setValidityPeriod(security::ValidityPeriod(notBefore, notAfter));
141 state.m_keyChain.sign(certRequest, signingByKey(keyName).setSignatureInfo(signatureInfo));
142
143 // generate Interest packet
144 Name interestName = state.m_caItem.m_caPrefix;
145 interestName.append("CA").append("NEW");
146 auto interest = make_shared<Interest>(interestName);
147 interest->setMustBeFresh(true);
148 interest->setCanBePrefix(false);
149 interest->setApplicationParameters(
150 NEW_RENEW_REVOKE::encodeApplicationParameters(RequestType::NEW, state.m_ecdh.getBase64PubKey(), certRequest));
151
152 // sign the Interest packet
153 state.m_keyChain.sign(*interest, signingByKey(keyName));
154 return interest;
155}
156
157shared_ptr<Interest>
158Requester::genRevokeInterest(RequesterState& state, const security::v2::Certificate& certificate)
159{
160 if (!state.m_caItem.m_caPrefix.isPrefixOf(certificate.getName())) {
161 return nullptr;
162 }
163 // generate Interest packet
164 Name interestName = state.m_caItem.m_caPrefix;
165 interestName.append("CA").append("REVOKE");
166 auto interest = make_shared<Interest>(interestName);
167 interest->setMustBeFresh(true);
168 interest->setCanBePrefix(false);
169 interest->setApplicationParameters(
170 NEW_RENEW_REVOKE::encodeApplicationParameters(RequestType::REVOKE, state.m_ecdh.getBase64PubKey(), certificate));
171 return interest;
172}
173
174std::list<std::string>
175Requester::onNewRenewRevokeResponse(RequesterState& state, const Data& reply)
176{
177 if (!security::verifySignature(reply, *state.m_caItem.m_cert)) {
178 _LOG_ERROR("Cannot verify replied Data packet signature.");
179 return std::list<std::string>();
180 }
181 processIfError(reply);
182
183 auto contentTLV = reply.getContent();
tylerliu0790bdb2020-10-02 00:50:51 -0700184 const auto content = NEW_RENEW_REVOKE::decodeDataContent(contentTLV);
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700185
186 // ECDH
tylerliu0790bdb2020-10-02 00:50:51 -0700187 uint64_t saltInt = std::stoull(content.salt);
188 state.m_ecdh.deriveSecret(content.ecdhKey);
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700189
190 // HKDF
191 hkdf(state.m_ecdh.context->sharedSecret, state.m_ecdh.context->sharedSecretLen,
192 (uint8_t*)&saltInt, sizeof(saltInt), state.m_aesKey, sizeof(state.m_aesKey));
193
194 // update state
tylerliu0790bdb2020-10-02 00:50:51 -0700195 state.m_status = content.requestStatus;
196 state.m_requestId = content.requestId;
197
198 return content.challenges;
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700199}
200
201std::vector<std::tuple<std::string, std::string>>
202Requester::selectOrContinueChallenge(RequesterState& state, const std::string& challengeSelected)
203{
204 auto challenge = ChallengeModule::createChallengeModule(challengeSelected);
205 if (challenge == nullptr) {
206 BOOST_THROW_EXCEPTION(std::runtime_error("The challenge selected is not supported by your current version of NDNCERT."));
207 }
208 state.m_challengeType = challengeSelected;
209 return challenge->getRequestedParameterList(state.m_status, state.m_challengeStatus);
210}
211
212shared_ptr<Interest>
213Requester::genChallengeInterest(const RequesterState& state,
214 std::vector<std::tuple<std::string, std::string>>&& parameters)
215{
216 if (state.m_challengeType == "") {
217 BOOST_THROW_EXCEPTION(std::runtime_error("The challenge has not been selected."));
218 }
219 auto challenge = ChallengeModule::createChallengeModule(state.m_challengeType);
220 if (challenge == nullptr) {
221 BOOST_THROW_EXCEPTION(std::runtime_error("The challenge selected is not supported by your current version of NDNCERT."));
222 }
223 auto challengeParams = challenge->genChallengeRequestTLV(state.m_status, state.m_challengeStatus, std::move(parameters));
224
225 Name interestName = state.m_caItem.m_caPrefix;
226 interestName.append("CA").append("CHALLENGE").append(state.m_requestId);
227 auto interest = make_shared<Interest>(interestName);
228 interest->setMustBeFresh(true);
229 interest->setCanBePrefix(false);
230
231 // encrypt the Interest parameters
232 auto paramBlock = encodeBlockWithAesGcm128(tlv::ApplicationParameters, state.m_aesKey,
233 challengeParams.value(), challengeParams.value_size(),
234 (const uint8_t*)"test", strlen("test"));
235 interest->setApplicationParameters(paramBlock);
236 state.m_keyChain.sign(*interest, signingByKey(state.m_keyPair.getName()));
237 return interest;
238}
239
240void
241Requester::onChallengeResponse(RequesterState& state, const Data& reply)
242{
243 if (!security::verifySignature(reply, *state.m_caItem.m_cert)) {
244 _LOG_ERROR("Cannot verify replied Data packet signature.");
245 return;
246 }
247 processIfError(reply);
248 auto result = decodeBlockWithAesGcm128(reply.getContent(), state.m_aesKey, (const uint8_t*)"test", strlen("test"));
249 Block contentTLV = makeBinaryBlock(tlv_encrypted_payload, result.data(), result.size());
tylerliu0790bdb2020-10-02 00:50:51 -0700250 auto decoded = CHALLENGE::decodeDataPayload(contentTLV);
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700251
252 // update state
tylerliu0790bdb2020-10-02 00:50:51 -0700253 state.m_status = decoded.status;
254 state.m_challengeStatus = decoded.challengeStatus;
255 state.m_remainingTries = decoded.remainingTries;
256 state.m_freshBefore = time::system_clock::now() + decoded.remainingTime;
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700257
tylerliu0790bdb2020-10-02 00:50:51 -0700258 if (decoded.issuedCertName) {
259 state.m_issuedCertName = *decoded.issuedCertName;
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700260 }
261}
262
263shared_ptr<Interest>
264Requester::genCertFetchInterest(const RequesterState& state)
265{
266 Name interestName = state.m_issuedCertName;
267 auto interest = make_shared<Interest>(interestName);
268 interest->setMustBeFresh(false);
269 interest->setCanBePrefix(false);
270 return interest;
271}
272
273shared_ptr<security::v2::Certificate>
274Requester::onCertFetchResponse(const Data& reply)
275{
276 try {
277 return std::make_shared<security::v2::Certificate>(reply.getContent().blockFromValue());
278 }
279 catch (const std::exception& e) {
280 _LOG_ERROR("Cannot parse replied certificate ");
281 return nullptr;
282 }
283}
284
285void
286Requester::endSession(RequesterState& state)
287{
288 if (state.m_status == Status::SUCCESS || state.m_status == Status::ENDED) {
289 return;
290 }
291 if (state.m_isNewlyCreatedIdentity) {
292 // put the identity into the if scope is because it may cause an error
293 // outside since when endSession is called, identity may not have been created yet.
294 auto identity = state.m_keyChain.getPib().getIdentity(state.m_identityName);
295 state.m_keyChain.deleteIdentity(identity);
296 }
297 else if (state.m_isNewlyCreatedKey) {
298 auto identity = state.m_keyChain.getPib().getIdentity(state.m_identityName);
299 state.m_keyChain.deleteKey(identity, state.m_keyPair);
300 }
301 state.m_status = Status::ENDED;
302}
303
304void
305Requester::processIfError(const Data& data)
306{
307 auto errorInfo = ErrorTLV::decodefromDataContent(data.getContent());
308 if (std::get<0>(errorInfo) == ErrorCode::NO_ERROR) {
309 return;
310 }
311 BOOST_THROW_EXCEPTION(std::runtime_error("Error info replied from the CA with Error code: " +
312 errorCodeToString(std::get<0>(errorInfo)) +
313 " and Error Info: " + std::get<1>(errorInfo)));
314}
315
316} // namespace ndncert
317} // namespace ndn