blob: 4cb4135dfd316f8c989f889d485ab0847368c217 [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
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -070043shared_ptr<Interest>
Zhiyi Zhangfbcab842020-10-07 15:17:13 -070044Requester::genCaProfileDiscoveryInterest(const Name& caName)
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -070045{
Zhiyi Zhangfbcab842020-10-07 15:17:13 -070046 Name contentName = caName;
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -070047 if (readString(caName.at(-1)) != "CA")
Zhiyi Zhangfbcab842020-10-07 15:17:13 -070048 contentName.append("CA");
49 contentName.append("INFO");
50 return std::make_shared<Interest>(MetadataObject::makeDiscoveryInterest(contentName));
51}
52
53shared_ptr<Interest>
54Requester::genCaProfileInterestFromDiscoveryResponse(const Data& reply)
55{
56 auto metaData = MetadataObject(reply);
57 auto interestName= metaData.getVersionedName();
58 interestName.appendSegment(0);
59 auto interest = std::make_shared<Interest>(interestName);
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -070060 interest->setCanBePrefix(false);
61 return interest;
62}
63
64boost::optional<CaProfile>
65Requester::onCaProfileResponse(const Data& reply)
66{
67 auto caItem = INFO::decodeDataContent(reply.getContent());
68 if (!security::verifySignature(reply, *caItem.m_cert)) {
69 _LOG_ERROR("Cannot verify replied Data packet signature.");
tylerliu2f5d28f2020-06-23 10:18:15 -070070 BOOST_THROW_EXCEPTION(std::runtime_error("Cannot verify replied Data packet signature."));
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -070071 }
72 return caItem;
73}
74
Zhiyi Zhang837406d2020-10-05 22:01:31 -070075
76boost::optional<CaProfile>
77Requester::onCaProfileResponseAfterRedirection(const Data& reply, const Name& caCertFullName)
78{
79 auto caItem = INFO::decodeDataContent(reply.getContent());
80 auto certBlock = caItem.m_cert->wireEncode();
tylerliua7bea662020-10-08 18:51:02 -070081 caItem.m_cert = std::make_shared<security::Certificate>(certBlock);
Zhiyi Zhang837406d2020-10-05 22:01:31 -070082 if (caItem.m_cert->getFullName() != caCertFullName) {
83 _LOG_ERROR("Ca profile does not match the certificate information offered by the original CA.");
84 BOOST_THROW_EXCEPTION(std::runtime_error("Cannot verify replied Data packet signature."));
85 }
86 return onCaProfileResponse(reply);
87}
88
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -070089shared_ptr<Interest>
90Requester::genProbeInterest(const CaProfile& ca, std::vector<std::tuple<std::string, std::string>>&& probeInfo)
91{
92 Name interestName = ca.m_caPrefix;
93 interestName.append("CA").append("PROBE");
94 auto interest = make_shared<Interest>(interestName);
95 interest->setMustBeFresh(true);
96 interest->setCanBePrefix(false);
97 interest->setApplicationParameters(PROBE::encodeApplicationParameters(std::move(probeInfo)));
98 return interest;
99}
100
101void
102Requester::onProbeResponse(const Data& reply, const CaProfile& ca,
tylerliub47dad72020-10-08 21:36:55 -0700103 std::vector<std::pair<Name, int>>& identityNames, std::vector<Name>& otherCas)
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700104{
105 if (!security::verifySignature(reply, *ca.m_cert)) {
106 _LOG_ERROR("Cannot verify replied Data packet signature.");
tylerliu2f5d28f2020-06-23 10:18:15 -0700107 BOOST_THROW_EXCEPTION(std::runtime_error("Cannot verify replied Data packet signature."));
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700108 return;
109 }
110 processIfError(reply);
111 PROBE::decodeDataContent(reply.getContent(), identityNames, otherCas);
112}
113
114shared_ptr<Interest>
115Requester::genNewInterest(RequesterState& state, const Name& identityName,
116 const time::system_clock::TimePoint& notBefore,
117 const time::system_clock::TimePoint& notAfter)
118{
119 if (!state.m_caItem.m_caPrefix.isPrefixOf(identityName)) {
120 return nullptr;
121 }
122 if (identityName.empty()) {
123 NDN_LOG_TRACE("Randomly create a new name because identityName is empty and the param is empty.");
124 state.m_identityName = state.m_caItem.m_caPrefix;
125 state.m_identityName.append(std::to_string(random::generateSecureWord64()));
126 }
127 else {
128 state.m_identityName = identityName;
129 }
130
131 // generate a newly key pair or use an existing key
132 const auto& pib = state.m_keyChain.getPib();
133 security::pib::Identity identity;
134 try {
135 identity = pib.getIdentity(state.m_identityName);
136 }
137 catch (const security::Pib::Error& e) {
138 identity = state.m_keyChain.createIdentity(state.m_identityName);
139 state.m_isNewlyCreatedIdentity = true;
140 state.m_isNewlyCreatedKey = true;
141 }
142 try {
143 state.m_keyPair = identity.getDefaultKey();
144 }
145 catch (const security::Pib::Error& e) {
146 state.m_keyPair = state.m_keyChain.createKey(identity);
147 state.m_isNewlyCreatedKey = true;
148 }
149 auto& keyName = state.m_keyPair.getName();
150
151 // generate certificate request
tylerliua7bea662020-10-08 18:51:02 -0700152 security::Certificate certRequest;
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700153 certRequest.setName(Name(keyName).append("cert-request").appendVersion());
154 certRequest.setContentType(tlv::ContentType_Key);
155 certRequest.setContent(state.m_keyPair.getPublicKey().data(), state.m_keyPair.getPublicKey().size());
156 SignatureInfo signatureInfo;
157 signatureInfo.setValidityPeriod(security::ValidityPeriod(notBefore, notAfter));
158 state.m_keyChain.sign(certRequest, signingByKey(keyName).setSignatureInfo(signatureInfo));
159
160 // generate Interest packet
161 Name interestName = state.m_caItem.m_caPrefix;
162 interestName.append("CA").append("NEW");
163 auto interest = make_shared<Interest>(interestName);
164 interest->setMustBeFresh(true);
165 interest->setCanBePrefix(false);
166 interest->setApplicationParameters(
167 NEW_RENEW_REVOKE::encodeApplicationParameters(RequestType::NEW, state.m_ecdh.getBase64PubKey(), certRequest));
168
169 // sign the Interest packet
170 state.m_keyChain.sign(*interest, signingByKey(keyName));
171 return interest;
172}
173
174shared_ptr<Interest>
tylerliua7bea662020-10-08 18:51:02 -0700175Requester::genRevokeInterest(RequesterState& state, const security::Certificate& certificate)
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700176{
177 if (!state.m_caItem.m_caPrefix.isPrefixOf(certificate.getName())) {
178 return nullptr;
179 }
180 // generate Interest packet
181 Name interestName = state.m_caItem.m_caPrefix;
182 interestName.append("CA").append("REVOKE");
183 auto interest = make_shared<Interest>(interestName);
184 interest->setMustBeFresh(true);
185 interest->setCanBePrefix(false);
186 interest->setApplicationParameters(
187 NEW_RENEW_REVOKE::encodeApplicationParameters(RequestType::REVOKE, state.m_ecdh.getBase64PubKey(), certificate));
188 return interest;
189}
190
191std::list<std::string>
192Requester::onNewRenewRevokeResponse(RequesterState& state, const Data& reply)
193{
194 if (!security::verifySignature(reply, *state.m_caItem.m_cert)) {
195 _LOG_ERROR("Cannot verify replied Data packet signature.");
tylerliu2f5d28f2020-06-23 10:18:15 -0700196 BOOST_THROW_EXCEPTION(std::runtime_error("Cannot verify replied Data packet signature."));
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700197 }
198 processIfError(reply);
199
200 auto contentTLV = reply.getContent();
Zhiyi Zhang91f86ab2020-10-05 15:36:35 -0700201 const auto& content = NEW_RENEW_REVOKE::decodeDataContent(contentTLV);
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700202
Zhiyi Zhang91f86ab2020-10-05 15:36:35 -0700203 // ECDH and HKDF
tylerliu0790bdb2020-10-02 00:50:51 -0700204 state.m_ecdh.deriveSecret(content.ecdhKey);
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700205 hkdf(state.m_ecdh.context->sharedSecret, state.m_ecdh.context->sharedSecretLen,
Zhiyi Zhang91f86ab2020-10-05 15:36:35 -0700206 (uint8_t*)&content.salt, sizeof(content.salt), state.m_aesKey, sizeof(state.m_aesKey));
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700207
208 // update state
tylerliu0790bdb2020-10-02 00:50:51 -0700209 state.m_status = content.requestStatus;
210 state.m_requestId = content.requestId;
tylerliu0790bdb2020-10-02 00:50:51 -0700211 return content.challenges;
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700212}
213
214std::vector<std::tuple<std::string, std::string>>
215Requester::selectOrContinueChallenge(RequesterState& state, const std::string& challengeSelected)
216{
217 auto challenge = ChallengeModule::createChallengeModule(challengeSelected);
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 state.m_challengeType = challengeSelected;
222 return challenge->getRequestedParameterList(state.m_status, state.m_challengeStatus);
223}
224
225shared_ptr<Interest>
226Requester::genChallengeInterest(const RequesterState& state,
227 std::vector<std::tuple<std::string, std::string>>&& parameters)
228{
229 if (state.m_challengeType == "") {
230 BOOST_THROW_EXCEPTION(std::runtime_error("The challenge has not been selected."));
231 }
232 auto challenge = ChallengeModule::createChallengeModule(state.m_challengeType);
233 if (challenge == nullptr) {
234 BOOST_THROW_EXCEPTION(std::runtime_error("The challenge selected is not supported by your current version of NDNCERT."));
235 }
236 auto challengeParams = challenge->genChallengeRequestTLV(state.m_status, state.m_challengeStatus, std::move(parameters));
237
238 Name interestName = state.m_caItem.m_caPrefix;
239 interestName.append("CA").append("CHALLENGE").append(state.m_requestId);
240 auto interest = make_shared<Interest>(interestName);
241 interest->setMustBeFresh(true);
242 interest->setCanBePrefix(false);
243
244 // encrypt the Interest parameters
245 auto paramBlock = encodeBlockWithAesGcm128(tlv::ApplicationParameters, state.m_aesKey,
246 challengeParams.value(), challengeParams.value_size(),
247 (const uint8_t*)"test", strlen("test"));
248 interest->setApplicationParameters(paramBlock);
249 state.m_keyChain.sign(*interest, signingByKey(state.m_keyPair.getName()));
250 return interest;
251}
252
253void
254Requester::onChallengeResponse(RequesterState& state, const Data& reply)
255{
256 if (!security::verifySignature(reply, *state.m_caItem.m_cert)) {
257 _LOG_ERROR("Cannot verify replied Data packet signature.");
tylerliu2f5d28f2020-06-23 10:18:15 -0700258 BOOST_THROW_EXCEPTION(std::runtime_error("Cannot verify replied Data packet signature."));
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700259 }
260 processIfError(reply);
261 auto result = decodeBlockWithAesGcm128(reply.getContent(), state.m_aesKey, (const uint8_t*)"test", strlen("test"));
262 Block contentTLV = makeBinaryBlock(tlv_encrypted_payload, result.data(), result.size());
Zhiyi Zhangf2306f72020-10-09 11:26:05 -0700263 CHALLENGE::decodeDataContent(contentTLV, state);
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700264}
265
266shared_ptr<Interest>
267Requester::genCertFetchInterest(const RequesterState& state)
268{
269 Name interestName = state.m_issuedCertName;
270 auto interest = make_shared<Interest>(interestName);
271 interest->setMustBeFresh(false);
272 interest->setCanBePrefix(false);
273 return interest;
274}
275
tylerliua7bea662020-10-08 18:51:02 -0700276shared_ptr<security::Certificate>
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700277Requester::onCertFetchResponse(const Data& reply)
278{
279 try {
tylerliua7bea662020-10-08 18:51:02 -0700280 return std::make_shared<security::Certificate>(reply);
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700281 }
282 catch (const std::exception& e) {
283 _LOG_ERROR("Cannot parse replied certificate ");
tylerliu2f5d28f2020-06-23 10:18:15 -0700284 BOOST_THROW_EXCEPTION(std::runtime_error("Cannot parse replied certificate "));
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700285 return nullptr;
286 }
287}
288
289void
290Requester::endSession(RequesterState& state)
291{
292 if (state.m_status == Status::SUCCESS || state.m_status == Status::ENDED) {
293 return;
294 }
295 if (state.m_isNewlyCreatedIdentity) {
296 // put the identity into the if scope is because it may cause an error
297 // outside since when endSession is called, identity may not have been created yet.
298 auto identity = state.m_keyChain.getPib().getIdentity(state.m_identityName);
299 state.m_keyChain.deleteIdentity(identity);
300 }
301 else if (state.m_isNewlyCreatedKey) {
302 auto identity = state.m_keyChain.getPib().getIdentity(state.m_identityName);
303 state.m_keyChain.deleteKey(identity, state.m_keyPair);
304 }
305 state.m_status = Status::ENDED;
306}
307
308void
309Requester::processIfError(const Data& data)
310{
311 auto errorInfo = ErrorTLV::decodefromDataContent(data.getContent());
312 if (std::get<0>(errorInfo) == ErrorCode::NO_ERROR) {
313 return;
314 }
tylerliu2f5d28f2020-06-23 10:18:15 -0700315 _LOG_ERROR("Error info replied from the CA with Error code: " +
316 errorCodeToString(std::get<0>(errorInfo)) +
317 " and Error Info: " + std::get<1>(errorInfo));
Zhiyi Zhang1d3dcd22020-10-01 22:25:43 -0700318 BOOST_THROW_EXCEPTION(std::runtime_error("Error info replied from the CA with Error code: " +
319 errorCodeToString(std::get<0>(errorInfo)) +
320 " and Error Info: " + std::get<1>(errorInfo)));
321}
322
Zhiyi Zhange4891b72020-10-10 15:11:57 -0700323} // namespace ndncert
324} // namespace ndn