blob: 163008064c0a7d73b20ac9b74b659812be9a69c7 [file] [log] [blame]
Alexander Afanasyevff3ee9f2018-06-13 20:33:30 -04001/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
Davide Pesaventod51d9602019-07-20 23:33:06 -04002/*
Davide Pesaventoc2649492020-12-22 21:43:35 -05003 * Copyright (c) 2014-2020, Regents of the University of California
Alexander Afanasyevff3ee9f2018-06-13 20:33:30 -04004 *
5 * NAC library is free software: you can redistribute it and/or modify it under the
6 * terms of the GNU Lesser General Public License as published by the Free Software
7 * Foundation, either version 3 of the License, or (at your option) any later version.
8 *
9 * NAC library is distributed in the hope that it will be useful, but WITHOUT ANY
10 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
11 * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
12 *
13 * You should have received copies of the GNU General Public License and GNU Lesser
14 * General Public License along with ndn-cxx, e.g., in COPYING.md file. If not, see
15 * <http://www.gnu.org/licenses/>.
16 *
17 * See AUTHORS.md for complete list of NAC library authors and contributors.
18 */
19
20#include "decryptor.hpp"
21
Davide Pesaventoc2649492020-12-22 21:43:35 -050022#include <ndn-cxx/security/transform/block-cipher.hpp>
23#include <ndn-cxx/security/transform/buffer-source.hpp>
24#include <ndn-cxx/security/transform/stream-sink.hpp>
25#include <ndn-cxx/util/exception.hpp>
Alexander Afanasyevff3ee9f2018-06-13 20:33:30 -040026#include <ndn-cxx/util/logger.hpp>
27
28namespace ndn {
29namespace nac {
30
31NDN_LOG_INIT(nac.Decryptor);
32
33const size_t N_RETRIES = 3;
34
35Decryptor::Decryptor(const Key& credentialsKey, Validator& validator, KeyChain& keyChain, Face& face)
36 : m_credentialsKey(credentialsKey)
37 // , m_validator(validator)
38 , m_face(face)
39 , m_keyChain(keyChain)
40 , m_internalKeyChain("pib-memory:", "tpm-memory:")
41{
42}
43
44Decryptor::~Decryptor()
45{
46 for (auto& i : m_cks) {
Davide Pesaventod51d9602019-07-20 23:33:06 -040047 if (i.second.pendingInterest) {
48 i.second.pendingInterest->cancel();
Alexander Afanasyevff3ee9f2018-06-13 20:33:30 -040049 for (const auto& p : i.second.pendingDecrypts) {
Davide Pesaventod51d9602019-07-20 23:33:06 -040050 p.onFailure(ErrorCode::CkRetrievalFailure,
51 "Cancel pending decrypt as ContentKey is being destroyed");
Alexander Afanasyevff3ee9f2018-06-13 20:33:30 -040052 }
Alexander Afanasyevff3ee9f2018-06-13 20:33:30 -040053 }
54 }
55}
56
57void
Davide Pesaventod51d9602019-07-20 23:33:06 -040058Decryptor::decrypt(const Block& encryptedContent,
59 const DecryptSuccessCallback& onSuccess,
60 const ErrorCallback& onFailure)
Alexander Afanasyevff3ee9f2018-06-13 20:33:30 -040061{
62 EncryptedContent ec(encryptedContent);
63 if (!ec.hasKeyLocator()) {
64 NDN_LOG_INFO("Missing required KeyLocator in the supplied EncryptedContent block");
65 return onFailure(ErrorCode::MissingRequiredKeyLocator,
66 "Missing required KeyLocator in the supplied EncryptedContent block");
67 }
68
69 if (!ec.hasIv()) {
70 NDN_LOG_INFO("Missing required InitialVector in the supplied EncryptedContent block");
71 return onFailure(ErrorCode::MissingRequiredKeyLocator,
72 "Missing required InitialVector in the supplied EncryptedContent block");
73 }
74
75 ContentKeys::iterator ck;
76 bool isNew = false;
77 std::tie(ck, isNew) = m_cks.emplace(ec.getKeyLocator(), ContentKey{});
78
79 if (ck->second.isRetrieved) {
80 doDecrypt(ec, ck->second.bits, onSuccess, onFailure);
81 }
82 else {
83 NDN_LOG_DEBUG("CK " << ec.getKeyLocator() << " not yet available, adding decrypt to the pending queue");
84 ck->second.pendingDecrypts.push_back({ec, onSuccess, onFailure});
85 }
86
87 if (isNew) {
88 fetchCk(ck, onFailure, N_RETRIES);
89 }
90}
91
92void
93Decryptor::fetchCk(ContentKeys::iterator ck, const ErrorCallback& onFailure, size_t nTriesLeft)
94{
95 // full name of CK is
96
97 // <whatever-prefix>/CK/<ck-id> /ENCRYPTED-BY /<kek-prefix>/KEK/<key-id>
98 // \ / \ /
99 // ----------- ------------- ----------- -----------
100 // \/ \/
101 // from the encrypted data unknown (name in retrieved CK is used to determine KDK)
102
103 const Name& ckName = ck->first;
104
105 NDN_LOG_DEBUG("Fetching CK " << ckName);
106
107 ck->second.pendingInterest = m_face.expressInterest(Interest(ckName)
108 .setMustBeFresh(false) // ?
109 .setCanBePrefix(true),
110 [=] (const Interest& ckInterest, const Data& ckData) {
Davide Pesaventod51d9602019-07-20 23:33:06 -0400111 ck->second.pendingInterest = nullopt;
Alexander Afanasyevff3ee9f2018-06-13 20:33:30 -0400112 // @TODO verify if the key is legit
113 Name kdkPrefix, kdkIdentity, kdkKeyName;
114 std::tie(kdkPrefix, kdkIdentity, kdkKeyName) =
115 extractKdkInfoFromCkName(ckData.getName(), ckInterest.getName(), onFailure);
116 if (kdkPrefix.empty()) {
117 return; // error has been already reported
118 }
119
120 // check if KDK already exists (there is a corresponding
121 auto kdkIdentityIt = m_internalKeyChain.getPib().getIdentities().find(kdkIdentity);
122 if (kdkIdentityIt != m_internalKeyChain.getPib().getIdentities().end()) {
123 auto kdkKeyIt = (*kdkIdentityIt).getKeys().find(kdkKeyName);
124 if (kdkKeyIt != (*kdkIdentityIt).getKeys().end()) {
125 // KDK was already fetched and imported
126 NDN_LOG_DEBUG("KDK " << kdkKeyName << " already exists, directly using it to decrypt CK");
127 return decryptCkAndProcessPendingDecrypts(ck, ckData, kdkKeyName, onFailure);
128 }
129 }
130
131 fetchKdk(ck, kdkPrefix, ckData, onFailure, N_RETRIES);
132 },
133 [=] (const Interest& i, const lp::Nack& nack) {
Davide Pesaventod51d9602019-07-20 23:33:06 -0400134 ck->second.pendingInterest = nullopt;
Alexander Afanasyevff3ee9f2018-06-13 20:33:30 -0400135 onFailure(ErrorCode::CkRetrievalFailure,
136 "Retrieval of CK [" + i.getName().toUri() + "] failed. "
137 "Got NACK (" + boost::lexical_cast<std::string>(nack.getReason()) + ")");
138 },
139 [=] (const Interest& i) {
Davide Pesaventod51d9602019-07-20 23:33:06 -0400140 ck->second.pendingInterest = nullopt;
Alexander Afanasyevff3ee9f2018-06-13 20:33:30 -0400141 if (nTriesLeft > 1) {
142 fetchCk(ck, onFailure, nTriesLeft - 1);
143 }
144 else {
145 onFailure(ErrorCode::CkRetrievalTimeout,
146 "Retrieval of CK [" + i.getName().toUri() + "] timed out");
147 }
148 });
149}
150
151void
152Decryptor::fetchKdk(ContentKeys::iterator ck, const Name& kdkPrefix, const Data& ckData,
153 const ErrorCallback& onFailure, size_t nTriesLeft)
154{
155 // <kdk-prefix>/KDK/<kdk-id> /ENCRYPTED-BY /<credential-identity>/KEY/<key-id>
156 // \ / \ /
157 // ----------- ------------- --------------- ---------------
158 // \/ \/
159 // from the CK data from configuration
160
161 Name kdkName = kdkPrefix;
162 kdkName
163 .append(ENCRYPTED_BY)
164 .append(m_credentialsKey.getName());
165
166 NDN_LOG_DEBUG("Fetching KDK " << kdkName);
167
168 ck->second.pendingInterest = m_face.expressInterest(Interest(kdkName)
169 .setMustBeFresh(true)
170 .setCanBePrefix(false),
Davide Pesaventod51d9602019-07-20 23:33:06 -0400171 [=] (const Interest&, const Data& kdkData) {
172 ck->second.pendingInterest = nullopt;
Alexander Afanasyevff3ee9f2018-06-13 20:33:30 -0400173 // @TODO verify if the key is legit
174
175 bool isOk = decryptAndImportKdk(kdkData, onFailure);
176 if (!isOk)
177 return;
178 decryptCkAndProcessPendingDecrypts(ck, ckData,
179 kdkPrefix.getPrefix(-2).append("KEY").append(kdkPrefix.get(-1)), // a bit hacky
180 onFailure);
181 },
182 [=] (const Interest& i, const lp::Nack& nack) {
Davide Pesaventod51d9602019-07-20 23:33:06 -0400183 ck->second.pendingInterest = nullopt;
Alexander Afanasyevff3ee9f2018-06-13 20:33:30 -0400184 onFailure(ErrorCode::KdkRetrievalFailure,
185 "Retrieval of KDK [" + i.getName().toUri() + "] failed. "
186 "Got NACK (" + boost::lexical_cast<std::string>(nack.getReason()) + ")");
187 },
188 [=] (const Interest& i) {
Davide Pesaventod51d9602019-07-20 23:33:06 -0400189 ck->second.pendingInterest = nullopt;
Alexander Afanasyevff3ee9f2018-06-13 20:33:30 -0400190 if (nTriesLeft > 1) {
191 fetchKdk(ck, kdkPrefix, ckData, onFailure, nTriesLeft - 1);
192 }
193 else {
194 onFailure(ErrorCode::KdkRetrievalTimeout,
195 "Retrieval of KDK [" + i.getName().toUri() + "] timed out");
196 }
197 });
198}
199
200bool
201Decryptor::decryptAndImportKdk(const Data& kdkData, const ErrorCallback& onFailure)
202{
203 try {
204 NDN_LOG_DEBUG("Decrypting and importing KDK " << kdkData.getName());
205 EncryptedContent content(kdkData.getContent().blockFromValue());
206
207 SafeBag safeBag(content.getPayload().blockFromValue());
208 auto secret = m_keyChain.getTpm().decrypt(content.getPayloadKey().value(),
209 content.getPayloadKey().value_size(),
210 m_credentialsKey.getName());
211 if (secret == nullptr) {
212 onFailure(ErrorCode::TpmKeyNotFound,
213 "Could not decrypt secret, " + m_credentialsKey.getName().toUri() + " not found in TPM");
214 return false;
215 }
216
217 m_internalKeyChain.importSafeBag(safeBag, reinterpret_cast<const char*>(secret->data()), secret->size());
218 return true;
219 }
220 catch (const std::runtime_error& e) {
221 // can be tlv::Error, pib::Error, tpm::Error, and bunch of other runtime-derived errors
222 onFailure(ErrorCode::KdkDecryptionFailure,
223 "Failed to decrypt KDK [" + kdkData.getName().toUri() + "]: " + e.what());
224 return false;
225 }
226}
227
228void
229Decryptor::decryptCkAndProcessPendingDecrypts(ContentKeys::iterator ck, const Data& ckData, const Name& kdkKeyName,
230 const ErrorCallback& onFailure)
231{
232 NDN_LOG_DEBUG("Decrypting CK data " << ckData.getName());
233
234 EncryptedContent content(ckData.getContent().blockFromValue());
235
236 auto ckBits = m_internalKeyChain.getTpm().decrypt(content.getPayload().value(), content.getPayload().value_size(),
237 kdkKeyName);
238 if (ckBits == nullptr) {
239 onFailure(ErrorCode::TpmKeyNotFound, "Could not decrypt secret, " + kdkKeyName.toUri() + " not found in TPM");
240 return;
241 }
242
243 ck->second.bits = *ckBits;
244 ck->second.isRetrieved = true;
245
246 for (const auto& item : ck->second.pendingDecrypts) {
247 doDecrypt(item.encryptedContent, ck->second.bits, item.onSuccess, item.onFailure);
248 }
249 ck->second.pendingDecrypts.clear();
250}
251
252void
253Decryptor::doDecrypt(const EncryptedContent& content, const Buffer& ckBits,
254 const DecryptSuccessCallback& onSuccess,
255 const ErrorCallback& onFailure)
256{
257 if (!content.hasIv()) {
Davide Pesaventoc2649492020-12-22 21:43:35 -0500258 NDN_THROW(Error("Expecting Initialization Vector in the encrypted content, but it is not present"));
Alexander Afanasyevff3ee9f2018-06-13 20:33:30 -0400259 }
260
261 OBufferStream os;
262 security::transform::bufferSource(content.getPayload().value(), content.getPayload().value_size())
263 >> security::transform::blockCipher(BlockCipherAlgorithm::AES_CBC,
264 CipherOperator::DECRYPT,
265 ckBits.data(), ckBits.size(),
266 content.getIv().value(), content.getIv().value_size())
267 >> security::transform::streamSink(os);
268
269 onSuccess(os.buf());
270}
271
272} // namespace nac
273} // namespace ndn