blob: c93a29c27c4e213b0b75105e781a226f8b134a2c [file] [log] [blame]
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -07001/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
Davide Pesavento368341b2019-08-13 23:57:50 -04002/*
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -07003 * Copyright (c) 2017-2019, Regents of the University of California.
4 *
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>
26
27#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
41_LOG_INIT(crypto-support);
42
43ECDHState::ECDHState()
44{
45 OpenSSL_add_all_algorithms();
46 context = std::make_unique<ECDH_CTX>();
47 context->EC_NID = NID_X9_62_prime256v1;
48
49 // Create the context for parameter generation
50 if (nullptr == (context->ctx_params = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, nullptr))) {
51 handleErrors("Could not create context contexts.");
52 return;
53 }
54
55 // Initialise the parameter generation
56 if (EVP_PKEY_paramgen_init(context->ctx_params) != 1) {
57 handleErrors("Could not initialize parameter generation.");
58 return;
59 }
60
61 // We're going to use the ANSI X9.62 Prime 256v1 curve
62 if (1 != EVP_PKEY_CTX_set_ec_paramgen_curve_nid(context->ctx_params, context->EC_NID)) {
63 handleErrors("Likely unknown elliptical curve ID specified.");
64 return;
65 }
66
67 // Create the parameter object params
68 if (!EVP_PKEY_paramgen(context->ctx_params, &context->params)) {
69 // the generated key is written to context->params
70 handleErrors("Could not create parameter object parameters.");
71 return;
72 }
73
74 // Create the context for the key generation
75 if (nullptr == (context->ctx_keygen = EVP_PKEY_CTX_new(context->params, nullptr))) {
76 //The EVP_PKEY_CTX_new() function allocates public key algorithm context using
77 //the algorithm specified in pkey and ENGINE e (in this case nullptr).
78 handleErrors("Could not create the context for the key generation");
79 return;
80 }
81
82 // initializes a public key algorithm context
83 if (1 != EVP_PKEY_keygen_init(context->ctx_keygen)){
84 handleErrors("Could not init context for key generation.");
85 return;
86 }
87 if (1 != EVP_PKEY_keygen(context->ctx_keygen, &context->privkey)) {
88 //performs a key generation operation, the generated key is written to context->privkey.
89 handleErrors("Could not generate DHE keys in final step");
90 return;
91 }
92}
93
94ECDHState::~ECDHState()
95{
96 // Contexts
97 if(context->ctx_params != nullptr){
98 EVP_PKEY_CTX_free(context->ctx_params);
99 }
100 if(context->ctx_keygen != nullptr){
101 EVP_PKEY_CTX_free(context->ctx_keygen);
102 }
103
104 // Keys
105 if(context->privkey != nullptr){
106 EVP_PKEY_free(context->privkey);
107 }
108 if(context->peerkey != nullptr){
109 EVP_PKEY_free(context->peerkey);
110 }
111 if(context->params != nullptr){
112 EVP_PKEY_free(context->params);
113 }
114}
115
116uint8_t*
117ECDHState::getRawSelfPubKey()
118{
119 auto privECKey = EVP_PKEY_get1_EC_KEY(context->privkey);
120
121 if (privECKey == nullptr) {
122 handleErrors("Could not get referenced key when calling EVP_PKEY_get1_EC_KEY().");
123 return nullptr;
124 }
125
126 auto ecPoint = EC_KEY_get0_public_key(privECKey);
127 const EC_GROUP* group = EC_KEY_get0_group(privECKey);
128 context->publicKeyLen = EC_POINT_point2oct(group, ecPoint, POINT_CONVERSION_COMPRESSED,
129 context->publicKey, 256, nullptr);
130 EC_KEY_free(privECKey);
131 if (context->publicKeyLen == 0) {
132 handleErrors("Could not convert EC_POINTS to octet string when calling EC_POINT_point2oct.");
133 return nullptr;
134 }
135
136 return context->publicKey;
137}
138
139std::string
140ECDHState::getBase64PubKey()
141{
Davide Pesavento368341b2019-08-13 23:57:50 -0400142 namespace t = ndn::security::transform;
143
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700144 if (context->publicKeyLen == 0) {
145 this->getRawSelfPubKey();
146 }
Davide Pesavento368341b2019-08-13 23:57:50 -0400147
148 std::ostringstream os;
149 t::bufferSource(context->publicKey, context->publicKeyLen)
150 >> t::base64Encode()
151 >> t::streamSink(os);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700152 return os.str();
153}
154
155uint8_t*
156ECDHState::deriveSecret(const uint8_t* peerkey, int peerKeySize)
157{
158 auto privECKey = EVP_PKEY_get1_EC_KEY(context->privkey);
159
160 if (privECKey == nullptr) {
161 handleErrors("Could not get referenced key when calling EVP_PKEY_get1_EC_KEY().");
162 return nullptr;
163 }
164
165 auto group = EC_KEY_get0_group(privECKey);
166 auto peerPoint = EC_POINT_new(group);
167 EC_POINT_oct2point(group, peerPoint, peerkey, peerKeySize, nullptr);
168
169 if (0 == (context->sharedSecretLen = ECDH_compute_key(context->sharedSecret, 256,
170 peerPoint, privECKey, nullptr))) {
171 EC_POINT_free(peerPoint);
172 EC_KEY_free(privECKey);
173 handleErrors("Cannot generate ECDH secret with ECDH_compute_key");
174 }
175 EC_POINT_free(peerPoint);
176 EC_KEY_free(privECKey);
177 return context->sharedSecret;
178}
179
180uint8_t*
181ECDHState::deriveSecret(const std::string& peerKeyStr)
182{
183 namespace t = ndn::security::transform;
Davide Pesavento368341b2019-08-13 23:57:50 -0400184
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700185 OBufferStream os;
Davide Pesavento368341b2019-08-13 23:57:50 -0400186 t::bufferSource(peerKeyStr) >> t::base64Decode() >> t::streamSink(os);
187 auto result = os.buf();
188
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700189 return this->deriveSecret(result->data(), result->size());
190}
191
Davide Pesavento368341b2019-08-13 23:57:50 -0400192int
193ndn_compute_hmac_sha256(const uint8_t *data, const unsigned data_length,
194 const uint8_t *key, const unsigned key_length,
195 uint8_t *prk)
196{
197 namespace t = ndn::security::transform;
198
199 t::PrivateKey privKey;
200 privKey.loadRaw(KeyType::HMAC, key, key_length);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700201 OBufferStream os;
202
Davide Pesavento368341b2019-08-13 23:57:50 -0400203 t::bufferSource(data, data_length)
204 >> t::signerFilter(DigestAlgorithm::SHA256, privKey)
205 >> t::streamSink(os);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700206
Davide Pesavento368341b2019-08-13 23:57:50 -0400207 memcpy(prk, os.buf()->data(), HASH_SIZE);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700208 return 0;
209}
210
Davide Pesavento368341b2019-08-13 23:57:50 -0400211// avoid dependency on OpenSSL >= 1.1
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700212int
213hkdf(const uint8_t* secret, int secretLen, const uint8_t* salt,
214 int saltLen, uint8_t* okm, int okm_len,
215 const uint8_t* info, int info_len)
216{
Davide Pesavento368341b2019-08-13 23:57:50 -0400217 namespace t = ndn::security::transform;
218
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700219 // hkdf generate prk
220 uint8_t prk[HASH_SIZE];
221 ndn_compute_hmac_sha256(salt, saltLen, secret, secretLen, prk);
222
223 // hkdf expand
224 uint8_t prev[HASH_SIZE] = {0};
225 int done_len = 0, dig_len = HASH_SIZE, n = okm_len / dig_len;
Davide Pesavento368341b2019-08-13 23:57:50 -0400226 if (okm_len % dig_len)
227 n++;
228 if (n > 255 || okm == nullptr)
229 return 0;
230
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700231 for (int i = 1; i <= n; i++) {
232 size_t copy_len;
233 const uint8_t ctr = i;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700234
Davide Pesavento368341b2019-08-13 23:57:50 -0400235 t::StepSource source;
236 t::PrivateKey privKey;
237 privKey.loadRaw(KeyType::HMAC, prk, dig_len);
238 OBufferStream os;
239 source >> t::signerFilter(DigestAlgorithm::SHA256, privKey)
240 >> t::streamSink(os);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700241
242 if (i > 1) {
243 source.write(prev, dig_len);
244 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700245 source.write(info, info_len);
246 source.write(&ctr, 1);
247 source.end();
248
249 auto result = os.buf();
250 memcpy(prev, result->data(), dig_len);
Davide Pesavento368341b2019-08-13 23:57:50 -0400251 copy_len = (done_len + dig_len > okm_len) ? okm_len - done_len : dig_len;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700252 memcpy(okm + done_len, prev, copy_len);
253 done_len += copy_len;
254 }
255 return done_len;
256}
257
258void
259handleErrors(const std::string& errorInfo)
260{
261 _LOG_DEBUG("Error in CRYPTO SUPPORT " << errorInfo);
262 BOOST_THROW_EXCEPTION(CryptoError("Error in CRYPTO SUPPORT: " + errorInfo));
263}
264
265} // namespace ndncert
266} // namespace ndn