blob: ea18dbafa794c84e60b6d3f9c863a0539223b99c [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>
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)
151 >> t::base64Encode()
152 >> 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) {
162 handleErrors("Could not get referenced key when calling EVP_PKEY_get1_EC_KEY().");
163 return nullptr;
164 }
165
166 auto group = EC_KEY_get0_group(privECKey);
167 auto peerPoint = EC_POINT_new(group);
168 EC_POINT_oct2point(group, peerPoint, peerkey, peerKeySize, nullptr);
169
170 if (0 == (context->sharedSecretLen = ECDH_compute_key(context->sharedSecret, 256,
171 peerPoint, privECKey, nullptr))) {
172 EC_POINT_free(peerPoint);
173 EC_KEY_free(privECKey);
174 handleErrors("Cannot generate ECDH secret with ECDH_compute_key");
175 }
176 EC_POINT_free(peerPoint);
177 EC_KEY_free(privECKey);
178 return context->sharedSecret;
179}
180
181uint8_t*
182ECDHState::deriveSecret(const std::string& peerKeyStr)
183{
184 namespace t = ndn::security::transform;
Davide Pesavento368341b2019-08-13 23:57:50 -0400185
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700186 OBufferStream os;
Davide Pesavento368341b2019-08-13 23:57:50 -0400187 t::bufferSource(peerKeyStr) >> t::base64Decode() >> t::streamSink(os);
188 auto result = os.buf();
189
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700190 return this->deriveSecret(result->data(), result->size());
191}
192
Davide Pesavento368341b2019-08-13 23:57:50 -0400193int
194ndn_compute_hmac_sha256(const uint8_t *data, const unsigned data_length,
195 const uint8_t *key, const unsigned key_length,
196 uint8_t *prk)
197{
Zhiyi Zhanga2ce5992019-08-14 17:35:00 -0700198 HMAC(EVP_sha256(), key, key_length,
199 (unsigned char*)data, data_length,
200 (unsigned char*)prk, nullptr);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700201 return 0;
202}
203
Davide Pesavento368341b2019-08-13 23:57:50 -0400204// avoid dependency on OpenSSL >= 1.1
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700205int
206hkdf(const uint8_t* secret, int secretLen, const uint8_t* salt,
207 int saltLen, uint8_t* okm, int okm_len,
208 const uint8_t* info, int info_len)
209{
Davide Pesavento368341b2019-08-13 23:57:50 -0400210 namespace t = ndn::security::transform;
211
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700212 // hkdf generate prk
213 uint8_t prk[HASH_SIZE];
Zhiyi Zhanga2ce5992019-08-14 17:35:00 -0700214 if (saltLen == 0) {
215 uint8_t realSalt[HASH_SIZE] = {0};
216 ndn_compute_hmac_sha256(secret, secretLen, realSalt, HASH_SIZE, prk);
217 }
218 else {
219 ndn_compute_hmac_sha256(secret, secretLen, salt, saltLen, prk);
220 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700221
222 // hkdf expand
223 uint8_t prev[HASH_SIZE] = {0};
224 int done_len = 0, dig_len = HASH_SIZE, n = okm_len / dig_len;
Davide Pesavento368341b2019-08-13 23:57:50 -0400225 if (okm_len % dig_len)
226 n++;
227 if (n > 255 || okm == nullptr)
228 return 0;
229
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700230 for (int i = 1; i <= n; i++) {
231 size_t copy_len;
232 const uint8_t ctr = i;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700233
Davide Pesavento368341b2019-08-13 23:57:50 -0400234 t::StepSource source;
235 t::PrivateKey privKey;
236 privKey.loadRaw(KeyType::HMAC, prk, dig_len);
237 OBufferStream os;
238 source >> t::signerFilter(DigestAlgorithm::SHA256, privKey)
239 >> t::streamSink(os);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700240
241 if (i > 1) {
242 source.write(prev, dig_len);
243 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700244 source.write(info, info_len);
245 source.write(&ctr, 1);
246 source.end();
247
248 auto result = os.buf();
249 memcpy(prev, result->data(), dig_len);
Davide Pesavento368341b2019-08-13 23:57:50 -0400250 copy_len = (done_len + dig_len > okm_len) ? okm_len - done_len : dig_len;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700251 memcpy(okm + done_len, prev, copy_len);
252 done_len += copy_len;
253 }
254 return done_len;
255}
256
257void
258handleErrors(const std::string& errorInfo)
259{
260 _LOG_DEBUG("Error in CRYPTO SUPPORT " << errorInfo);
261 BOOST_THROW_EXCEPTION(CryptoError("Error in CRYPTO SUPPORT: " + errorInfo));
262}
263
264} // namespace ndncert
265} // namespace ndn