blob: 6ff58cc82aab827bf8a71046d6246c8c75825bc8 [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
43struct ECDHState::ECDH_CTX {
44 int EC_NID;
45 EVP_PKEY_CTX* ctx_params;
46 EVP_PKEY_CTX* ctx_keygen;
47 EVP_PKEY* privkey;
48 EVP_PKEY* peerkey;
49 EVP_PKEY* params;
50};
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070051
52ECDHState::ECDHState()
Zhiyi Zhangcfad98d2020-10-11 11:25:14 -070053 : m_publicKeyLen(0)
54 , m_sharedSecretLen(0)
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070055{
56 OpenSSL_add_all_algorithms();
57 context = std::make_unique<ECDH_CTX>();
58 context->EC_NID = NID_X9_62_prime256v1;
59
60 // Create the context for parameter generation
61 if (nullptr == (context->ctx_params = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, nullptr))) {
62 handleErrors("Could not create context contexts.");
63 return;
64 }
65
66 // Initialise the parameter generation
67 if (EVP_PKEY_paramgen_init(context->ctx_params) != 1) {
68 handleErrors("Could not initialize parameter generation.");
69 return;
70 }
71
72 // We're going to use the ANSI X9.62 Prime 256v1 curve
73 if (1 != EVP_PKEY_CTX_set_ec_paramgen_curve_nid(context->ctx_params, context->EC_NID)) {
74 handleErrors("Likely unknown elliptical curve ID specified.");
75 return;
76 }
77
78 // Create the parameter object params
79 if (!EVP_PKEY_paramgen(context->ctx_params, &context->params)) {
80 // the generated key is written to context->params
81 handleErrors("Could not create parameter object parameters.");
82 return;
83 }
84
85 // Create the context for the key generation
86 if (nullptr == (context->ctx_keygen = EVP_PKEY_CTX_new(context->params, nullptr))) {
87 //The EVP_PKEY_CTX_new() function allocates public key algorithm context using
88 //the algorithm specified in pkey and ENGINE e (in this case nullptr).
89 handleErrors("Could not create the context for the key generation");
90 return;
91 }
92
93 // initializes a public key algorithm context
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -070094 if (1 != EVP_PKEY_keygen_init(context->ctx_keygen)) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070095 handleErrors("Could not init context for key generation.");
96 return;
97 }
98 if (1 != EVP_PKEY_keygen(context->ctx_keygen, &context->privkey)) {
99 //performs a key generation operation, the generated key is written to context->privkey.
100 handleErrors("Could not generate DHE keys in final step");
101 return;
102 }
103}
104
105ECDHState::~ECDHState()
106{
107 // Contexts
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -0700108 if (context->ctx_params != nullptr) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700109 EVP_PKEY_CTX_free(context->ctx_params);
110 }
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -0700111 if (context->ctx_keygen != nullptr) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700112 EVP_PKEY_CTX_free(context->ctx_keygen);
113 }
114
115 // Keys
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -0700116 if (context->privkey != nullptr) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700117 EVP_PKEY_free(context->privkey);
118 }
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -0700119 if (context->peerkey != nullptr) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700120 EVP_PKEY_free(context->peerkey);
121 }
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -0700122 if (context->params != nullptr) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700123 EVP_PKEY_free(context->params);
124 }
125}
126
127uint8_t*
128ECDHState::getRawSelfPubKey()
129{
130 auto privECKey = EVP_PKEY_get1_EC_KEY(context->privkey);
131
132 if (privECKey == nullptr) {
133 handleErrors("Could not get referenced key when calling EVP_PKEY_get1_EC_KEY().");
134 return nullptr;
135 }
136
137 auto ecPoint = EC_KEY_get0_public_key(privECKey);
138 const EC_GROUP* group = EC_KEY_get0_group(privECKey);
Zhiyi Zhangcfad98d2020-10-11 11:25:14 -0700139 m_publicKeyLen = EC_POINT_point2oct(group, ecPoint, POINT_CONVERSION_COMPRESSED,
140 m_publicKey, 256, nullptr);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700141 EC_KEY_free(privECKey);
Zhiyi Zhangcfad98d2020-10-11 11:25:14 -0700142 if (m_publicKeyLen == 0) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700143 handleErrors("Could not convert EC_POINTS to octet string when calling EC_POINT_point2oct.");
144 return nullptr;
145 }
146
Zhiyi Zhangcfad98d2020-10-11 11:25:14 -0700147 return m_publicKey;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700148}
149
150std::string
151ECDHState::getBase64PubKey()
152{
Davide Pesavento368341b2019-08-13 23:57:50 -0400153 namespace t = ndn::security::transform;
154
Zhiyi Zhangcfad98d2020-10-11 11:25:14 -0700155 if (m_publicKeyLen == 0) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700156 this->getRawSelfPubKey();
157 }
Davide Pesavento368341b2019-08-13 23:57:50 -0400158 std::ostringstream os;
Zhiyi Zhangcfad98d2020-10-11 11:25:14 -0700159 t::bufferSource(m_publicKey, m_publicKeyLen) >> t::base64Encode(false) >> t::streamSink(os);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700160 return os.str();
161}
162
163uint8_t*
164ECDHState::deriveSecret(const uint8_t* peerkey, int peerKeySize)
165{
166 auto privECKey = EVP_PKEY_get1_EC_KEY(context->privkey);
167
168 if (privECKey == nullptr) {
Zhiyi Zhang8da54d62019-11-21 00:03:05 -0800169 handleErrors("Could not get referenced key when calling EVP_PKEY_get1_EC_KEY()");
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700170 return nullptr;
171 }
172
173 auto group = EC_KEY_get0_group(privECKey);
174 auto peerPoint = EC_POINT_new(group);
Zhiyi Zhang8da54d62019-11-21 00:03:05 -0800175 int result = EC_POINT_oct2point(group, peerPoint, peerkey, peerKeySize, nullptr);
176 if (result == 0) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700177 EC_POINT_free(peerPoint);
178 EC_KEY_free(privECKey);
Zhiyi Zhang8da54d62019-11-21 00:03:05 -0800179 handleErrors("Cannot convert peer's key into a EC point when calling EC_POINT_oct2point()");
180 }
181
Zhiyi Zhangcfad98d2020-10-11 11:25:14 -0700182 if (-1 == (m_sharedSecretLen = ECDH_compute_key(m_sharedSecret, 256, peerPoint, privECKey, nullptr))) {
Zhiyi Zhang8da54d62019-11-21 00:03:05 -0800183 EC_POINT_free(peerPoint);
184 EC_KEY_free(privECKey);
185 handleErrors("Cannot generate ECDH secret when calling ECDH_compute_key()");
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700186 }
187 EC_POINT_free(peerPoint);
188 EC_KEY_free(privECKey);
Zhiyi Zhangcfad98d2020-10-11 11:25:14 -0700189 return m_sharedSecret;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700190}
191
192uint8_t*
193ECDHState::deriveSecret(const std::string& peerKeyStr)
194{
195 namespace t = ndn::security::transform;
Davide Pesavento368341b2019-08-13 23:57:50 -0400196
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700197 OBufferStream os;
Zhiyi Zhang8da54d62019-11-21 00:03:05 -0800198 t::bufferSource(peerKeyStr) >> t::base64Decode(false) >> t::streamSink(os);
Davide Pesavento368341b2019-08-13 23:57:50 -0400199 auto result = os.buf();
200
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700201 return this->deriveSecret(result->data(), result->size());
202}
203
Davide Pesavento368341b2019-08-13 23:57:50 -0400204int
Zhiyi Zhang97bedb82020-10-10 11:11:35 -0700205hmac_sha256(const uint8_t* data, const unsigned data_length,
Zhiyi Zhangcfad98d2020-10-11 11:25:14 -0700206 const uint8_t* key, const unsigned key_length,
207 uint8_t* result)
Davide Pesavento368341b2019-08-13 23:57:50 -0400208{
Zhiyi Zhanga2ce5992019-08-14 17:35:00 -0700209 HMAC(EVP_sha256(), key, key_length,
210 (unsigned char*)data, data_length,
Zhiyi Zhanga2c39f72020-10-06 16:45:55 -0700211 (unsigned char*)result, nullptr);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700212 return 0;
213}
214
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700215int
Zhiyi Zhang97bedb82020-10-10 11:11:35 -0700216hkdf(const uint8_t* secret, int secret_len, const uint8_t* salt,
217 int salt_len, uint8_t* output, int output_len,
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700218 const uint8_t* info, int info_len)
219{
Davide Pesavento368341b2019-08-13 23:57:50 -0400220 namespace t = ndn::security::transform;
221
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700222 // hkdf generate prk
223 uint8_t prk[HASH_SIZE];
Zhiyi Zhang97bedb82020-10-10 11:11:35 -0700224 if (salt_len == 0) {
Zhiyi Zhanga2ce5992019-08-14 17:35:00 -0700225 uint8_t realSalt[HASH_SIZE] = {0};
Zhiyi Zhang97bedb82020-10-10 11:11:35 -0700226 hmac_sha256(secret, secret_len, realSalt, HASH_SIZE, prk);
Zhiyi Zhanga2ce5992019-08-14 17:35:00 -0700227 }
228 else {
Zhiyi Zhang97bedb82020-10-10 11:11:35 -0700229 hmac_sha256(secret, secret_len, salt, salt_len, prk);
Zhiyi Zhanga2ce5992019-08-14 17:35:00 -0700230 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700231
232 // hkdf expand
233 uint8_t prev[HASH_SIZE] = {0};
Zhiyi Zhang97bedb82020-10-10 11:11:35 -0700234 int done_len = 0, dig_len = HASH_SIZE, n = output_len / dig_len;
235 if (output_len % dig_len)
Davide Pesavento368341b2019-08-13 23:57:50 -0400236 n++;
Zhiyi Zhang97bedb82020-10-10 11:11:35 -0700237 if (n > 255 || output == nullptr)
Davide Pesavento368341b2019-08-13 23:57:50 -0400238 return 0;
239
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700240 for (int i = 1; i <= n; i++) {
241 size_t copy_len;
242 const uint8_t ctr = i;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700243
Davide Pesavento368341b2019-08-13 23:57:50 -0400244 t::StepSource source;
245 t::PrivateKey privKey;
246 privKey.loadRaw(KeyType::HMAC, prk, dig_len);
247 OBufferStream os;
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -0700248 source >> t::signerFilter(DigestAlgorithm::SHA256, privKey) >> t::streamSink(os);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700249
250 if (i > 1) {
251 source.write(prev, dig_len);
252 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700253 source.write(info, info_len);
254 source.write(&ctr, 1);
255 source.end();
256
257 auto result = os.buf();
258 memcpy(prev, result->data(), dig_len);
Zhiyi Zhang97bedb82020-10-10 11:11:35 -0700259 copy_len = (done_len + dig_len > output_len) ? output_len - done_len : dig_len;
260 memcpy(output + done_len, prev, copy_len);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700261 done_len += copy_len;
262 }
263 return done_len;
264}
265
Zhiyi Zhanga67fa462020-04-19 13:48:03 -0700266int
267aes_gcm_128_encrypt(const uint8_t* plaintext, size_t plaintext_len, const uint8_t* associated, size_t associated_len,
268 const uint8_t* key, const uint8_t* iv, uint8_t* ciphertext, uint8_t* tag)
269{
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -0700270 EVP_CIPHER_CTX* ctx;
Zhiyi Zhanga67fa462020-04-19 13:48:03 -0700271 int len;
272 int ciphertext_len;
273
274 // Create and initialise the context
275 if (!(ctx = EVP_CIPHER_CTX_new())) {
276 handleErrors("Cannot create and initialise the context when calling EVP_CIPHER_CTX_new()");
277 }
278
279 // Initialise the encryption operation.
280 if (1 != EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), nullptr, nullptr, nullptr)) {
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -0700281 handleErrors("Cannot initialise the encryption operation when calling EVP_EncryptInit_ex()");
Zhiyi Zhanga67fa462020-04-19 13:48:03 -0700282 }
283
284 // Set IV length if default 12 bytes (96 bits) is not appropriate
285 if (1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 12, nullptr)) {
286 handleErrors("Cannot set IV length when calling EVP_CIPHER_CTX_ctrl()");
287 }
288
289 // Initialise key and IV
290 if (1 != EVP_EncryptInit_ex(ctx, nullptr, nullptr, key, iv)) {
291 handleErrors("Cannot initialize key and IV when calling EVP_EncryptInit_ex()");
292 }
293
294 // Provide any AAD data. This can be called zero or more times as required
295 if (1 != EVP_EncryptUpdate(ctx, nullptr, &len, associated, associated_len)) {
296 handleErrors("Cannot set associated authentication data when calling EVP_EncryptUpdate()");
297 }
298
299 // Provide the message to be encrypted, and obtain the encrypted output.
300 // EVP_EncryptUpdate can be called multiple times if necessary
301 if (1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len)) {
302 handleErrors("Cannot encrypt when calling EVP_EncryptUpdate()");
303 }
304 ciphertext_len = len;
305
306 // Finalise the encryption. Normally ciphertext bytes may be written at
307 // this stage, but this does not occur in GCM mode
308 if (1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) {
309 handleErrors("Cannot finalise the encryption when calling EVP_EncryptFinal_ex()");
310 }
311 ciphertext_len += len;
312
313 // Get the tag
314 if (1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, 16, tag)) {
315 handleErrors("Cannot get tag when calling EVP_CIPHER_CTX_ctrl()");
316 }
317
318 // Clean up
319 EVP_CIPHER_CTX_free(ctx);
320 return ciphertext_len;
321}
322
323int
324aes_gcm_128_decrypt(const uint8_t* ciphertext, size_t ciphertext_len, const uint8_t* associated, size_t associated_len,
325 const uint8_t* tag, const uint8_t* key, const uint8_t* iv, uint8_t* plaintext)
326{
327 EVP_CIPHER_CTX* ctx;
328 int len;
329 int plaintext_len;
330 int ret;
331
332 // Create and initialise the context
333 if (!(ctx = EVP_CIPHER_CTX_new())) {
334 handleErrors("Cannot create and initialise the context when calling EVP_CIPHER_CTX_new()");
335 }
336
337 // Initialise the decryption operation.
338 if (!EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), nullptr, nullptr, nullptr)) {
339 handleErrors("Cannot initialise the decryption operation when calling EVP_DecryptInit_ex()");
340 }
341
342 // Set IV length. Not necessary if this is 12 bytes (96 bits)
343 if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 12, nullptr)) {
344 handleErrors("Cannot set IV length when calling EVP_CIPHER_CTX_ctrl");
345 }
346
347 // Initialise key and IV
348 if (!EVP_DecryptInit_ex(ctx, nullptr, nullptr, key, iv)) {
349 handleErrors("Cannot initialise key and IV when calling EVP_DecryptInit_ex()");
350 }
351
352 // Provide any AAD data. This can be called zero or more times as required
353 if (!EVP_DecryptUpdate(ctx, nullptr, &len, associated, associated_len)) {
354 handleErrors("Cannot set associated authentication data when calling EVP_EncryptUpdate()");
355 }
356
357 // Provide the message to be decrypted, and obtain the plaintext output.
358 // EVP_DecryptUpdate can be called multiple times if necessary
359 if (!EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len)) {
360 handleErrors("Cannot decrypt when calling EVP_DecryptUpdate()");
361 }
362 plaintext_len = len;
363
364 // Set expected tag value. Works in OpenSSL 1.0.1d and later
365 if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, 16, (void*)tag)) {
366 handleErrors("Cannot set tag value when calling EVP_CIPHER_CTX_ctrl");
367 }
368
369 // Finalise the decryption. A positive return value indicates success,
370 // anything else is a failure - the plaintext is not trustworthy.
371 ret = EVP_DecryptFinal_ex(ctx, plaintext + len, &len);
372
373 // Clean up
374 EVP_CIPHER_CTX_free(ctx);
375
376 if (ret > 0) {
377 // Success
378 plaintext_len += len;
379 return plaintext_len;
380 }
381 else {
382 // Verify failed
383 return -1;
384 }
385}
386
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700387void
388handleErrors(const std::string& errorInfo)
389{
Zhiyi Zhangd61b4a82020-10-10 15:18:43 -0700390 NDN_LOG_DEBUG("Error in CRYPTO SUPPORT " << errorInfo);
Zhiyi Zhangccd5a0c2020-10-12 13:48:16 -0700391 NDN_THROW(std::runtime_error("Error in CRYPTO SUPPORT: " + errorInfo));
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700392}
393
Zhiyi Zhange4891b72020-10-10 15:11:57 -0700394} // namespace ndncert
395} // namespace ndn