blob: 297bbefed4bafb390e614a51066714ff58b8f731 [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>
Davide Pesavento368341b2019-08-13 23:57:50 -040025#include <openssl/pem.h>
Zhiyi Zhanga2ce5992019-08-14 17:35:00 -070026#include <openssl/hmac.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
84 if (1 != EVP_PKEY_keygen_init(context->ctx_keygen)){
85 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
98 if(context->ctx_params != nullptr){
99 EVP_PKEY_CTX_free(context->ctx_params);
100 }
101 if(context->ctx_keygen != nullptr){
102 EVP_PKEY_CTX_free(context->ctx_keygen);
103 }
104
105 // Keys
106 if(context->privkey != nullptr){
107 EVP_PKEY_free(context->privkey);
108 }
109 if(context->peerkey != nullptr){
110 EVP_PKEY_free(context->peerkey);
111 }
112 if(context->params != nullptr){
113 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;
150 t::bufferSource(context->publicKey, context->publicKeyLen)
Zhiyi Zhang8da54d62019-11-21 00:03:05 -0800151 >> t::base64Encode(false)
Davide Pesavento368341b2019-08-13 23:57:50 -0400152 >> t::streamSink(os);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700153 return os.str();
154}
155
156uint8_t*
157ECDHState::deriveSecret(const uint8_t* peerkey, int peerKeySize)
158{
159 auto privECKey = EVP_PKEY_get1_EC_KEY(context->privkey);
160
161 if (privECKey == nullptr) {
Zhiyi Zhang8da54d62019-11-21 00:03:05 -0800162 handleErrors("Could not get referenced key when calling EVP_PKEY_get1_EC_KEY()");
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700163 return nullptr;
164 }
165
166 auto group = EC_KEY_get0_group(privECKey);
167 auto peerPoint = EC_POINT_new(group);
Zhiyi Zhang8da54d62019-11-21 00:03:05 -0800168 int result = EC_POINT_oct2point(group, peerPoint, peerkey, peerKeySize, nullptr);
169 if (result == 0) {
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700170 EC_POINT_free(peerPoint);
171 EC_KEY_free(privECKey);
Zhiyi Zhang8da54d62019-11-21 00:03:05 -0800172 handleErrors("Cannot convert peer's key into a EC point when calling EC_POINT_oct2point()");
173 }
174
175 if (-1 == (context->sharedSecretLen = ECDH_compute_key(context->sharedSecret, 256,
176 peerPoint, privECKey, nullptr))) {
177 EC_POINT_free(peerPoint);
178 EC_KEY_free(privECKey);
179 handleErrors("Cannot generate ECDH secret when calling ECDH_compute_key()");
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700180 }
181 EC_POINT_free(peerPoint);
182 EC_KEY_free(privECKey);
183 return context->sharedSecret;
184}
185
186uint8_t*
187ECDHState::deriveSecret(const std::string& peerKeyStr)
188{
189 namespace t = ndn::security::transform;
Davide Pesavento368341b2019-08-13 23:57:50 -0400190
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700191 OBufferStream os;
Zhiyi Zhang8da54d62019-11-21 00:03:05 -0800192 t::bufferSource(peerKeyStr) >> t::base64Decode(false) >> t::streamSink(os);
Davide Pesavento368341b2019-08-13 23:57:50 -0400193 auto result = os.buf();
194
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700195 return this->deriveSecret(result->data(), result->size());
196}
197
Davide Pesavento368341b2019-08-13 23:57:50 -0400198int
199ndn_compute_hmac_sha256(const uint8_t *data, const unsigned data_length,
200 const uint8_t *key, const unsigned key_length,
201 uint8_t *prk)
202{
Zhiyi Zhanga2ce5992019-08-14 17:35:00 -0700203 HMAC(EVP_sha256(), key, key_length,
204 (unsigned char*)data, data_length,
205 (unsigned char*)prk, nullptr);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700206 return 0;
207}
208
Davide Pesavento368341b2019-08-13 23:57:50 -0400209// avoid dependency on OpenSSL >= 1.1
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700210int
211hkdf(const uint8_t* secret, int secretLen, const uint8_t* salt,
212 int saltLen, uint8_t* okm, int okm_len,
213 const uint8_t* info, int info_len)
214{
Davide Pesavento368341b2019-08-13 23:57:50 -0400215 namespace t = ndn::security::transform;
216
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700217 // hkdf generate prk
218 uint8_t prk[HASH_SIZE];
Zhiyi Zhanga2ce5992019-08-14 17:35:00 -0700219 if (saltLen == 0) {
220 uint8_t realSalt[HASH_SIZE] = {0};
221 ndn_compute_hmac_sha256(secret, secretLen, realSalt, HASH_SIZE, prk);
222 }
223 else {
224 ndn_compute_hmac_sha256(secret, secretLen, salt, saltLen, prk);
225 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700226
227 // hkdf expand
228 uint8_t prev[HASH_SIZE] = {0};
229 int done_len = 0, dig_len = HASH_SIZE, n = okm_len / dig_len;
Davide Pesavento368341b2019-08-13 23:57:50 -0400230 if (okm_len % dig_len)
231 n++;
232 if (n > 255 || okm == nullptr)
233 return 0;
234
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700235 for (int i = 1; i <= n; i++) {
236 size_t copy_len;
237 const uint8_t ctr = i;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700238
Davide Pesavento368341b2019-08-13 23:57:50 -0400239 t::StepSource source;
240 t::PrivateKey privKey;
241 privKey.loadRaw(KeyType::HMAC, prk, dig_len);
242 OBufferStream os;
243 source >> t::signerFilter(DigestAlgorithm::SHA256, privKey)
244 >> t::streamSink(os);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700245
246 if (i > 1) {
247 source.write(prev, dig_len);
248 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700249 source.write(info, info_len);
250 source.write(&ctr, 1);
251 source.end();
252
253 auto result = os.buf();
254 memcpy(prev, result->data(), dig_len);
Davide Pesavento368341b2019-08-13 23:57:50 -0400255 copy_len = (done_len + dig_len > okm_len) ? okm_len - done_len : dig_len;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700256 memcpy(okm + done_len, prev, copy_len);
257 done_len += copy_len;
258 }
259 return done_len;
260}
261
Zhiyi Zhanga67fa462020-04-19 13:48:03 -0700262int
263aes_gcm_128_encrypt(const uint8_t* plaintext, size_t plaintext_len, const uint8_t* associated, size_t associated_len,
264 const uint8_t* key, const uint8_t* iv, uint8_t* ciphertext, uint8_t* tag)
265{
266 EVP_CIPHER_CTX *ctx;
267 int len;
268 int ciphertext_len;
269
270 // Create and initialise the context
271 if (!(ctx = EVP_CIPHER_CTX_new())) {
272 handleErrors("Cannot create and initialise the context when calling EVP_CIPHER_CTX_new()");
273 }
274
275 // Initialise the encryption operation.
276 if (1 != EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), nullptr, nullptr, nullptr)) {
277 handleErrors("Cannot initialise the encryption operation when calling EVP_EncryptInit_ex()");
278 }
279
280 // Set IV length if default 12 bytes (96 bits) is not appropriate
281 if (1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 12, nullptr)) {
282 handleErrors("Cannot set IV length when calling EVP_CIPHER_CTX_ctrl()");
283 }
284
285 // Initialise key and IV
286 if (1 != EVP_EncryptInit_ex(ctx, nullptr, nullptr, key, iv)) {
287 handleErrors("Cannot initialize key and IV when calling EVP_EncryptInit_ex()");
288 }
289
290 // Provide any AAD data. This can be called zero or more times as required
291 if (1 != EVP_EncryptUpdate(ctx, nullptr, &len, associated, associated_len)) {
292 handleErrors("Cannot set associated authentication data when calling EVP_EncryptUpdate()");
293 }
294
295 // Provide the message to be encrypted, and obtain the encrypted output.
296 // EVP_EncryptUpdate can be called multiple times if necessary
297 if (1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len)) {
298 handleErrors("Cannot encrypt when calling EVP_EncryptUpdate()");
299 }
300 ciphertext_len = len;
301
302 // Finalise the encryption. Normally ciphertext bytes may be written at
303 // this stage, but this does not occur in GCM mode
304 if (1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) {
305 handleErrors("Cannot finalise the encryption when calling EVP_EncryptFinal_ex()");
306 }
307 ciphertext_len += len;
308
309 // Get the tag
310 if (1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, 16, tag)) {
311 handleErrors("Cannot get tag when calling EVP_CIPHER_CTX_ctrl()");
312 }
313
314 // Clean up
315 EVP_CIPHER_CTX_free(ctx);
316 return ciphertext_len;
317}
318
319int
320aes_gcm_128_decrypt(const uint8_t* ciphertext, size_t ciphertext_len, const uint8_t* associated, size_t associated_len,
321 const uint8_t* tag, const uint8_t* key, const uint8_t* iv, uint8_t* plaintext)
322{
323 EVP_CIPHER_CTX* ctx;
324 int len;
325 int plaintext_len;
326 int ret;
327
328 // Create and initialise the context
329 if (!(ctx = EVP_CIPHER_CTX_new())) {
330 handleErrors("Cannot create and initialise the context when calling EVP_CIPHER_CTX_new()");
331 }
332
333 // Initialise the decryption operation.
334 if (!EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), nullptr, nullptr, nullptr)) {
335 handleErrors("Cannot initialise the decryption operation when calling EVP_DecryptInit_ex()");
336 }
337
338 // Set IV length. Not necessary if this is 12 bytes (96 bits)
339 if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 12, nullptr)) {
340 handleErrors("Cannot set IV length when calling EVP_CIPHER_CTX_ctrl");
341 }
342
343 // Initialise key and IV
344 if (!EVP_DecryptInit_ex(ctx, nullptr, nullptr, key, iv)) {
345 handleErrors("Cannot initialise key and IV when calling EVP_DecryptInit_ex()");
346 }
347
348 // Provide any AAD data. This can be called zero or more times as required
349 if (!EVP_DecryptUpdate(ctx, nullptr, &len, associated, associated_len)) {
350 handleErrors("Cannot set associated authentication data when calling EVP_EncryptUpdate()");
351 }
352
353 // Provide the message to be decrypted, and obtain the plaintext output.
354 // EVP_DecryptUpdate can be called multiple times if necessary
355 if (!EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len)) {
356 handleErrors("Cannot decrypt when calling EVP_DecryptUpdate()");
357 }
358 plaintext_len = len;
359
360 // Set expected tag value. Works in OpenSSL 1.0.1d and later
361 if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, 16, (void*)tag)) {
362 handleErrors("Cannot set tag value when calling EVP_CIPHER_CTX_ctrl");
363 }
364
365 // Finalise the decryption. A positive return value indicates success,
366 // anything else is a failure - the plaintext is not trustworthy.
367 ret = EVP_DecryptFinal_ex(ctx, plaintext + len, &len);
368
369 // Clean up
370 EVP_CIPHER_CTX_free(ctx);
371
372 if (ret > 0) {
373 // Success
374 plaintext_len += len;
375 return plaintext_len;
376 }
377 else {
378 // Verify failed
379 return -1;
380 }
381}
382
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700383void
384handleErrors(const std::string& errorInfo)
385{
386 _LOG_DEBUG("Error in CRYPTO SUPPORT " << errorInfo);
387 BOOST_THROW_EXCEPTION(CryptoError("Error in CRYPTO SUPPORT: " + errorInfo));
388}
389
390} // namespace ndncert
391} // namespace ndn