blob: 5a56ab14b5243308311252b50779f65a2cb631ac [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>
Zhiyi Zhang2b6d80c2020-10-12 12:49:14 -070025#include <openssl/ec.h>
26#include <openssl/evp.h>
Davide Pesavento368341b2019-08-13 23:57:50 -040027#include <ndn-cxx/encoding/buffer-stream.hpp>
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070028#include <ndn-cxx/security/transform/base64-decode.hpp>
29#include <ndn-cxx/security/transform/base64-encode.hpp>
30#include <ndn-cxx/security/transform/buffer-source.hpp>
Davide Pesavento368341b2019-08-13 23:57:50 -040031#include <ndn-cxx/security/transform/private-key.hpp>
32#include <ndn-cxx/security/transform/signer-filter.hpp>
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070033#include <ndn-cxx/security/transform/step-source.hpp>
34#include <ndn-cxx/security/transform/stream-sink.hpp>
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070035
36namespace ndn {
37namespace ndncert {
38
39const size_t HASH_SIZE = 32;
40
Zhiyi Zhangcfad98d2020-10-11 11:25:14 -070041NDN_LOG_INIT(ndncert.cryptosupport);
42
Zhiyi Zhang63123172020-10-12 14:24:44 -070043struct ECDHState::ECDH_CTX
44{
Zhiyi Zhangcfad98d2020-10-11 11:25:14 -070045 int EC_NID;
46 EVP_PKEY_CTX* ctx_params;
47 EVP_PKEY_CTX* ctx_keygen;
48 EVP_PKEY* privkey;
49 EVP_PKEY* peerkey;
50 EVP_PKEY* params;
51};
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070052
53ECDHState::ECDHState()
Zhiyi Zhangcfad98d2020-10-11 11:25:14 -070054 : m_publicKeyLen(0)
55 , m_sharedSecretLen(0)
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070056{
57 OpenSSL_add_all_algorithms();
58 context = std::make_unique<ECDH_CTX>();
59 context->EC_NID = NID_X9_62_prime256v1;
60
61 // Create the context for parameter generation
62 if (nullptr == (context->ctx_params = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, nullptr))) {
63 handleErrors("Could not create context contexts.");
64 return;
65 }
66
67 // Initialise the parameter generation
68 if (EVP_PKEY_paramgen_init(context->ctx_params) != 1) {
69 handleErrors("Could not initialize parameter generation.");
70 return;
71 }
72
73 // We're going to use the ANSI X9.62 Prime 256v1 curve
74 if (1 != EVP_PKEY_CTX_set_ec_paramgen_curve_nid(context->ctx_params, context->EC_NID)) {
75 handleErrors("Likely unknown elliptical curve ID specified.");
76 return;
77 }
78
79 // Create the parameter object params
80 if (!EVP_PKEY_paramgen(context->ctx_params, &context->params)) {
81 // the generated key is written to context->params
82 handleErrors("Could not create parameter object parameters.");
83 return;
84 }
85
86 // Create the context for the key generation
87 if (nullptr == (context->ctx_keygen = EVP_PKEY_CTX_new(context->params, nullptr))) {
88 //The EVP_PKEY_CTX_new() function allocates public key algorithm context using
89 //the algorithm specified in pkey and ENGINE e (in this case nullptr).
90 handleErrors("Could not create the context for the key generation");
91 return;
92 }
93
94 // initializes a public key algorithm context
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -070095 if (1 != EVP_PKEY_keygen_init(context->ctx_keygen)) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070096 handleErrors("Could not init context for key generation.");
97 return;
98 }
99 if (1 != EVP_PKEY_keygen(context->ctx_keygen, &context->privkey)) {
100 //performs a key generation operation, the generated key is written to context->privkey.
101 handleErrors("Could not generate DHE keys in final step");
102 return;
103 }
104}
105
106ECDHState::~ECDHState()
107{
108 // Contexts
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -0700109 if (context->ctx_params != nullptr) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700110 EVP_PKEY_CTX_free(context->ctx_params);
111 }
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -0700112 if (context->ctx_keygen != nullptr) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700113 EVP_PKEY_CTX_free(context->ctx_keygen);
114 }
115
116 // Keys
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -0700117 if (context->privkey != nullptr) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700118 EVP_PKEY_free(context->privkey);
119 }
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -0700120 if (context->peerkey != nullptr) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700121 EVP_PKEY_free(context->peerkey);
122 }
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -0700123 if (context->params != nullptr) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700124 EVP_PKEY_free(context->params);
125 }
126}
127
128uint8_t*
129ECDHState::getRawSelfPubKey()
130{
131 auto privECKey = EVP_PKEY_get1_EC_KEY(context->privkey);
132
133 if (privECKey == nullptr) {
134 handleErrors("Could not get referenced key when calling EVP_PKEY_get1_EC_KEY().");
135 return nullptr;
136 }
137
138 auto ecPoint = EC_KEY_get0_public_key(privECKey);
139 const EC_GROUP* group = EC_KEY_get0_group(privECKey);
Zhiyi Zhangcfad98d2020-10-11 11:25:14 -0700140 m_publicKeyLen = EC_POINT_point2oct(group, ecPoint, POINT_CONVERSION_COMPRESSED,
Zhiyi Zhang938d7032020-10-12 17:23:45 -0700141 m_publicKey, 256, nullptr);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700142 EC_KEY_free(privECKey);
Zhiyi Zhangcfad98d2020-10-11 11:25:14 -0700143 if (m_publicKeyLen == 0) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700144 handleErrors("Could not convert EC_POINTS to octet string when calling EC_POINT_point2oct.");
145 return nullptr;
146 }
147
Zhiyi Zhangcfad98d2020-10-11 11:25:14 -0700148 return m_publicKey;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700149}
150
151std::string
152ECDHState::getBase64PubKey()
153{
Davide Pesavento368341b2019-08-13 23:57:50 -0400154 namespace t = ndn::security::transform;
155
Zhiyi Zhangcfad98d2020-10-11 11:25:14 -0700156 if (m_publicKeyLen == 0) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700157 this->getRawSelfPubKey();
158 }
Davide Pesavento368341b2019-08-13 23:57:50 -0400159 std::ostringstream os;
Zhiyi Zhangcfad98d2020-10-11 11:25:14 -0700160 t::bufferSource(m_publicKey, m_publicKeyLen) >> t::base64Encode(false) >> t::streamSink(os);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700161 return os.str();
162}
163
164uint8_t*
165ECDHState::deriveSecret(const uint8_t* peerkey, int peerKeySize)
166{
167 auto privECKey = EVP_PKEY_get1_EC_KEY(context->privkey);
168
169 if (privECKey == nullptr) {
Zhiyi Zhang8da54d62019-11-21 00:03:05 -0800170 handleErrors("Could not get referenced key when calling EVP_PKEY_get1_EC_KEY()");
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700171 return nullptr;
172 }
173
174 auto group = EC_KEY_get0_group(privECKey);
175 auto peerPoint = EC_POINT_new(group);
Zhiyi Zhang8da54d62019-11-21 00:03:05 -0800176 int result = EC_POINT_oct2point(group, peerPoint, peerkey, peerKeySize, nullptr);
177 if (result == 0) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700178 EC_POINT_free(peerPoint);
179 EC_KEY_free(privECKey);
Zhiyi Zhang8da54d62019-11-21 00:03:05 -0800180 handleErrors("Cannot convert peer's key into a EC point when calling EC_POINT_oct2point()");
181 }
182
Zhiyi Zhang938d7032020-10-12 17:23:45 -0700183 result = ECDH_compute_key(m_sharedSecret, 256, peerPoint, privECKey, nullptr);
184 if (result == -1) {
Zhiyi Zhang8da54d62019-11-21 00:03:05 -0800185 EC_POINT_free(peerPoint);
186 EC_KEY_free(privECKey);
187 handleErrors("Cannot generate ECDH secret when calling ECDH_compute_key()");
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700188 }
Zhiyi Zhang938d7032020-10-12 17:23:45 -0700189 m_sharedSecretLen = static_cast<size_t>(result);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700190 EC_POINT_free(peerPoint);
191 EC_KEY_free(privECKey);
Zhiyi Zhangcfad98d2020-10-11 11:25:14 -0700192 return m_sharedSecret;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700193}
194
195uint8_t*
196ECDHState::deriveSecret(const std::string& peerKeyStr)
197{
198 namespace t = ndn::security::transform;
Davide Pesavento368341b2019-08-13 23:57:50 -0400199
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700200 OBufferStream os;
Zhiyi Zhang8da54d62019-11-21 00:03:05 -0800201 t::bufferSource(peerKeyStr) >> t::base64Decode(false) >> t::streamSink(os);
Davide Pesavento368341b2019-08-13 23:57:50 -0400202 auto result = os.buf();
203
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700204 return this->deriveSecret(result->data(), result->size());
205}
206
Davide Pesavento368341b2019-08-13 23:57:50 -0400207int
Zhiyi Zhang97bedb82020-10-10 11:11:35 -0700208hmac_sha256(const uint8_t* data, const unsigned data_length,
Zhiyi Zhangcfad98d2020-10-11 11:25:14 -0700209 const uint8_t* key, const unsigned key_length,
210 uint8_t* result)
Davide Pesavento368341b2019-08-13 23:57:50 -0400211{
Zhiyi Zhanga2ce5992019-08-14 17:35:00 -0700212 HMAC(EVP_sha256(), key, key_length,
213 (unsigned char*)data, data_length,
Zhiyi Zhanga2c39f72020-10-06 16:45:55 -0700214 (unsigned char*)result, nullptr);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700215 return 0;
216}
217
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700218int
Zhiyi Zhang97bedb82020-10-10 11:11:35 -0700219hkdf(const uint8_t* secret, int secret_len, const uint8_t* salt,
220 int salt_len, uint8_t* output, int output_len,
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700221 const uint8_t* info, int info_len)
222{
Davide Pesavento368341b2019-08-13 23:57:50 -0400223 namespace t = ndn::security::transform;
224
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700225 // hkdf generate prk
226 uint8_t prk[HASH_SIZE];
Zhiyi Zhang97bedb82020-10-10 11:11:35 -0700227 if (salt_len == 0) {
Zhiyi Zhanga2ce5992019-08-14 17:35:00 -0700228 uint8_t realSalt[HASH_SIZE] = {0};
Zhiyi Zhang97bedb82020-10-10 11:11:35 -0700229 hmac_sha256(secret, secret_len, realSalt, HASH_SIZE, prk);
Zhiyi Zhanga2ce5992019-08-14 17:35:00 -0700230 }
231 else {
Zhiyi Zhang97bedb82020-10-10 11:11:35 -0700232 hmac_sha256(secret, secret_len, salt, salt_len, prk);
Zhiyi Zhanga2ce5992019-08-14 17:35:00 -0700233 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700234
235 // hkdf expand
236 uint8_t prev[HASH_SIZE] = {0};
Zhiyi Zhang97bedb82020-10-10 11:11:35 -0700237 int done_len = 0, dig_len = HASH_SIZE, n = output_len / dig_len;
238 if (output_len % dig_len)
Davide Pesavento368341b2019-08-13 23:57:50 -0400239 n++;
Zhiyi Zhang97bedb82020-10-10 11:11:35 -0700240 if (n > 255 || output == nullptr)
Davide Pesavento368341b2019-08-13 23:57:50 -0400241 return 0;
242
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700243 for (int i = 1; i <= n; i++) {
244 size_t copy_len;
245 const uint8_t ctr = i;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700246
Davide Pesavento368341b2019-08-13 23:57:50 -0400247 t::StepSource source;
248 t::PrivateKey privKey;
249 privKey.loadRaw(KeyType::HMAC, prk, dig_len);
250 OBufferStream os;
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -0700251 source >> t::signerFilter(DigestAlgorithm::SHA256, privKey) >> t::streamSink(os);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700252
253 if (i > 1) {
254 source.write(prev, dig_len);
255 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700256 source.write(info, info_len);
257 source.write(&ctr, 1);
258 source.end();
259
260 auto result = os.buf();
261 memcpy(prev, result->data(), dig_len);
Zhiyi Zhang97bedb82020-10-10 11:11:35 -0700262 copy_len = (done_len + dig_len > output_len) ? output_len - done_len : dig_len;
263 memcpy(output + done_len, prev, copy_len);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700264 done_len += copy_len;
265 }
266 return done_len;
267}
268
Zhiyi Zhanga67fa462020-04-19 13:48:03 -0700269int
270aes_gcm_128_encrypt(const uint8_t* plaintext, size_t plaintext_len, const uint8_t* associated, size_t associated_len,
271 const uint8_t* key, const uint8_t* iv, uint8_t* ciphertext, uint8_t* tag)
272{
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -0700273 EVP_CIPHER_CTX* ctx;
Zhiyi Zhanga67fa462020-04-19 13:48:03 -0700274 int len;
275 int ciphertext_len;
276
277 // Create and initialise the context
278 if (!(ctx = EVP_CIPHER_CTX_new())) {
279 handleErrors("Cannot create and initialise the context when calling EVP_CIPHER_CTX_new()");
280 }
281
282 // Initialise the encryption operation.
283 if (1 != EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), nullptr, nullptr, nullptr)) {
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -0700284 handleErrors("Cannot initialise the encryption operation when calling EVP_EncryptInit_ex()");
Zhiyi Zhanga67fa462020-04-19 13:48:03 -0700285 }
286
287 // Set IV length if default 12 bytes (96 bits) is not appropriate
288 if (1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 12, nullptr)) {
289 handleErrors("Cannot set IV length when calling EVP_CIPHER_CTX_ctrl()");
290 }
291
292 // Initialise key and IV
293 if (1 != EVP_EncryptInit_ex(ctx, nullptr, nullptr, key, iv)) {
294 handleErrors("Cannot initialize key and IV when calling EVP_EncryptInit_ex()");
295 }
296
297 // Provide any AAD data. This can be called zero or more times as required
298 if (1 != EVP_EncryptUpdate(ctx, nullptr, &len, associated, associated_len)) {
299 handleErrors("Cannot set associated authentication data when calling EVP_EncryptUpdate()");
300 }
301
302 // Provide the message to be encrypted, and obtain the encrypted output.
303 // EVP_EncryptUpdate can be called multiple times if necessary
304 if (1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len)) {
305 handleErrors("Cannot encrypt when calling EVP_EncryptUpdate()");
306 }
307 ciphertext_len = len;
308
309 // Finalise the encryption. Normally ciphertext bytes may be written at
310 // this stage, but this does not occur in GCM mode
311 if (1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) {
312 handleErrors("Cannot finalise the encryption when calling EVP_EncryptFinal_ex()");
313 }
314 ciphertext_len += len;
315
316 // Get the tag
317 if (1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, 16, tag)) {
318 handleErrors("Cannot get tag when calling EVP_CIPHER_CTX_ctrl()");
319 }
320
321 // Clean up
322 EVP_CIPHER_CTX_free(ctx);
323 return ciphertext_len;
324}
325
326int
327aes_gcm_128_decrypt(const uint8_t* ciphertext, size_t ciphertext_len, const uint8_t* associated, size_t associated_len,
328 const uint8_t* tag, const uint8_t* key, const uint8_t* iv, uint8_t* plaintext)
329{
330 EVP_CIPHER_CTX* ctx;
331 int len;
332 int plaintext_len;
333 int ret;
334
335 // Create and initialise the context
336 if (!(ctx = EVP_CIPHER_CTX_new())) {
337 handleErrors("Cannot create and initialise the context when calling EVP_CIPHER_CTX_new()");
338 }
339
340 // Initialise the decryption operation.
341 if (!EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), nullptr, nullptr, nullptr)) {
342 handleErrors("Cannot initialise the decryption operation when calling EVP_DecryptInit_ex()");
343 }
344
345 // Set IV length. Not necessary if this is 12 bytes (96 bits)
346 if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 12, nullptr)) {
347 handleErrors("Cannot set IV length when calling EVP_CIPHER_CTX_ctrl");
348 }
349
350 // Initialise key and IV
351 if (!EVP_DecryptInit_ex(ctx, nullptr, nullptr, key, iv)) {
352 handleErrors("Cannot initialise key and IV when calling EVP_DecryptInit_ex()");
353 }
354
355 // Provide any AAD data. This can be called zero or more times as required
356 if (!EVP_DecryptUpdate(ctx, nullptr, &len, associated, associated_len)) {
357 handleErrors("Cannot set associated authentication data when calling EVP_EncryptUpdate()");
358 }
359
360 // Provide the message to be decrypted, and obtain the plaintext output.
361 // EVP_DecryptUpdate can be called multiple times if necessary
362 if (!EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len)) {
363 handleErrors("Cannot decrypt when calling EVP_DecryptUpdate()");
364 }
365 plaintext_len = len;
366
367 // Set expected tag value. Works in OpenSSL 1.0.1d and later
368 if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, 16, (void*)tag)) {
369 handleErrors("Cannot set tag value when calling EVP_CIPHER_CTX_ctrl");
370 }
371
372 // Finalise the decryption. A positive return value indicates success,
373 // anything else is a failure - the plaintext is not trustworthy.
374 ret = EVP_DecryptFinal_ex(ctx, plaintext + len, &len);
375
376 // Clean up
377 EVP_CIPHER_CTX_free(ctx);
378
379 if (ret > 0) {
380 // Success
381 plaintext_len += len;
382 return plaintext_len;
383 }
384 else {
385 // Verify failed
386 return -1;
387 }
388}
389
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700390void
391handleErrors(const std::string& errorInfo)
392{
Zhiyi Zhangd61b4a82020-10-10 15:18:43 -0700393 NDN_LOG_DEBUG("Error in CRYPTO SUPPORT " << errorInfo);
Zhiyi Zhangccd5a0c2020-10-12 13:48:16 -0700394 NDN_THROW(std::runtime_error("Error in CRYPTO SUPPORT: " + errorInfo));
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700395}
396
Zhiyi Zhange4891b72020-10-10 15:11:57 -0700397} // namespace ndncert
398} // namespace ndn