blob: 915f17c165809026c86e3b9a886bb29db10338d7 [file] [log] [blame]
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -07001/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2/**
3 * 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"
23#include <openssl/pem.h>
24#include <openssl/rand.h>
25#include <openssl/err.h>
26#include <ndn-cxx/security/transform/block-cipher.hpp>
27#include <ndn-cxx/security/transform/base64-decode.hpp>
28#include <ndn-cxx/security/transform/base64-encode.hpp>
29#include <ndn-cxx/security/transform/buffer-source.hpp>
30#include <ndn-cxx/security/transform/step-source.hpp>
31#include <ndn-cxx/security/transform/stream-sink.hpp>
32#include <ndn-cxx/util/random.hpp>
33#include <ndn-cxx/encoding/buffer-stream.hpp>
34#include <ndn-cxx/security/transform/hmac-filter.hpp>
35
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{
142 if (context->publicKeyLen == 0) {
143 this->getRawSelfPubKey();
144 }
145 std::stringstream os;
146 security::transform::bufferSource(context->publicKey, context->publicKeyLen)
147 >> security::transform::base64Encode() >> security::transform::streamSink(os);
148 return os.str();
149}
150
151uint8_t*
152ECDHState::deriveSecret(const uint8_t* peerkey, int peerKeySize)
153{
154 auto privECKey = EVP_PKEY_get1_EC_KEY(context->privkey);
155
156 if (privECKey == nullptr) {
157 handleErrors("Could not get referenced key when calling EVP_PKEY_get1_EC_KEY().");
158 return nullptr;
159 }
160
161 auto group = EC_KEY_get0_group(privECKey);
162 auto peerPoint = EC_POINT_new(group);
163 EC_POINT_oct2point(group, peerPoint, peerkey, peerKeySize, nullptr);
164
165 if (0 == (context->sharedSecretLen = ECDH_compute_key(context->sharedSecret, 256,
166 peerPoint, privECKey, nullptr))) {
167 EC_POINT_free(peerPoint);
168 EC_KEY_free(privECKey);
169 handleErrors("Cannot generate ECDH secret with ECDH_compute_key");
170 }
171 EC_POINT_free(peerPoint);
172 EC_KEY_free(privECKey);
173 return context->sharedSecret;
174}
175
176uint8_t*
177ECDHState::deriveSecret(const std::string& peerKeyStr)
178{
179 namespace t = ndn::security::transform;
180 OBufferStream os;
181 security::transform::bufferSource(peerKeyStr)
182 >> security::transform::base64Decode()
183 >> security::transform::streamSink(os);
184 ConstBufferPtr result = os.buf();
185 return this->deriveSecret(result->data(), result->size());
186}
187
188int ndn_compute_hmac_sha256 (const uint8_t *data, const unsigned data_length,
189 const uint8_t *key, const unsigned key_length,
190 uint8_t *prk) {
191 OBufferStream os;
192
193 security::transform::bufferSource(data, data_length) >>
194 security::transform::hmacFilter(
195 DigestAlgorithm::SHA256, key, key_length) >>
196 security::transform::streamSink(os);
197
198 auto result = os.buf();
199 memcpy(prk, result->data(), HASH_SIZE);
200 return 0;
201}
202
203//removed dependency of OpenSSL@1.1
204int
205hkdf(const uint8_t* secret, int secretLen, const uint8_t* salt,
206 int saltLen, uint8_t* okm, int okm_len,
207 const uint8_t* info, int info_len)
208{
209 // hkdf generate prk
210 uint8_t prk[HASH_SIZE];
211 ndn_compute_hmac_sha256(salt, saltLen, secret, secretLen, prk);
212
213 // hkdf expand
214 uint8_t prev[HASH_SIZE] = {0};
215 int done_len = 0, dig_len = HASH_SIZE, n = okm_len / dig_len;
216 if (okm_len % dig_len) n++;
217 if (n > 255 || okm == nullptr) return 0;
218 for (int i = 1; i <= n; i++) {
219 size_t copy_len;
220 const uint8_t ctr = i;
221 OBufferStream os;
222 security::transform::StepSource source;
223
224 source >> security::transform::hmacFilter(DigestAlgorithm::SHA256, prk, dig_len)
225 >> security::transform::streamSink(os);
226
227 if (i > 1) {
228 source.write(prev, dig_len);
229 }
230
231 source.write(info, info_len);
232 source.write(&ctr, 1);
233 source.end();
234
235 auto result = os.buf();
236 memcpy(prev, result->data(), dig_len);
237
238 copy_len = (done_len + dig_len > okm_len) ?
239 okm_len - done_len :
240 dig_len;
241
242 memcpy(okm + done_len, prev, copy_len);
243 done_len += copy_len;
244 }
245 return done_len;
246}
247
248void
249handleErrors(const std::string& errorInfo)
250{
251 _LOG_DEBUG("Error in CRYPTO SUPPORT " << errorInfo);
252 BOOST_THROW_EXCEPTION(CryptoError("Error in CRYPTO SUPPORT: " + errorInfo));
253}
254
255} // namespace ndncert
256} // namespace ndn