blob: 286490d2fb20e9d29584096c2ec8675a10e2fb25 [file] [log] [blame]
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -07001/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
Zhiyi Zhanga67fa462020-04-19 13:48:03 -07002/**
3 * Copyright (c) 2017-2020, Regents of the University of California.
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -07004 *
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 "crypto-helper.hpp"
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070022#include <openssl/err.h>
Zhiyi Zhanga2ce5992019-08-14 17:35:00 -070023#include <openssl/hmac.h>
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -070024#include <openssl/pem.h>
Davide Pesavento368341b2019-08-13 23:57:50 -040025#include <ndn-cxx/encoding/buffer-stream.hpp>
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070026#include <ndn-cxx/security/transform/base64-decode.hpp>
27#include <ndn-cxx/security/transform/base64-encode.hpp>
28#include <ndn-cxx/security/transform/buffer-source.hpp>
Davide Pesavento368341b2019-08-13 23:57:50 -040029#include <ndn-cxx/security/transform/private-key.hpp>
30#include <ndn-cxx/security/transform/signer-filter.hpp>
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070031#include <ndn-cxx/security/transform/step-source.hpp>
32#include <ndn-cxx/security/transform/stream-sink.hpp>
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070033
34namespace ndn {
35namespace ndncert {
36
37const size_t HASH_SIZE = 32;
38
Zhiyi Zhangcfad98d2020-10-11 11:25:14 -070039NDN_LOG_INIT(ndncert.cryptosupport);
40
41struct ECDHState::ECDH_CTX {
42 int EC_NID;
43 EVP_PKEY_CTX* ctx_params;
44 EVP_PKEY_CTX* ctx_keygen;
45 EVP_PKEY* privkey;
46 EVP_PKEY* peerkey;
47 EVP_PKEY* params;
48};
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070049
50ECDHState::ECDHState()
Zhiyi Zhangcfad98d2020-10-11 11:25:14 -070051 : m_publicKeyLen(0)
52 , m_sharedSecretLen(0)
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070053{
54 OpenSSL_add_all_algorithms();
55 context = std::make_unique<ECDH_CTX>();
56 context->EC_NID = NID_X9_62_prime256v1;
57
58 // Create the context for parameter generation
59 if (nullptr == (context->ctx_params = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, nullptr))) {
60 handleErrors("Could not create context contexts.");
61 return;
62 }
63
64 // Initialise the parameter generation
65 if (EVP_PKEY_paramgen_init(context->ctx_params) != 1) {
66 handleErrors("Could not initialize parameter generation.");
67 return;
68 }
69
70 // We're going to use the ANSI X9.62 Prime 256v1 curve
71 if (1 != EVP_PKEY_CTX_set_ec_paramgen_curve_nid(context->ctx_params, context->EC_NID)) {
72 handleErrors("Likely unknown elliptical curve ID specified.");
73 return;
74 }
75
76 // Create the parameter object params
77 if (!EVP_PKEY_paramgen(context->ctx_params, &context->params)) {
78 // the generated key is written to context->params
79 handleErrors("Could not create parameter object parameters.");
80 return;
81 }
82
83 // Create the context for the key generation
84 if (nullptr == (context->ctx_keygen = EVP_PKEY_CTX_new(context->params, nullptr))) {
85 //The EVP_PKEY_CTX_new() function allocates public key algorithm context using
86 //the algorithm specified in pkey and ENGINE e (in this case nullptr).
87 handleErrors("Could not create the context for the key generation");
88 return;
89 }
90
91 // initializes a public key algorithm context
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -070092 if (1 != EVP_PKEY_keygen_init(context->ctx_keygen)) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070093 handleErrors("Could not init context for key generation.");
94 return;
95 }
96 if (1 != EVP_PKEY_keygen(context->ctx_keygen, &context->privkey)) {
97 //performs a key generation operation, the generated key is written to context->privkey.
98 handleErrors("Could not generate DHE keys in final step");
99 return;
100 }
101}
102
103ECDHState::~ECDHState()
104{
105 // Contexts
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -0700106 if (context->ctx_params != nullptr) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700107 EVP_PKEY_CTX_free(context->ctx_params);
108 }
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -0700109 if (context->ctx_keygen != nullptr) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700110 EVP_PKEY_CTX_free(context->ctx_keygen);
111 }
112
113 // Keys
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -0700114 if (context->privkey != nullptr) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700115 EVP_PKEY_free(context->privkey);
116 }
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -0700117 if (context->peerkey != nullptr) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700118 EVP_PKEY_free(context->peerkey);
119 }
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -0700120 if (context->params != nullptr) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700121 EVP_PKEY_free(context->params);
122 }
123}
124
125uint8_t*
126ECDHState::getRawSelfPubKey()
127{
128 auto privECKey = EVP_PKEY_get1_EC_KEY(context->privkey);
129
130 if (privECKey == nullptr) {
131 handleErrors("Could not get referenced key when calling EVP_PKEY_get1_EC_KEY().");
132 return nullptr;
133 }
134
135 auto ecPoint = EC_KEY_get0_public_key(privECKey);
136 const EC_GROUP* group = EC_KEY_get0_group(privECKey);
Zhiyi Zhangcfad98d2020-10-11 11:25:14 -0700137 m_publicKeyLen = EC_POINT_point2oct(group, ecPoint, POINT_CONVERSION_COMPRESSED,
138 m_publicKey, 256, nullptr);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700139 EC_KEY_free(privECKey);
Zhiyi Zhangcfad98d2020-10-11 11:25:14 -0700140 if (m_publicKeyLen == 0) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700141 handleErrors("Could not convert EC_POINTS to octet string when calling EC_POINT_point2oct.");
142 return nullptr;
143 }
144
Zhiyi Zhangcfad98d2020-10-11 11:25:14 -0700145 return m_publicKey;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700146}
147
148std::string
149ECDHState::getBase64PubKey()
150{
Davide Pesavento368341b2019-08-13 23:57:50 -0400151 namespace t = ndn::security::transform;
152
Zhiyi Zhangcfad98d2020-10-11 11:25:14 -0700153 if (m_publicKeyLen == 0) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700154 this->getRawSelfPubKey();
155 }
Davide Pesavento368341b2019-08-13 23:57:50 -0400156 std::ostringstream os;
Zhiyi Zhangcfad98d2020-10-11 11:25:14 -0700157 t::bufferSource(m_publicKey, m_publicKeyLen) >> t::base64Encode(false) >> t::streamSink(os);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700158 return os.str();
159}
160
161uint8_t*
162ECDHState::deriveSecret(const uint8_t* peerkey, int peerKeySize)
163{
164 auto privECKey = EVP_PKEY_get1_EC_KEY(context->privkey);
165
166 if (privECKey == nullptr) {
Zhiyi Zhang8da54d62019-11-21 00:03:05 -0800167 handleErrors("Could not get referenced key when calling EVP_PKEY_get1_EC_KEY()");
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700168 return nullptr;
169 }
170
171 auto group = EC_KEY_get0_group(privECKey);
172 auto peerPoint = EC_POINT_new(group);
Zhiyi Zhang8da54d62019-11-21 00:03:05 -0800173 int result = EC_POINT_oct2point(group, peerPoint, peerkey, peerKeySize, nullptr);
174 if (result == 0) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700175 EC_POINT_free(peerPoint);
176 EC_KEY_free(privECKey);
Zhiyi Zhang8da54d62019-11-21 00:03:05 -0800177 handleErrors("Cannot convert peer's key into a EC point when calling EC_POINT_oct2point()");
178 }
179
Zhiyi Zhangcfad98d2020-10-11 11:25:14 -0700180 if (-1 == (m_sharedSecretLen = ECDH_compute_key(m_sharedSecret, 256, peerPoint, privECKey, nullptr))) {
Zhiyi Zhang8da54d62019-11-21 00:03:05 -0800181 EC_POINT_free(peerPoint);
182 EC_KEY_free(privECKey);
183 handleErrors("Cannot generate ECDH secret when calling ECDH_compute_key()");
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700184 }
185 EC_POINT_free(peerPoint);
186 EC_KEY_free(privECKey);
Zhiyi Zhangcfad98d2020-10-11 11:25:14 -0700187 return m_sharedSecret;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700188}
189
190uint8_t*
191ECDHState::deriveSecret(const std::string& peerKeyStr)
192{
193 namespace t = ndn::security::transform;
Davide Pesavento368341b2019-08-13 23:57:50 -0400194
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700195 OBufferStream os;
Zhiyi Zhang8da54d62019-11-21 00:03:05 -0800196 t::bufferSource(peerKeyStr) >> t::base64Decode(false) >> t::streamSink(os);
Davide Pesavento368341b2019-08-13 23:57:50 -0400197 auto result = os.buf();
198
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700199 return this->deriveSecret(result->data(), result->size());
200}
201
Davide Pesavento368341b2019-08-13 23:57:50 -0400202int
Zhiyi Zhang97bedb82020-10-10 11:11:35 -0700203hmac_sha256(const uint8_t* data, const unsigned data_length,
Zhiyi Zhangcfad98d2020-10-11 11:25:14 -0700204 const uint8_t* key, const unsigned key_length,
205 uint8_t* result)
Davide Pesavento368341b2019-08-13 23:57:50 -0400206{
Zhiyi Zhanga2ce5992019-08-14 17:35:00 -0700207 HMAC(EVP_sha256(), key, key_length,
208 (unsigned char*)data, data_length,
Zhiyi Zhanga2c39f72020-10-06 16:45:55 -0700209 (unsigned char*)result, nullptr);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700210 return 0;
211}
212
Davide Pesavento368341b2019-08-13 23:57:50 -0400213// avoid dependency on OpenSSL >= 1.1
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700214int
Zhiyi Zhang97bedb82020-10-10 11:11:35 -0700215hkdf(const uint8_t* secret, int secret_len, const uint8_t* salt,
216 int salt_len, uint8_t* output, int output_len,
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700217 const uint8_t* info, int info_len)
218{
Davide Pesavento368341b2019-08-13 23:57:50 -0400219 namespace t = ndn::security::transform;
220
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700221 // hkdf generate prk
222 uint8_t prk[HASH_SIZE];
Zhiyi Zhang97bedb82020-10-10 11:11:35 -0700223 if (salt_len == 0) {
Zhiyi Zhanga2ce5992019-08-14 17:35:00 -0700224 uint8_t realSalt[HASH_SIZE] = {0};
Zhiyi Zhang97bedb82020-10-10 11:11:35 -0700225 hmac_sha256(secret, secret_len, realSalt, HASH_SIZE, prk);
Zhiyi Zhanga2ce5992019-08-14 17:35:00 -0700226 }
227 else {
Zhiyi Zhang97bedb82020-10-10 11:11:35 -0700228 hmac_sha256(secret, secret_len, salt, salt_len, prk);
Zhiyi Zhanga2ce5992019-08-14 17:35:00 -0700229 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700230
231 // hkdf expand
232 uint8_t prev[HASH_SIZE] = {0};
Zhiyi Zhang97bedb82020-10-10 11:11:35 -0700233 int done_len = 0, dig_len = HASH_SIZE, n = output_len / dig_len;
234 if (output_len % dig_len)
Davide Pesavento368341b2019-08-13 23:57:50 -0400235 n++;
Zhiyi Zhang97bedb82020-10-10 11:11:35 -0700236 if (n > 255 || output == nullptr)
Davide Pesavento368341b2019-08-13 23:57:50 -0400237 return 0;
238
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700239 for (int i = 1; i <= n; i++) {
240 size_t copy_len;
241 const uint8_t ctr = i;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700242
Davide Pesavento368341b2019-08-13 23:57:50 -0400243 t::StepSource source;
244 t::PrivateKey privKey;
245 privKey.loadRaw(KeyType::HMAC, prk, dig_len);
246 OBufferStream os;
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -0700247 source >> t::signerFilter(DigestAlgorithm::SHA256, privKey) >> t::streamSink(os);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700248
249 if (i > 1) {
250 source.write(prev, dig_len);
251 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700252 source.write(info, info_len);
253 source.write(&ctr, 1);
254 source.end();
255
256 auto result = os.buf();
257 memcpy(prev, result->data(), dig_len);
Zhiyi Zhang97bedb82020-10-10 11:11:35 -0700258 copy_len = (done_len + dig_len > output_len) ? output_len - done_len : dig_len;
259 memcpy(output + done_len, prev, copy_len);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700260 done_len += copy_len;
261 }
262 return done_len;
263}
264
Zhiyi Zhanga67fa462020-04-19 13:48:03 -0700265int
266aes_gcm_128_encrypt(const uint8_t* plaintext, size_t plaintext_len, const uint8_t* associated, size_t associated_len,
267 const uint8_t* key, const uint8_t* iv, uint8_t* ciphertext, uint8_t* tag)
268{
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -0700269 EVP_CIPHER_CTX* ctx;
Zhiyi Zhanga67fa462020-04-19 13:48:03 -0700270 int len;
271 int ciphertext_len;
272
273 // Create and initialise the context
274 if (!(ctx = EVP_CIPHER_CTX_new())) {
275 handleErrors("Cannot create and initialise the context when calling EVP_CIPHER_CTX_new()");
276 }
277
278 // Initialise the encryption operation.
279 if (1 != EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), nullptr, nullptr, nullptr)) {
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -0700280 handleErrors("Cannot initialise the encryption operation when calling EVP_EncryptInit_ex()");
Zhiyi Zhanga67fa462020-04-19 13:48:03 -0700281 }
282
283 // Set IV length if default 12 bytes (96 bits) is not appropriate
284 if (1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 12, nullptr)) {
285 handleErrors("Cannot set IV length when calling EVP_CIPHER_CTX_ctrl()");
286 }
287
288 // Initialise key and IV
289 if (1 != EVP_EncryptInit_ex(ctx, nullptr, nullptr, key, iv)) {
290 handleErrors("Cannot initialize key and IV when calling EVP_EncryptInit_ex()");
291 }
292
293 // Provide any AAD data. This can be called zero or more times as required
294 if (1 != EVP_EncryptUpdate(ctx, nullptr, &len, associated, associated_len)) {
295 handleErrors("Cannot set associated authentication data when calling EVP_EncryptUpdate()");
296 }
297
298 // Provide the message to be encrypted, and obtain the encrypted output.
299 // EVP_EncryptUpdate can be called multiple times if necessary
300 if (1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len)) {
301 handleErrors("Cannot encrypt when calling EVP_EncryptUpdate()");
302 }
303 ciphertext_len = len;
304
305 // Finalise the encryption. Normally ciphertext bytes may be written at
306 // this stage, but this does not occur in GCM mode
307 if (1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) {
308 handleErrors("Cannot finalise the encryption when calling EVP_EncryptFinal_ex()");
309 }
310 ciphertext_len += len;
311
312 // Get the tag
313 if (1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, 16, tag)) {
314 handleErrors("Cannot get tag when calling EVP_CIPHER_CTX_ctrl()");
315 }
316
317 // Clean up
318 EVP_CIPHER_CTX_free(ctx);
319 return ciphertext_len;
320}
321
322int
323aes_gcm_128_decrypt(const uint8_t* ciphertext, size_t ciphertext_len, const uint8_t* associated, size_t associated_len,
324 const uint8_t* tag, const uint8_t* key, const uint8_t* iv, uint8_t* plaintext)
325{
326 EVP_CIPHER_CTX* ctx;
327 int len;
328 int plaintext_len;
329 int ret;
330
331 // Create and initialise the context
332 if (!(ctx = EVP_CIPHER_CTX_new())) {
333 handleErrors("Cannot create and initialise the context when calling EVP_CIPHER_CTX_new()");
334 }
335
336 // Initialise the decryption operation.
337 if (!EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), nullptr, nullptr, nullptr)) {
338 handleErrors("Cannot initialise the decryption operation when calling EVP_DecryptInit_ex()");
339 }
340
341 // Set IV length. Not necessary if this is 12 bytes (96 bits)
342 if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 12, nullptr)) {
343 handleErrors("Cannot set IV length when calling EVP_CIPHER_CTX_ctrl");
344 }
345
346 // Initialise key and IV
347 if (!EVP_DecryptInit_ex(ctx, nullptr, nullptr, key, iv)) {
348 handleErrors("Cannot initialise key and IV when calling EVP_DecryptInit_ex()");
349 }
350
351 // Provide any AAD data. This can be called zero or more times as required
352 if (!EVP_DecryptUpdate(ctx, nullptr, &len, associated, associated_len)) {
353 handleErrors("Cannot set associated authentication data when calling EVP_EncryptUpdate()");
354 }
355
356 // Provide the message to be decrypted, and obtain the plaintext output.
357 // EVP_DecryptUpdate can be called multiple times if necessary
358 if (!EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len)) {
359 handleErrors("Cannot decrypt when calling EVP_DecryptUpdate()");
360 }
361 plaintext_len = len;
362
363 // Set expected tag value. Works in OpenSSL 1.0.1d and later
364 if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, 16, (void*)tag)) {
365 handleErrors("Cannot set tag value when calling EVP_CIPHER_CTX_ctrl");
366 }
367
368 // Finalise the decryption. A positive return value indicates success,
369 // anything else is a failure - the plaintext is not trustworthy.
370 ret = EVP_DecryptFinal_ex(ctx, plaintext + len, &len);
371
372 // Clean up
373 EVP_CIPHER_CTX_free(ctx);
374
375 if (ret > 0) {
376 // Success
377 plaintext_len += len;
378 return plaintext_len;
379 }
380 else {
381 // Verify failed
382 return -1;
383 }
384}
385
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700386void
387handleErrors(const std::string& errorInfo)
388{
Zhiyi Zhangd61b4a82020-10-10 15:18:43 -0700389 NDN_LOG_DEBUG("Error in CRYPTO SUPPORT " << errorInfo);
tylerliu41c11532020-10-10 16:14:45 -0700390 NDN_THROW(CryptoError("Error in CRYPTO SUPPORT: " + errorInfo));
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700391}
392
Zhiyi Zhange4891b72020-10-10 15:11:57 -0700393} // namespace ndncert
394} // namespace ndn