Zhiyi Zhang | 1d3dcd2 | 2020-10-01 22:25:43 -0700 | [diff] [blame^] | 1 | /* -*- 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 | |
| 37 | namespace ndn { |
| 38 | namespace ndncert { |
| 39 | |
| 40 | _LOG_INIT(ndncert.client); |
| 41 | |
| 42 | RequesterState::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 | |
| 49 | shared_ptr<Interest> |
| 50 | Requester::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 | |
| 62 | boost::optional<CaProfile> |
| 63 | Requester::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 | |
| 73 | shared_ptr<Interest> |
| 74 | Requester::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 | |
| 85 | void |
| 86 | Requester::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 | |
| 97 | shared_ptr<Interest> |
| 98 | Requester::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 | |
| 157 | shared_ptr<Interest> |
| 158 | Requester::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 | |
| 174 | std::list<std::string> |
| 175 | Requester::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(); |
| 184 | contentTLV.parse(); |
| 185 | |
| 186 | // ECDH |
| 187 | const auto& peerKeyBase64Str = readString(contentTLV.get(tlv_ecdh_pub)); |
| 188 | const auto& saltStr = readString(contentTLV.get(tlv_salt)); |
| 189 | uint64_t saltInt = std::stoull(saltStr); |
| 190 | state.m_ecdh.deriveSecret(peerKeyBase64Str); |
| 191 | |
| 192 | // HKDF |
| 193 | hkdf(state.m_ecdh.context->sharedSecret, state.m_ecdh.context->sharedSecretLen, |
| 194 | (uint8_t*)&saltInt, sizeof(saltInt), state.m_aesKey, sizeof(state.m_aesKey)); |
| 195 | |
| 196 | // update state |
| 197 | state.m_status = static_cast<Status>(readNonNegativeInteger(contentTLV.get(tlv_status))); |
| 198 | state.m_requestId = readString(contentTLV.get(tlv_request_id)); |
| 199 | std::list<std::string> challengeList; |
| 200 | for (auto const& element : contentTLV.elements()) { |
| 201 | if (element.type() == tlv_challenge) { |
| 202 | challengeList.push_back(readString(element)); |
| 203 | } |
| 204 | } |
| 205 | return challengeList; |
| 206 | } |
| 207 | |
| 208 | std::vector<std::tuple<std::string, std::string>> |
| 209 | Requester::selectOrContinueChallenge(RequesterState& state, const std::string& challengeSelected) |
| 210 | { |
| 211 | auto challenge = ChallengeModule::createChallengeModule(challengeSelected); |
| 212 | if (challenge == nullptr) { |
| 213 | BOOST_THROW_EXCEPTION(std::runtime_error("The challenge selected is not supported by your current version of NDNCERT.")); |
| 214 | } |
| 215 | state.m_challengeType = challengeSelected; |
| 216 | return challenge->getRequestedParameterList(state.m_status, state.m_challengeStatus); |
| 217 | } |
| 218 | |
| 219 | shared_ptr<Interest> |
| 220 | Requester::genChallengeInterest(const RequesterState& state, |
| 221 | std::vector<std::tuple<std::string, std::string>>&& parameters) |
| 222 | { |
| 223 | if (state.m_challengeType == "") { |
| 224 | BOOST_THROW_EXCEPTION(std::runtime_error("The challenge has not been selected.")); |
| 225 | } |
| 226 | auto challenge = ChallengeModule::createChallengeModule(state.m_challengeType); |
| 227 | if (challenge == nullptr) { |
| 228 | BOOST_THROW_EXCEPTION(std::runtime_error("The challenge selected is not supported by your current version of NDNCERT.")); |
| 229 | } |
| 230 | auto challengeParams = challenge->genChallengeRequestTLV(state.m_status, state.m_challengeStatus, std::move(parameters)); |
| 231 | |
| 232 | Name interestName = state.m_caItem.m_caPrefix; |
| 233 | interestName.append("CA").append("CHALLENGE").append(state.m_requestId); |
| 234 | auto interest = make_shared<Interest>(interestName); |
| 235 | interest->setMustBeFresh(true); |
| 236 | interest->setCanBePrefix(false); |
| 237 | |
| 238 | // encrypt the Interest parameters |
| 239 | auto paramBlock = encodeBlockWithAesGcm128(tlv::ApplicationParameters, state.m_aesKey, |
| 240 | challengeParams.value(), challengeParams.value_size(), |
| 241 | (const uint8_t*)"test", strlen("test")); |
| 242 | interest->setApplicationParameters(paramBlock); |
| 243 | state.m_keyChain.sign(*interest, signingByKey(state.m_keyPair.getName())); |
| 244 | return interest; |
| 245 | } |
| 246 | |
| 247 | void |
| 248 | Requester::onChallengeResponse(RequesterState& state, const Data& reply) |
| 249 | { |
| 250 | if (!security::verifySignature(reply, *state.m_caItem.m_cert)) { |
| 251 | _LOG_ERROR("Cannot verify replied Data packet signature."); |
| 252 | return; |
| 253 | } |
| 254 | processIfError(reply); |
| 255 | auto result = decodeBlockWithAesGcm128(reply.getContent(), state.m_aesKey, (const uint8_t*)"test", strlen("test")); |
| 256 | Block contentTLV = makeBinaryBlock(tlv_encrypted_payload, result.data(), result.size()); |
| 257 | contentTLV.parse(); |
| 258 | |
| 259 | // update state |
| 260 | state.m_status = static_cast<Status>(readNonNegativeInteger(contentTLV.get(tlv_status))); |
| 261 | state.m_challengeStatus = readString(contentTLV.get(tlv_challenge_status)); |
| 262 | state.m_remainingTries = readNonNegativeInteger(contentTLV.get(tlv_remaining_tries)); |
| 263 | state.m_freshBefore = time::system_clock::now() + |
| 264 | time::seconds(readNonNegativeInteger(contentTLV.get(tlv_remaining_time))); |
| 265 | |
| 266 | if (contentTLV.find(tlv_issued_cert_name) != contentTLV.elements_end()) { |
| 267 | Block issuedCertNameBlock = contentTLV.get(tlv_issued_cert_name); |
| 268 | issuedCertNameBlock.parse(); |
| 269 | state.m_issuedCertName.wireDecode(issuedCertNameBlock.get(tlv::Name)); |
| 270 | } |
| 271 | } |
| 272 | |
| 273 | shared_ptr<Interest> |
| 274 | Requester::genCertFetchInterest(const RequesterState& state) |
| 275 | { |
| 276 | Name interestName = state.m_issuedCertName; |
| 277 | auto interest = make_shared<Interest>(interestName); |
| 278 | interest->setMustBeFresh(false); |
| 279 | interest->setCanBePrefix(false); |
| 280 | return interest; |
| 281 | } |
| 282 | |
| 283 | shared_ptr<security::v2::Certificate> |
| 284 | Requester::onCertFetchResponse(const Data& reply) |
| 285 | { |
| 286 | try { |
| 287 | return std::make_shared<security::v2::Certificate>(reply.getContent().blockFromValue()); |
| 288 | } |
| 289 | catch (const std::exception& e) { |
| 290 | _LOG_ERROR("Cannot parse replied certificate "); |
| 291 | return nullptr; |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | void |
| 296 | Requester::endSession(RequesterState& state) |
| 297 | { |
| 298 | if (state.m_status == Status::SUCCESS || state.m_status == Status::ENDED) { |
| 299 | return; |
| 300 | } |
| 301 | if (state.m_isNewlyCreatedIdentity) { |
| 302 | // put the identity into the if scope is because it may cause an error |
| 303 | // outside since when endSession is called, identity may not have been created yet. |
| 304 | auto identity = state.m_keyChain.getPib().getIdentity(state.m_identityName); |
| 305 | state.m_keyChain.deleteIdentity(identity); |
| 306 | } |
| 307 | else if (state.m_isNewlyCreatedKey) { |
| 308 | auto identity = state.m_keyChain.getPib().getIdentity(state.m_identityName); |
| 309 | state.m_keyChain.deleteKey(identity, state.m_keyPair); |
| 310 | } |
| 311 | state.m_status = Status::ENDED; |
| 312 | } |
| 313 | |
| 314 | void |
| 315 | Requester::processIfError(const Data& data) |
| 316 | { |
| 317 | auto errorInfo = ErrorTLV::decodefromDataContent(data.getContent()); |
| 318 | if (std::get<0>(errorInfo) == ErrorCode::NO_ERROR) { |
| 319 | return; |
| 320 | } |
| 321 | BOOST_THROW_EXCEPTION(std::runtime_error("Error info replied from the CA with Error code: " + |
| 322 | errorCodeToString(std::get<0>(errorInfo)) + |
| 323 | " and Error Info: " + std::get<1>(errorInfo))); |
| 324 | } |
| 325 | |
| 326 | } // namespace ndncert |
| 327 | } // namespace ndn |