blob: 22c9d27fcc41fbe9a252e01a6054f879646c2254 [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"
Zhiyi Zhangdbd9d432020-10-07 15:56:27 -070022#include "identity-challenge/challenge-module.hpp"
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -070023#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>
Zhiyi Zhangfbcab842020-10-07 15:17:13 -070036#include <ndn-cxx/metadata-object.hpp>
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -070037
38namespace ndn {
39namespace ndncert {
40
41_LOG_INIT(ndncert.client);
42
43RequesterState::RequesterState(security::v2::KeyChain& keyChain, const CaProfile& caItem, RequestType requestType)
44 : m_caItem(caItem)
45 , m_keyChain(keyChain)
46 , m_type(requestType)
47{
48}
49
50shared_ptr<Interest>
Zhiyi Zhangfbcab842020-10-07 15:17:13 -070051Requester::genCaProfileDiscoveryInterest(const Name& caName)
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -070052{
Zhiyi Zhangfbcab842020-10-07 15:17:13 -070053 Name contentName = caName;
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -070054 if (readString(caName.at(-1)) != "CA")
Zhiyi Zhangfbcab842020-10-07 15:17:13 -070055 contentName.append("CA");
56 contentName.append("INFO");
57 return std::make_shared<Interest>(MetadataObject::makeDiscoveryInterest(contentName));
58}
59
60shared_ptr<Interest>
61Requester::genCaProfileInterestFromDiscoveryResponse(const Data& reply)
62{
63 auto metaData = MetadataObject(reply);
64 auto interestName= metaData.getVersionedName();
65 interestName.appendSegment(0);
66 auto interest = std::make_shared<Interest>(interestName);
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -070067 interest->setCanBePrefix(false);
68 return interest;
69}
70
71boost::optional<CaProfile>
72Requester::onCaProfileResponse(const Data& reply)
73{
74 auto caItem = INFO::decodeDataContent(reply.getContent());
75 if (!security::verifySignature(reply, *caItem.m_cert)) {
76 _LOG_ERROR("Cannot verify replied Data packet signature.");
tylerliu2f5d28f2020-06-23 10:18:15 -070077 BOOST_THROW_EXCEPTION(std::runtime_error("Cannot verify replied Data packet signature."));
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -070078 }
79 return caItem;
80}
81
Zhiyi Zhang837406d2020-10-05 22:01:31 -070082
83boost::optional<CaProfile>
84Requester::onCaProfileResponseAfterRedirection(const Data& reply, const Name& caCertFullName)
85{
86 auto caItem = INFO::decodeDataContent(reply.getContent());
87 auto certBlock = caItem.m_cert->wireEncode();
88 caItem.m_cert = std::make_shared<security::v2::Certificate>(certBlock);
89 if (caItem.m_cert->getFullName() != caCertFullName) {
90 _LOG_ERROR("Ca profile does not match the certificate information offered by the original CA.");
91 BOOST_THROW_EXCEPTION(std::runtime_error("Cannot verify replied Data packet signature."));
92 }
93 return onCaProfileResponse(reply);
94}
95
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -070096shared_ptr<Interest>
97Requester::genProbeInterest(const CaProfile& ca, std::vector<std::tuple<std::string, std::string>>&& probeInfo)
98{
99 Name interestName = ca.m_caPrefix;
100 interestName.append("CA").append("PROBE");
101 auto interest = make_shared<Interest>(interestName);
102 interest->setMustBeFresh(true);
103 interest->setCanBePrefix(false);
104 interest->setApplicationParameters(PROBE::encodeApplicationParameters(std::move(probeInfo)));
105 return interest;
106}
107
108void
109Requester::onProbeResponse(const Data& reply, const CaProfile& ca,
110 std::vector<Name>& identityNames, std::vector<Name>& otherCas)
111{
112 if (!security::verifySignature(reply, *ca.m_cert)) {
113 _LOG_ERROR("Cannot verify replied Data packet signature.");
tylerliu2f5d28f2020-06-23 10:18:15 -0700114 BOOST_THROW_EXCEPTION(std::runtime_error("Cannot verify replied Data packet signature."));
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700115 return;
116 }
117 processIfError(reply);
118 PROBE::decodeDataContent(reply.getContent(), identityNames, otherCas);
119}
120
121shared_ptr<Interest>
122Requester::genNewInterest(RequesterState& state, const Name& identityName,
123 const time::system_clock::TimePoint& notBefore,
124 const time::system_clock::TimePoint& notAfter)
125{
126 if (!state.m_caItem.m_caPrefix.isPrefixOf(identityName)) {
127 return nullptr;
128 }
129 if (identityName.empty()) {
130 NDN_LOG_TRACE("Randomly create a new name because identityName is empty and the param is empty.");
131 state.m_identityName = state.m_caItem.m_caPrefix;
132 state.m_identityName.append(std::to_string(random::generateSecureWord64()));
133 }
134 else {
135 state.m_identityName = identityName;
136 }
137
138 // generate a newly key pair or use an existing key
139 const auto& pib = state.m_keyChain.getPib();
140 security::pib::Identity identity;
141 try {
142 identity = pib.getIdentity(state.m_identityName);
143 }
144 catch (const security::Pib::Error& e) {
145 identity = state.m_keyChain.createIdentity(state.m_identityName);
146 state.m_isNewlyCreatedIdentity = true;
147 state.m_isNewlyCreatedKey = true;
148 }
149 try {
150 state.m_keyPair = identity.getDefaultKey();
151 }
152 catch (const security::Pib::Error& e) {
153 state.m_keyPair = state.m_keyChain.createKey(identity);
154 state.m_isNewlyCreatedKey = true;
155 }
156 auto& keyName = state.m_keyPair.getName();
157
158 // generate certificate request
159 security::v2::Certificate certRequest;
160 certRequest.setName(Name(keyName).append("cert-request").appendVersion());
161 certRequest.setContentType(tlv::ContentType_Key);
162 certRequest.setContent(state.m_keyPair.getPublicKey().data(), state.m_keyPair.getPublicKey().size());
163 SignatureInfo signatureInfo;
164 signatureInfo.setValidityPeriod(security::ValidityPeriod(notBefore, notAfter));
165 state.m_keyChain.sign(certRequest, signingByKey(keyName).setSignatureInfo(signatureInfo));
166
167 // generate Interest packet
168 Name interestName = state.m_caItem.m_caPrefix;
169 interestName.append("CA").append("NEW");
170 auto interest = make_shared<Interest>(interestName);
171 interest->setMustBeFresh(true);
172 interest->setCanBePrefix(false);
173 interest->setApplicationParameters(
174 NEW_RENEW_REVOKE::encodeApplicationParameters(RequestType::NEW, state.m_ecdh.getBase64PubKey(), certRequest));
175
176 // sign the Interest packet
177 state.m_keyChain.sign(*interest, signingByKey(keyName));
178 return interest;
179}
180
181shared_ptr<Interest>
182Requester::genRevokeInterest(RequesterState& state, const security::v2::Certificate& certificate)
183{
184 if (!state.m_caItem.m_caPrefix.isPrefixOf(certificate.getName())) {
185 return nullptr;
186 }
187 // generate Interest packet
188 Name interestName = state.m_caItem.m_caPrefix;
189 interestName.append("CA").append("REVOKE");
190 auto interest = make_shared<Interest>(interestName);
191 interest->setMustBeFresh(true);
192 interest->setCanBePrefix(false);
193 interest->setApplicationParameters(
194 NEW_RENEW_REVOKE::encodeApplicationParameters(RequestType::REVOKE, state.m_ecdh.getBase64PubKey(), certificate));
195 return interest;
196}
197
198std::list<std::string>
199Requester::onNewRenewRevokeResponse(RequesterState& state, const Data& reply)
200{
201 if (!security::verifySignature(reply, *state.m_caItem.m_cert)) {
202 _LOG_ERROR("Cannot verify replied Data packet signature.");
tylerliu2f5d28f2020-06-23 10:18:15 -0700203 BOOST_THROW_EXCEPTION(std::runtime_error("Cannot verify replied Data packet signature."));
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700204 }
205 processIfError(reply);
206
207 auto contentTLV = reply.getContent();
Zhiyi Zhang91f86ab2020-10-05 15:36:35 -0700208 const auto& content = NEW_RENEW_REVOKE::decodeDataContent(contentTLV);
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700209
Zhiyi Zhang91f86ab2020-10-05 15:36:35 -0700210 // ECDH and HKDF
tylerliu0790bdb2020-10-02 00:50:51 -0700211 state.m_ecdh.deriveSecret(content.ecdhKey);
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700212 hkdf(state.m_ecdh.context->sharedSecret, state.m_ecdh.context->sharedSecretLen,
Zhiyi Zhang91f86ab2020-10-05 15:36:35 -0700213 (uint8_t*)&content.salt, sizeof(content.salt), state.m_aesKey, sizeof(state.m_aesKey));
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700214
215 // update state
tylerliu0790bdb2020-10-02 00:50:51 -0700216 state.m_status = content.requestStatus;
217 state.m_requestId = content.requestId;
tylerliu0790bdb2020-10-02 00:50:51 -0700218 return content.challenges;
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700219}
220
221std::vector<std::tuple<std::string, std::string>>
222Requester::selectOrContinueChallenge(RequesterState& state, const std::string& challengeSelected)
223{
224 auto challenge = ChallengeModule::createChallengeModule(challengeSelected);
225 if (challenge == nullptr) {
226 BOOST_THROW_EXCEPTION(std::runtime_error("The challenge selected is not supported by your current version of NDNCERT."));
227 }
228 state.m_challengeType = challengeSelected;
229 return challenge->getRequestedParameterList(state.m_status, state.m_challengeStatus);
230}
231
232shared_ptr<Interest>
233Requester::genChallengeInterest(const RequesterState& state,
234 std::vector<std::tuple<std::string, std::string>>&& parameters)
235{
236 if (state.m_challengeType == "") {
237 BOOST_THROW_EXCEPTION(std::runtime_error("The challenge has not been selected."));
238 }
239 auto challenge = ChallengeModule::createChallengeModule(state.m_challengeType);
240 if (challenge == nullptr) {
241 BOOST_THROW_EXCEPTION(std::runtime_error("The challenge selected is not supported by your current version of NDNCERT."));
242 }
243 auto challengeParams = challenge->genChallengeRequestTLV(state.m_status, state.m_challengeStatus, std::move(parameters));
244
245 Name interestName = state.m_caItem.m_caPrefix;
246 interestName.append("CA").append("CHALLENGE").append(state.m_requestId);
247 auto interest = make_shared<Interest>(interestName);
248 interest->setMustBeFresh(true);
249 interest->setCanBePrefix(false);
250
251 // encrypt the Interest parameters
252 auto paramBlock = encodeBlockWithAesGcm128(tlv::ApplicationParameters, state.m_aesKey,
253 challengeParams.value(), challengeParams.value_size(),
254 (const uint8_t*)"test", strlen("test"));
255 interest->setApplicationParameters(paramBlock);
256 state.m_keyChain.sign(*interest, signingByKey(state.m_keyPair.getName()));
257 return interest;
258}
259
260void
261Requester::onChallengeResponse(RequesterState& state, const Data& reply)
262{
263 if (!security::verifySignature(reply, *state.m_caItem.m_cert)) {
264 _LOG_ERROR("Cannot verify replied Data packet signature.");
tylerliu2f5d28f2020-06-23 10:18:15 -0700265 BOOST_THROW_EXCEPTION(std::runtime_error("Cannot verify replied Data packet signature."));
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700266 }
267 processIfError(reply);
268 auto result = decodeBlockWithAesGcm128(reply.getContent(), state.m_aesKey, (const uint8_t*)"test", strlen("test"));
269 Block contentTLV = makeBinaryBlock(tlv_encrypted_payload, result.data(), result.size());
tylerliu0790bdb2020-10-02 00:50:51 -0700270 auto decoded = CHALLENGE::decodeDataPayload(contentTLV);
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700271
272 // update state
tylerliu0790bdb2020-10-02 00:50:51 -0700273 state.m_status = decoded.status;
274 state.m_challengeStatus = decoded.challengeStatus;
275 state.m_remainingTries = decoded.remainingTries;
276 state.m_freshBefore = time::system_clock::now() + decoded.remainingTime;
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700277
tylerliu0790bdb2020-10-02 00:50:51 -0700278 if (decoded.issuedCertName) {
279 state.m_issuedCertName = *decoded.issuedCertName;
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700280 }
281}
282
283shared_ptr<Interest>
284Requester::genCertFetchInterest(const RequesterState& state)
285{
286 Name interestName = state.m_issuedCertName;
287 auto interest = make_shared<Interest>(interestName);
288 interest->setMustBeFresh(false);
289 interest->setCanBePrefix(false);
290 return interest;
291}
292
293shared_ptr<security::v2::Certificate>
294Requester::onCertFetchResponse(const Data& reply)
295{
296 try {
Zhiyi Zhang837406d2020-10-05 22:01:31 -0700297 return std::make_shared<security::v2::Certificate>(reply);
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700298 }
299 catch (const std::exception& e) {
300 _LOG_ERROR("Cannot parse replied certificate ");
tylerliu2f5d28f2020-06-23 10:18:15 -0700301 BOOST_THROW_EXCEPTION(std::runtime_error("Cannot parse replied certificate "));
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700302 return nullptr;
303 }
304}
305
306void
307Requester::endSession(RequesterState& state)
308{
309 if (state.m_status == Status::SUCCESS || state.m_status == Status::ENDED) {
310 return;
311 }
312 if (state.m_isNewlyCreatedIdentity) {
313 // put the identity into the if scope is because it may cause an error
314 // outside since when endSession is called, identity may not have been created yet.
315 auto identity = state.m_keyChain.getPib().getIdentity(state.m_identityName);
316 state.m_keyChain.deleteIdentity(identity);
317 }
318 else if (state.m_isNewlyCreatedKey) {
319 auto identity = state.m_keyChain.getPib().getIdentity(state.m_identityName);
320 state.m_keyChain.deleteKey(identity, state.m_keyPair);
321 }
322 state.m_status = Status::ENDED;
323}
324
325void
326Requester::processIfError(const Data& data)
327{
328 auto errorInfo = ErrorTLV::decodefromDataContent(data.getContent());
329 if (std::get<0>(errorInfo) == ErrorCode::NO_ERROR) {
330 return;
331 }
tylerliu2f5d28f2020-06-23 10:18:15 -0700332 _LOG_ERROR("Error info replied from the CA with Error code: " +
333 errorCodeToString(std::get<0>(errorInfo)) +
334 " and Error Info: " + std::get<1>(errorInfo));
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700335 BOOST_THROW_EXCEPTION(std::runtime_error("Error info replied from the CA with Error code: " +
336 errorCodeToString(std::get<0>(errorInfo)) +
337 " and Error Info: " + std::get<1>(errorInfo)));
338}
339
340} // namespace ndncert
341} // namespace ndn