blob: 8fba982e7244784254f3b612ae5e6d441316a8c2 [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"
22#include "../logging.hpp"
Davide Pesavento368341b2019-08-13 23:57:50 -040023
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070024#include <openssl/err.h>
Zhiyi Zhanga2ce5992019-08-14 17:35:00 -070025#include <openssl/hmac.h>
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -070026#include <openssl/pem.h>
Davide Pesavento368341b2019-08-13 23:57:50 -040027
28#include <ndn-cxx/encoding/buffer-stream.hpp>
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070029#include <ndn-cxx/security/transform/base64-decode.hpp>
30#include <ndn-cxx/security/transform/base64-encode.hpp>
31#include <ndn-cxx/security/transform/buffer-source.hpp>
Davide Pesavento368341b2019-08-13 23:57:50 -040032#include <ndn-cxx/security/transform/private-key.hpp>
33#include <ndn-cxx/security/transform/signer-filter.hpp>
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070034#include <ndn-cxx/security/transform/step-source.hpp>
35#include <ndn-cxx/security/transform/stream-sink.hpp>
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070036
37namespace ndn {
38namespace ndncert {
39
40const size_t HASH_SIZE = 32;
41
42_LOG_INIT(crypto-support);
43
44ECDHState::ECDHState()
45{
46 OpenSSL_add_all_algorithms();
47 context = std::make_unique<ECDH_CTX>();
48 context->EC_NID = NID_X9_62_prime256v1;
49
50 // Create the context for parameter generation
51 if (nullptr == (context->ctx_params = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, nullptr))) {
52 handleErrors("Could not create context contexts.");
53 return;
54 }
55
56 // Initialise the parameter generation
57 if (EVP_PKEY_paramgen_init(context->ctx_params) != 1) {
58 handleErrors("Could not initialize parameter generation.");
59 return;
60 }
61
62 // We're going to use the ANSI X9.62 Prime 256v1 curve
63 if (1 != EVP_PKEY_CTX_set_ec_paramgen_curve_nid(context->ctx_params, context->EC_NID)) {
64 handleErrors("Likely unknown elliptical curve ID specified.");
65 return;
66 }
67
68 // Create the parameter object params
69 if (!EVP_PKEY_paramgen(context->ctx_params, &context->params)) {
70 // the generated key is written to context->params
71 handleErrors("Could not create parameter object parameters.");
72 return;
73 }
74
75 // Create the context for the key generation
76 if (nullptr == (context->ctx_keygen = EVP_PKEY_CTX_new(context->params, nullptr))) {
77 //The EVP_PKEY_CTX_new() function allocates public key algorithm context using
78 //the algorithm specified in pkey and ENGINE e (in this case nullptr).
79 handleErrors("Could not create the context for the key generation");
80 return;
81 }
82
83 // initializes a public key algorithm context
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -070084 if (1 != EVP_PKEY_keygen_init(context->ctx_keygen)) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070085 handleErrors("Could not init context for key generation.");
86 return;
87 }
88 if (1 != EVP_PKEY_keygen(context->ctx_keygen, &context->privkey)) {
89 //performs a key generation operation, the generated key is written to context->privkey.
90 handleErrors("Could not generate DHE keys in final step");
91 return;
92 }
93}
94
95ECDHState::~ECDHState()
96{
97 // Contexts
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -070098 if (context->ctx_params != nullptr) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070099 EVP_PKEY_CTX_free(context->ctx_params);
100 }
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -0700101 if (context->ctx_keygen != nullptr) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700102 EVP_PKEY_CTX_free(context->ctx_keygen);
103 }
104
105 // Keys
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -0700106 if (context->privkey != nullptr) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700107 EVP_PKEY_free(context->privkey);
108 }
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -0700109 if (context->peerkey != nullptr) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700110 EVP_PKEY_free(context->peerkey);
111 }
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -0700112 if (context->params != nullptr) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700113 EVP_PKEY_free(context->params);
114 }
115}
116
117uint8_t*
118ECDHState::getRawSelfPubKey()
119{
120 auto privECKey = EVP_PKEY_get1_EC_KEY(context->privkey);
121
122 if (privECKey == nullptr) {
123 handleErrors("Could not get referenced key when calling EVP_PKEY_get1_EC_KEY().");
124 return nullptr;
125 }
126
127 auto ecPoint = EC_KEY_get0_public_key(privECKey);
128 const EC_GROUP* group = EC_KEY_get0_group(privECKey);
129 context->publicKeyLen = EC_POINT_point2oct(group, ecPoint, POINT_CONVERSION_COMPRESSED,
130 context->publicKey, 256, nullptr);
131 EC_KEY_free(privECKey);
132 if (context->publicKeyLen == 0) {
133 handleErrors("Could not convert EC_POINTS to octet string when calling EC_POINT_point2oct.");
134 return nullptr;
135 }
136
137 return context->publicKey;
138}
139
140std::string
141ECDHState::getBase64PubKey()
142{
Davide Pesavento368341b2019-08-13 23:57:50 -0400143 namespace t = ndn::security::transform;
144
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700145 if (context->publicKeyLen == 0) {
146 this->getRawSelfPubKey();
147 }
Davide Pesavento368341b2019-08-13 23:57:50 -0400148
149 std::ostringstream os;
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -0700150 t::bufferSource(context->publicKey, context->publicKeyLen) >> t::base64Encode(false) >> t::streamSink(os);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700151 return os.str();
152}
153
154uint8_t*
155ECDHState::deriveSecret(const uint8_t* peerkey, int peerKeySize)
156{
157 auto privECKey = EVP_PKEY_get1_EC_KEY(context->privkey);
158
159 if (privECKey == nullptr) {
Zhiyi Zhang8da54d62019-11-21 00:03:05 -0800160 handleErrors("Could not get referenced key when calling EVP_PKEY_get1_EC_KEY()");
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700161 return nullptr;
162 }
163
164 auto group = EC_KEY_get0_group(privECKey);
165 auto peerPoint = EC_POINT_new(group);
Zhiyi Zhang8da54d62019-11-21 00:03:05 -0800166 int result = EC_POINT_oct2point(group, peerPoint, peerkey, peerKeySize, nullptr);
167 if (result == 0) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700168 EC_POINT_free(peerPoint);
169 EC_KEY_free(privECKey);
Zhiyi Zhang8da54d62019-11-21 00:03:05 -0800170 handleErrors("Cannot convert peer's key into a EC point when calling EC_POINT_oct2point()");
171 }
172
173 if (-1 == (context->sharedSecretLen = ECDH_compute_key(context->sharedSecret, 256,
174 peerPoint, privECKey, nullptr))) {
175 EC_POINT_free(peerPoint);
176 EC_KEY_free(privECKey);
177 handleErrors("Cannot generate ECDH secret when calling ECDH_compute_key()");
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700178 }
179 EC_POINT_free(peerPoint);
180 EC_KEY_free(privECKey);
181 return context->sharedSecret;
182}
183
184uint8_t*
185ECDHState::deriveSecret(const std::string& peerKeyStr)
186{
187 namespace t = ndn::security::transform;
Davide Pesavento368341b2019-08-13 23:57:50 -0400188
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700189 OBufferStream os;
Zhiyi Zhang8da54d62019-11-21 00:03:05 -0800190 t::bufferSource(peerKeyStr) >> t::base64Decode(false) >> t::streamSink(os);
Davide Pesavento368341b2019-08-13 23:57:50 -0400191 auto result = os.buf();
192
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700193 return this->deriveSecret(result->data(), result->size());
194}
195
Davide Pesavento368341b2019-08-13 23:57:50 -0400196int
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -0700197ndn_compute_hmac_sha256(const uint8_t* data, const unsigned data_length,
198 const uint8_t* key, const unsigned key_length,
199 uint8_t* prk)
Davide Pesavento368341b2019-08-13 23:57:50 -0400200{
Zhiyi Zhanga2ce5992019-08-14 17:35:00 -0700201 HMAC(EVP_sha256(), key, key_length,
202 (unsigned char*)data, data_length,
203 (unsigned char*)prk, nullptr);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700204 return 0;
205}
206
Davide Pesavento368341b2019-08-13 23:57:50 -0400207// avoid dependency on OpenSSL >= 1.1
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700208int
209hkdf(const uint8_t* secret, int secretLen, const uint8_t* salt,
210 int saltLen, uint8_t* okm, int okm_len,
211 const uint8_t* info, int info_len)
212{
Davide Pesavento368341b2019-08-13 23:57:50 -0400213 namespace t = ndn::security::transform;
214
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700215 // hkdf generate prk
216 uint8_t prk[HASH_SIZE];
Zhiyi Zhanga2ce5992019-08-14 17:35:00 -0700217 if (saltLen == 0) {
218 uint8_t realSalt[HASH_SIZE] = {0};
219 ndn_compute_hmac_sha256(secret, secretLen, realSalt, HASH_SIZE, prk);
220 }
221 else {
222 ndn_compute_hmac_sha256(secret, secretLen, salt, saltLen, prk);
223 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700224
225 // hkdf expand
226 uint8_t prev[HASH_SIZE] = {0};
227 int done_len = 0, dig_len = HASH_SIZE, n = okm_len / dig_len;
Davide Pesavento368341b2019-08-13 23:57:50 -0400228 if (okm_len % dig_len)
229 n++;
230 if (n > 255 || okm == nullptr)
231 return 0;
232
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700233 for (int i = 1; i <= n; i++) {
234 size_t copy_len;
235 const uint8_t ctr = i;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700236
Davide Pesavento368341b2019-08-13 23:57:50 -0400237 t::StepSource source;
238 t::PrivateKey privKey;
239 privKey.loadRaw(KeyType::HMAC, prk, dig_len);
240 OBufferStream os;
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -0700241 source >> t::signerFilter(DigestAlgorithm::SHA256, privKey) >> t::streamSink(os);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700242
243 if (i > 1) {
244 source.write(prev, dig_len);
245 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700246 source.write(info, info_len);
247 source.write(&ctr, 1);
248 source.end();
249
250 auto result = os.buf();
251 memcpy(prev, result->data(), dig_len);
Davide Pesavento368341b2019-08-13 23:57:50 -0400252 copy_len = (done_len + dig_len > okm_len) ? okm_len - done_len : dig_len;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700253 memcpy(okm + done_len, prev, copy_len);
254 done_len += copy_len;
255 }
256 return done_len;
257}
258
Zhiyi Zhanga67fa462020-04-19 13:48:03 -0700259int
260aes_gcm_128_encrypt(const uint8_t* plaintext, size_t plaintext_len, const uint8_t* associated, size_t associated_len,
261 const uint8_t* key, const uint8_t* iv, uint8_t* ciphertext, uint8_t* tag)
262{
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -0700263 EVP_CIPHER_CTX* ctx;
Zhiyi Zhanga67fa462020-04-19 13:48:03 -0700264 int len;
265 int ciphertext_len;
266
267 // Create and initialise the context
268 if (!(ctx = EVP_CIPHER_CTX_new())) {
269 handleErrors("Cannot create and initialise the context when calling EVP_CIPHER_CTX_new()");
270 }
271
272 // Initialise the encryption operation.
273 if (1 != EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), nullptr, nullptr, nullptr)) {
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -0700274 handleErrors("Cannot initialise the encryption operation when calling EVP_EncryptInit_ex()");
Zhiyi Zhanga67fa462020-04-19 13:48:03 -0700275 }
276
277 // Set IV length if default 12 bytes (96 bits) is not appropriate
278 if (1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 12, nullptr)) {
279 handleErrors("Cannot set IV length when calling EVP_CIPHER_CTX_ctrl()");
280 }
281
282 // Initialise key and IV
283 if (1 != EVP_EncryptInit_ex(ctx, nullptr, nullptr, key, iv)) {
284 handleErrors("Cannot initialize key and IV when calling EVP_EncryptInit_ex()");
285 }
286
287 // Provide any AAD data. This can be called zero or more times as required
288 if (1 != EVP_EncryptUpdate(ctx, nullptr, &len, associated, associated_len)) {
289 handleErrors("Cannot set associated authentication data when calling EVP_EncryptUpdate()");
290 }
291
292 // Provide the message to be encrypted, and obtain the encrypted output.
293 // EVP_EncryptUpdate can be called multiple times if necessary
294 if (1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len)) {
295 handleErrors("Cannot encrypt when calling EVP_EncryptUpdate()");
296 }
297 ciphertext_len = len;
298
299 // Finalise the encryption. Normally ciphertext bytes may be written at
300 // this stage, but this does not occur in GCM mode
301 if (1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) {
302 handleErrors("Cannot finalise the encryption when calling EVP_EncryptFinal_ex()");
303 }
304 ciphertext_len += len;
305
306 // Get the tag
307 if (1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, 16, tag)) {
308 handleErrors("Cannot get tag when calling EVP_CIPHER_CTX_ctrl()");
309 }
310
311 // Clean up
312 EVP_CIPHER_CTX_free(ctx);
313 return ciphertext_len;
314}
315
316int
317aes_gcm_128_decrypt(const uint8_t* ciphertext, size_t ciphertext_len, const uint8_t* associated, size_t associated_len,
318 const uint8_t* tag, const uint8_t* key, const uint8_t* iv, uint8_t* plaintext)
319{
320 EVP_CIPHER_CTX* ctx;
321 int len;
322 int plaintext_len;
323 int ret;
324
325 // Create and initialise the context
326 if (!(ctx = EVP_CIPHER_CTX_new())) {
327 handleErrors("Cannot create and initialise the context when calling EVP_CIPHER_CTX_new()");
328 }
329
330 // Initialise the decryption operation.
331 if (!EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), nullptr, nullptr, nullptr)) {
332 handleErrors("Cannot initialise the decryption operation when calling EVP_DecryptInit_ex()");
333 }
334
335 // Set IV length. Not necessary if this is 12 bytes (96 bits)
336 if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 12, nullptr)) {
337 handleErrors("Cannot set IV length when calling EVP_CIPHER_CTX_ctrl");
338 }
339
340 // Initialise key and IV
341 if (!EVP_DecryptInit_ex(ctx, nullptr, nullptr, key, iv)) {
342 handleErrors("Cannot initialise key and IV when calling EVP_DecryptInit_ex()");
343 }
344
345 // Provide any AAD data. This can be called zero or more times as required
346 if (!EVP_DecryptUpdate(ctx, nullptr, &len, associated, associated_len)) {
347 handleErrors("Cannot set associated authentication data when calling EVP_EncryptUpdate()");
348 }
349
350 // Provide the message to be decrypted, and obtain the plaintext output.
351 // EVP_DecryptUpdate can be called multiple times if necessary
352 if (!EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len)) {
353 handleErrors("Cannot decrypt when calling EVP_DecryptUpdate()");
354 }
355 plaintext_len = len;
356
357 // Set expected tag value. Works in OpenSSL 1.0.1d and later
358 if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, 16, (void*)tag)) {
359 handleErrors("Cannot set tag value when calling EVP_CIPHER_CTX_ctrl");
360 }
361
362 // Finalise the decryption. A positive return value indicates success,
363 // anything else is a failure - the plaintext is not trustworthy.
364 ret = EVP_DecryptFinal_ex(ctx, plaintext + len, &len);
365
366 // Clean up
367 EVP_CIPHER_CTX_free(ctx);
368
369 if (ret > 0) {
370 // Success
371 plaintext_len += len;
372 return plaintext_len;
373 }
374 else {
375 // Verify failed
376 return -1;
377 }
378}
379
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700380void
381handleErrors(const std::string& errorInfo)
382{
383 _LOG_DEBUG("Error in CRYPTO SUPPORT " << errorInfo);
384 BOOST_THROW_EXCEPTION(CryptoError("Error in CRYPTO SUPPORT: " + errorInfo));
385}
386
Zhiyi Zhangb8cb0472020-05-05 20:55:05 -0700387} // namespace ndncert
388} // namespace ndn