blob: a2a0af501c4e6095481cbee52ccf9f98a9bceb72 [file] [log] [blame]
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -07001/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
Davide Pesaventoa34d6de2021-11-18 22:16:04 -05002/*
3 * Copyright (c) 2017-2021, 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
Zhiyi Zhangb041d442020-10-22 21:57:11 -070021#include "detail/crypto-helpers.hpp"
Zhiyi Zhangdc25ddf2020-10-20 14:28:55 -070022
23#include <boost/endian/conversion.hpp>
Davide Pesaventoa34d6de2021-11-18 22:16:04 -050024
Davide Pesavento368341b2019-08-13 23:57:50 -040025#include <ndn-cxx/encoding/buffer-stream.hpp>
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070026#include <ndn-cxx/security/transform/base64-decode.hpp>
27#include <ndn-cxx/security/transform/base64-encode.hpp>
28#include <ndn-cxx/security/transform/buffer-source.hpp>
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070029#include <ndn-cxx/security/transform/stream-sink.hpp>
Zhiyi Zhangc5d93a92020-10-14 17:07:35 -070030#include <ndn-cxx/util/random.hpp>
Davide Pesaventoa34d6de2021-11-18 22:16:04 -050031
Zhiyi Zhangdc25ddf2020-10-20 14:28:55 -070032#include <openssl/ec.h>
33#include <openssl/err.h>
Zhiyi Zhangdc25ddf2020-10-20 14:28:55 -070034#include <openssl/hmac.h>
35#include <openssl/kdf.h>
36#include <openssl/pem.h>
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070037
Davide Pesaventoa34d6de2021-11-18 22:16:04 -050038#include <cstring>
39
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070040namespace ndn {
41namespace ndncert {
42
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070043ECDHState::ECDHState()
44{
Zhiyi Zhangf12ee302020-10-14 17:46:44 -070045 auto EC_NID = NID_X9_62_prime256v1;
Zhiyi Zhangbed854c2020-10-20 18:25:35 -070046 // params context
47 EVP_PKEY_CTX* ctx_params = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, nullptr);
Zhiyi Zhang6701f3c2021-02-18 17:38:42 -080048 EVP_PKEY_paramgen_init(ctx_params);
49 EVP_PKEY_CTX_set_ec_paramgen_curve_nid(ctx_params, EC_NID);
Zhiyi Zhangbed854c2020-10-20 18:25:35 -070050 // generate params
51 EVP_PKEY* params = nullptr;
Zhiyi Zhang6701f3c2021-02-18 17:38:42 -080052 EVP_PKEY_paramgen(ctx_params, &params);
Zhiyi Zhangbed854c2020-10-20 18:25:35 -070053 // key generation context
Zhiyi Zhangf908f662020-10-21 12:55:10 -070054 EVP_PKEY_CTX* ctx_keygen = EVP_PKEY_CTX_new(params, nullptr);
Zhiyi Zhang6701f3c2021-02-18 17:38:42 -080055 EVP_PKEY_keygen_init(ctx_keygen);
56 auto resultCode = EVP_PKEY_keygen(ctx_keygen, &m_privkey);
Zhiyi Zhangbed854c2020-10-20 18:25:35 -070057 EVP_PKEY_CTX_free(ctx_keygen);
58 EVP_PKEY_free(params);
59 EVP_PKEY_CTX_free(ctx_params);
Zhiyi Zhang6701f3c2021-02-18 17:38:42 -080060 if (resultCode <= 0) {
61 NDN_THROW(std::runtime_error("Error in initiating ECDH"));
62 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070063}
64
65ECDHState::~ECDHState()
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070066{
Zhiyi Zhangbed854c2020-10-20 18:25:35 -070067 if (m_privkey != nullptr) {
68 EVP_PKEY_free(m_privkey);
69 }
70}
71
Zhiyi Zhang3b9a5032021-02-18 11:15:09 -080072const std::vector <uint8_t>&
Zhiyi Zhangbed854c2020-10-20 18:25:35 -070073ECDHState::getSelfPubKey()
74{
75 auto privECKey = EVP_PKEY_get1_EC_KEY(m_privkey);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070076 auto ecPoint = EC_KEY_get0_public_key(privECKey);
Zhiyi Zhangbed854c2020-10-20 18:25:35 -070077 auto group = EC_KEY_get0_group(privECKey);
Zhiyi Zhang5e74ecd2020-10-21 12:52:25 -070078 auto requiredBufLen = EC_POINT_point2oct(group, ecPoint, POINT_CONVERSION_UNCOMPRESSED, nullptr, 0, nullptr);
Zhiyi Zhangbed854c2020-10-20 18:25:35 -070079 m_pubKey.resize(requiredBufLen);
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -080080 auto resultCode = EC_POINT_point2oct(group, ecPoint, POINT_CONVERSION_UNCOMPRESSED,
81 m_pubKey.data(), requiredBufLen, nullptr);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070082 EC_KEY_free(privECKey);
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -080083 if (resultCode == 0) {
84 NDN_THROW(std::runtime_error("Error in getting EC Public Key in the format of octet string"));
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070085 }
Zhiyi Zhangbed854c2020-10-20 18:25:35 -070086 return m_pubKey;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070087}
88
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -080089const std::vector<uint8_t>&
Zhiyi Zhang3b9a5032021-02-18 11:15:09 -080090ECDHState::deriveSecret(const std::vector <uint8_t>& peerKey)
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070091{
Zhiyi Zhangbed854c2020-10-20 18:25:35 -070092 // prepare self private key
93 auto privECKey = EVP_PKEY_get1_EC_KEY(m_privkey);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070094 auto group = EC_KEY_get0_group(privECKey);
Zhiyi Zhangbed854c2020-10-20 18:25:35 -070095 EC_KEY_free(privECKey);
96 // prepare the peer public key
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070097 auto peerPoint = EC_POINT_new(group);
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -080098 EC_POINT_oct2point(group, peerPoint, peerKey.data(), peerKey.size(), nullptr);
Zhiyi Zhangdef00e42020-10-20 22:41:56 -070099 EC_KEY* ecPeerkey = EC_KEY_new();
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800100 EC_KEY_set_group(ecPeerkey, group);
101 EC_KEY_set_public_key(ecPeerkey, peerPoint);
Zhiyi Zhangdef00e42020-10-20 22:41:56 -0700102 EVP_PKEY* evpPeerkey = EVP_PKEY_new();
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800103 EVP_PKEY_set1_EC_KEY(evpPeerkey, ecPeerkey);
Zhiyi Zhangbed854c2020-10-20 18:25:35 -0700104 EC_KEY_free(ecPeerkey);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700105 EC_POINT_free(peerPoint);
Zhiyi Zhangbed854c2020-10-20 18:25:35 -0700106 // ECDH context
Zhiyi Zhangdef00e42020-10-20 22:41:56 -0700107 EVP_PKEY_CTX* ctx = EVP_PKEY_CTX_new(m_privkey, nullptr);
Zhiyi Zhangdef00e42020-10-20 22:41:56 -0700108 // Initialize
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800109 EVP_PKEY_derive_init(ctx);
Zhiyi Zhangdef00e42020-10-20 22:41:56 -0700110 // Provide the peer public key
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800111 EVP_PKEY_derive_set_peer(ctx, evpPeerkey);
Zhiyi Zhangdef00e42020-10-20 22:41:56 -0700112 // Determine buffer length for shared secret
Zhiyi Zhangbed854c2020-10-20 18:25:35 -0700113 size_t secretLen = 0;
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800114 EVP_PKEY_derive(ctx, nullptr, &secretLen);
Zhiyi Zhangdef00e42020-10-20 22:41:56 -0700115 m_secret.resize(secretLen);
116 // Derive the shared secret
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800117 auto resultCode = EVP_PKEY_derive(ctx, m_secret.data(), &secretLen);
Zhiyi Zhangbed854c2020-10-20 18:25:35 -0700118 EVP_PKEY_CTX_free(ctx);
119 EVP_PKEY_free(evpPeerkey);
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800120 if (resultCode == 0) {
121 NDN_THROW(std::runtime_error("Error when calling ECDH"));
122 }
Zhiyi Zhangbed854c2020-10-20 18:25:35 -0700123 return m_secret;
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800124
125// // prepare self private key
126// auto privECKey = EVP_PKEY_get1_EC_KEY(m_privkey);
127// if (privECKey == nullptr) {
128// NDN_THROW(std::runtime_error("Cannot not get key when calling EVP_PKEY_get1_EC_KEY()"));
129// }
130// auto group = EC_KEY_get0_group(privECKey);
131// EC_KEY_free(privECKey);
132// // prepare the peer public key
133// auto peerPoint = EC_POINT_new(group);
134// if (peerPoint == nullptr) {
135// NDN_THROW(std::runtime_error("Cannot create the EC_POINT for peer key when calling EC_POINT_new()"));
136// }
137// if (EC_POINT_oct2point(group, peerPoint, peerKey.data(), peerKey.size(), nullptr) == 0) {
138// EC_POINT_free(peerPoint);
139// NDN_THROW(std::runtime_error("Cannot convert peer's key into a EC point when calling EC_POINT_oct2point()"));
140// }
141// EC_KEY* ecPeerkey = EC_KEY_new();
142// if (ecPeerkey == nullptr) {
143// EC_POINT_free(peerPoint);
144// NDN_THROW(std::runtime_error("Cannot create EC_KEY for peer key when calling EC_KEY_new()"));
145// }
146// if (EC_KEY_set_group(ecPeerkey, group) != 1) {
147// EC_POINT_free(peerPoint);
148// NDN_THROW(std::runtime_error("Cannot set group for peer key's EC_KEY when calling EC_KEY_set_group()"));
149// }
150// if (EC_KEY_set_public_key(ecPeerkey, peerPoint) == 0) {
151// EC_KEY_free(ecPeerkey);
152// EC_POINT_free(peerPoint);
153// NDN_THROW(
154// std::runtime_error("Cannot initialize peer EC_KEY with the EC_POINT when calling EC_KEY_set_public_key()"));
155// }
156// EVP_PKEY* evpPeerkey = EVP_PKEY_new();
157// if (EVP_PKEY_set1_EC_KEY(evpPeerkey, ecPeerkey) == 0) {
158// EC_KEY_free(ecPeerkey);
159// EC_POINT_free(peerPoint);
160// NDN_THROW(std::runtime_error("Cannot create EVP_PKEY for peer key when calling EVP_PKEY_new()"));
161// }
162// EC_KEY_free(ecPeerkey);
163// EC_POINT_free(peerPoint);
164// // ECDH context
165// EVP_PKEY_CTX* ctx = EVP_PKEY_CTX_new(m_privkey, nullptr);
166// if (ctx == nullptr) {
167// EVP_PKEY_free(evpPeerkey);
168// NDN_THROW(std::runtime_error("Cannot create context for ECDH when calling EVP_PKEY_CTX_new()"));
169// }
170// // Initialize
171// if (1 != EVP_PKEY_derive_init(ctx)) {
172// EVP_PKEY_CTX_free(ctx);
173// EVP_PKEY_free(evpPeerkey);
174// NDN_THROW(std::runtime_error("Cannot initialize context for ECDH when calling EVP_PKEY_derive_init()"));
175// }
176// // Provide the peer public key
177// if (1 != EVP_PKEY_derive_set_peer(ctx, evpPeerkey)) {
178// EVP_PKEY_CTX_free(ctx);
179// EVP_PKEY_free(evpPeerkey);
180// NDN_THROW(std::runtime_error("Cannot set peer key for ECDH when calling EVP_PKEY_derive_set_peer()"));
181// }
182// // Determine buffer length for shared secret
183// size_t secretLen = 0;
184// if (1 != EVP_PKEY_derive(ctx, nullptr, &secretLen)) {
185// EVP_PKEY_CTX_free(ctx);
186// EVP_PKEY_free(evpPeerkey);
187// NDN_THROW(std::runtime_error("Cannot determine the needed buffer length when calling EVP_PKEY_derive()"));
188// }
189// m_secret.resize(secretLen);
190// // Derive the shared secret
191// if (1 != (EVP_PKEY_derive(ctx, m_secret.data(), &secretLen))) {
192// EVP_PKEY_CTX_free(ctx);
193// EVP_PKEY_free(evpPeerkey);
194// NDN_THROW(std::runtime_error("Cannot derive ECDH secret when calling EVP_PKEY_derive()"));
195// }
196// EVP_PKEY_CTX_free(ctx);
197// EVP_PKEY_free(evpPeerkey);
198// return m_secret;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700199}
200
Zhiyi Zhangf12ee302020-10-14 17:46:44 -0700201void
Zhiyi Zhang11cf7eb2020-10-20 15:43:36 -0700202hmacSha256(const uint8_t* data, size_t dataLen,
Zhiyi Zhang199508a2020-10-21 10:45:50 -0700203 const uint8_t* key, size_t keyLen,
204 uint8_t* result)
Davide Pesavento368341b2019-08-13 23:57:50 -0400205{
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800206 auto ret = HMAC(EVP_sha256(), key, keyLen, data, dataLen, result, nullptr);
Zhiyi Zhangf12ee302020-10-14 17:46:44 -0700207 if (ret == nullptr) {
Zhiyi Zhang5c059452020-10-16 17:43:31 -0700208 NDN_THROW(std::runtime_error("Error computing HMAC when calling HMAC()"));
Zhiyi Zhangf12ee302020-10-14 17:46:44 -0700209 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700210}
211
Zhiyi Zhang159ba632020-10-20 15:09:12 -0700212size_t
Zhiyi Zhang11cf7eb2020-10-20 15:43:36 -0700213hkdf(const uint8_t* secret, size_t secretLen, const uint8_t* salt,
214 size_t saltLen, uint8_t* output, size_t outputLen,
215 const uint8_t* info, size_t infoLen)
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700216{
Zhiyi Zhangf908f662020-10-21 12:55:10 -0700217 EVP_PKEY_CTX* pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, nullptr);
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800218 EVP_PKEY_derive_init(pctx);
219 EVP_PKEY_CTX_set_hkdf_md(pctx, EVP_sha256());
220 EVP_PKEY_CTX_set1_hkdf_salt(pctx, salt, saltLen);
221 EVP_PKEY_CTX_set1_hkdf_key(pctx, secret, secretLen);
222 EVP_PKEY_CTX_add1_hkdf_info(pctx, info, infoLen);
Zhiyi Zhang11cf7eb2020-10-20 15:43:36 -0700223 size_t outLen = outputLen;
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800224 auto resultCode = EVP_PKEY_derive(pctx, output, &outLen);
Zhiyi Zhang222810b2020-10-16 21:50:35 -0700225 EVP_PKEY_CTX_free(pctx);
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800226 if (resultCode == 0) {
227 NDN_THROW(std::runtime_error("Error when calling HKDF"));
228 }
Zhiyi Zhang159ba632020-10-20 15:09:12 -0700229 return outLen;
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800230
231// if (EVP_PKEY_derive_init(pctx) <= 0) {
232// EVP_PKEY_CTX_free(pctx);
233// NDN_THROW(std::runtime_error("HKDF: Cannot init ctx when calling EVP_PKEY_derive_init()"));
234// }
235// if (EVP_PKEY_CTX_set_hkdf_md(pctx, EVP_sha256()) <= 0) {
236// EVP_PKEY_CTX_free(pctx);
237// NDN_THROW(std::runtime_error("HKDF: Cannot set md when calling EVP_PKEY_CTX_set_hkdf_md()"));
238// }
239// if (EVP_PKEY_CTX_set1_hkdf_salt(pctx, salt, saltLen) <= 0) {
240// EVP_PKEY_CTX_free(pctx);
241// NDN_THROW(std::runtime_error("HKDF: Cannot set salt when calling EVP_PKEY_CTX_set1_hkdf_salt()"));
242// }
243// if (EVP_PKEY_CTX_set1_hkdf_key(pctx, secret, secretLen) <= 0) {
244// EVP_PKEY_CTX_free(pctx);
245// NDN_THROW(std::runtime_error("HKDF: Cannot set secret when calling EVP_PKEY_CTX_set1_hkdf_key()"));
246// }
247// if (EVP_PKEY_CTX_add1_hkdf_info(pctx, info, infoLen) <= 0) {
248// EVP_PKEY_CTX_free(pctx);
249// NDN_THROW(std::runtime_error("HKDF: Cannot set info when calling EVP_PKEY_CTX_add1_hkdf_info()"));
250// }
251// size_t outLen = outputLen;
252// if (EVP_PKEY_derive(pctx, output, &outLen) <= 0) {
253// EVP_PKEY_CTX_free(pctx);
254// NDN_THROW(std::runtime_error("HKDF: Cannot derive result when calling EVP_PKEY_derive()"));
255// }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700256}
257
Zhiyi Zhange5a07c92020-10-21 10:51:37 -0700258size_t
Zhiyi Zhang11cf7eb2020-10-20 15:43:36 -0700259aesGcm128Encrypt(const uint8_t* plaintext, size_t plaintextLen, const uint8_t* associated, size_t associatedLen,
Zhiyi Zhangf908f662020-10-21 12:55:10 -0700260 const uint8_t* key, const uint8_t* iv, uint8_t* ciphertext, uint8_t* tag)
Zhiyi Zhanga67fa462020-04-19 13:48:03 -0700261{
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800262 int len = 0;
263 size_t ciphertextLen = 0;
264 EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
265 EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), nullptr, nullptr, nullptr);
266 EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 12, nullptr);
267 EVP_EncryptInit_ex(ctx, nullptr, nullptr, key, iv);
268 EVP_EncryptUpdate(ctx, nullptr, &len, associated, associatedLen);
269 EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintextLen);
Zhiyi Zhang11cf7eb2020-10-20 15:43:36 -0700270 ciphertextLen = len;
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800271 EVP_EncryptFinal_ex(ctx, ciphertext + len, &len);
272 auto resultCode = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, 16, tag);
Zhiyi Zhanga67fa462020-04-19 13:48:03 -0700273 EVP_CIPHER_CTX_free(ctx);
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800274 if (resultCode == 0) {
275 NDN_THROW(std::runtime_error("Error in encryption plaintext with AES GCM"));
276 }
Zhiyi Zhang11cf7eb2020-10-20 15:43:36 -0700277 return ciphertextLen;
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800278
279// if (!(ctx = EVP_CIPHER_CTX_new())) {
280// NDN_THROW(std::runtime_error("Cannot create and initialise the context when calling EVP_CIPHER_CTX_new()"));
281// }
282// if (1 != EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), nullptr, nullptr, nullptr)) {
283// EVP_CIPHER_CTX_free(ctx);
284// NDN_THROW(std::runtime_error("Cannot initialize the encryption operation when calling EVP_EncryptInit_ex()"));
285// }
286// if (1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 12, nullptr)) {
287// EVP_CIPHER_CTX_free(ctx);
288// NDN_THROW(std::runtime_error("Cannot set IV length when calling EVP_CIPHER_CTX_ctrl()"));
289// }
290// if (1 != EVP_EncryptInit_ex(ctx, nullptr, nullptr, key, iv)) {
291// EVP_CIPHER_CTX_free(ctx);
292// NDN_THROW(std::runtime_error("Cannot initialize key and IV when calling EVP_EncryptInit_ex()"));
293// }
294// if (1 != EVP_EncryptUpdate(ctx, nullptr, &len, associated, associatedLen)) {
295// EVP_CIPHER_CTX_free(ctx);
296// NDN_THROW(std::runtime_error("Cannot set associated authentication data when calling EVP_EncryptUpdate()"));
297// }
298// if (1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintextLen)) {
299// EVP_CIPHER_CTX_free(ctx);
300// NDN_THROW(std::runtime_error("Cannot encrypt when calling EVP_EncryptUpdate()"));
301// }
302// ciphertextLen = len;
303// if (1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) {
304// EVP_CIPHER_CTX_free(ctx);
305// NDN_THROW(std::runtime_error("Cannot finalise the encryption when calling EVP_EncryptFinal_ex()"));
306// }
307// ciphertextLen += len;
308// if (1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, 16, tag)) {
309// EVP_CIPHER_CTX_free(ctx);
310// NDN_THROW(std::runtime_error("Cannot get tag when calling EVP_CIPHER_CTX_ctrl()"));
311// }
Zhiyi Zhanga67fa462020-04-19 13:48:03 -0700312}
313
Zhiyi Zhange5a07c92020-10-21 10:51:37 -0700314size_t
Zhiyi Zhang11cf7eb2020-10-20 15:43:36 -0700315aesGcm128Decrypt(const uint8_t* ciphertext, size_t ciphertextLen, const uint8_t* associated, size_t associatedLen,
Zhiyi Zhangf908f662020-10-21 12:55:10 -0700316 const uint8_t* tag, const uint8_t* key, const uint8_t* iv, uint8_t* plaintext)
Zhiyi Zhanga67fa462020-04-19 13:48:03 -0700317{
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800318 int len = 0;
319 size_t plaintextLen = 0;
320 EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
321 EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), nullptr, nullptr, nullptr);
322 EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 12, nullptr);
323 EVP_DecryptInit_ex(ctx, nullptr, nullptr, key, iv);
324 EVP_DecryptUpdate(ctx, nullptr, &len, associated, associatedLen);
325 EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertextLen);
Zhiyi Zhang11cf7eb2020-10-20 15:43:36 -0700326 plaintextLen = len;
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800327 EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, 16, const_cast<void*>(reinterpret_cast<const void*>(tag)));
328 auto resultCode = EVP_DecryptFinal_ex(ctx, plaintext + len, &len);
329 plaintextLen += len;
Zhiyi Zhanga67fa462020-04-19 13:48:03 -0700330 EVP_CIPHER_CTX_free(ctx);
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800331 if (resultCode == 0) {
332 NDN_THROW(std::runtime_error("Error in decrypting ciphertext with AES GCM"));
Zhiyi Zhanga67fa462020-04-19 13:48:03 -0700333 }
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800334 return plaintextLen;
335
336// if (!(ctx = EVP_CIPHER_CTX_new())) {
337// NDN_THROW(std::runtime_error("Cannot create and initialise the context when calling EVP_CIPHER_CTX_new()"));
338// }
339// if (!EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), nullptr, nullptr, nullptr)) {
340// EVP_CIPHER_CTX_free(ctx);
341// NDN_THROW(std::runtime_error("Cannot initialise the decryption operation when calling EVP_DecryptInit_ex()"));
342// }
343// if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 12, nullptr)) {
344// EVP_CIPHER_CTX_free(ctx);
345// NDN_THROW(std::runtime_error("Cannot set IV length when calling EVP_CIPHER_CTX_ctrl"));
346// }
347// if (!EVP_DecryptInit_ex(ctx, nullptr, nullptr, key, iv)) {
348// EVP_CIPHER_CTX_free(ctx);
349// NDN_THROW(std::runtime_error("Cannot initialise key and IV when calling EVP_DecryptInit_ex()"));
350// }
351// if (!EVP_DecryptUpdate(ctx, nullptr, &len, associated, associatedLen)) {
352// EVP_CIPHER_CTX_free(ctx);
353// NDN_THROW(std::runtime_error("Cannot set associated authentication data when calling EVP_EncryptUpdate()"));
354// }
355// if (!EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertextLen)) {
356// EVP_CIPHER_CTX_free(ctx);
357// NDN_THROW(std::runtime_error("Cannot decrypt when calling EVP_DecryptUpdate()"));
358// }
359// plaintextLen = len;
360// if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, 16, const_cast<void*>(reinterpret_cast<const void*>(tag)))) {
361// EVP_CIPHER_CTX_free(ctx);
362// NDN_THROW(std::runtime_error("Cannot set tag value when calling EVP_CIPHER_CTX_ctrl()"));
363// }
Zhiyi Zhanga67fa462020-04-19 13:48:03 -0700364}
365
Davide Pesaventoa34d6de2021-11-18 22:16:04 -0500366#ifndef NDNCERT_HAVE_TESTS
367static
368#endif
369uint32_t
370loadBigU32(const uint8_t* src) noexcept
Zhiyi Zhang886a2262020-12-24 15:19:33 -0800371{
Davide Pesaventoa34d6de2021-11-18 22:16:04 -0500372#if BOOST_VERSION >= 107100
373 return boost::endian::endian_load<uint32_t, 4, boost::endian::order::big>(src);
374#else
375 uint32_t dest;
376 std::memcpy(reinterpret_cast<uint8_t*>(&dest), src, sizeof(dest));
377 return boost::endian::big_to_native(dest);
378#endif
Zhiyi Zhang886a2262020-12-24 15:19:33 -0800379}
380
Davide Pesaventoa34d6de2021-11-18 22:16:04 -0500381#ifndef NDNCERT_HAVE_TESTS
382static
383#endif
384void
385storeBigU32(uint8_t* dest, uint32_t src) noexcept
Zhiyi Zhang886a2262020-12-24 15:19:33 -0800386{
Davide Pesaventoa34d6de2021-11-18 22:16:04 -0500387#if BOOST_VERSION >= 107100
388 boost::endian::endian_store<uint32_t, 4, boost::endian::order::big>(dest, src);
389#else
390 boost::endian::native_to_big_inplace(src);
391 std::memcpy(dest, reinterpret_cast<const uint8_t*>(&src), sizeof(src));
392#endif
Zhiyi Zhang886a2262020-12-24 15:19:33 -0800393}
394
Zhiyi Zhang4f1c0102020-12-21 15:08:09 -0800395static void
Davide Pesaventoa34d6de2021-11-18 22:16:04 -0500396updateIv(std::vector<uint8_t>& iv, size_t payloadSize)
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700397{
Davide Pesaventoa34d6de2021-11-18 22:16:04 -0500398 BOOST_ASSERT(iv.size() >= 12);
399 uint32_t counter = loadBigU32(&iv[8]);
Zhiyi Zhang199508a2020-10-21 10:45:50 -0700400 uint32_t increment = (payloadSize + 15) / 16;
Zhiyi Zhang4f1c0102020-12-21 15:08:09 -0800401 if (std::numeric_limits<uint32_t>::max() - counter <= increment) {
Zhiyi Zhangaeab4972020-10-22 22:20:40 -0700402 NDN_THROW(std::runtime_error("Error incrementing the AES block counter: "
Zhiyi Zhange11a2d62020-10-22 09:59:12 -0700403 "too many blocks have been encrypted for the same request instance"));
Zhiyi Zhang159ba632020-10-20 15:09:12 -0700404 }
405 else {
406 counter += increment;
407 }
Zhiyi Zhang886a2262020-12-24 15:19:33 -0800408 storeBigU32(&iv[8], counter);
Zhiyi Zhang4f1c0102020-12-21 15:08:09 -0800409}
Zhiyi Zhangc5d93a92020-10-14 17:07:35 -0700410
Zhiyi Zhang4f1c0102020-12-21 15:08:09 -0800411Block
Zhiyi Zhangc1e98152020-12-21 16:15:39 -0800412encodeBlockWithAesGcm128(uint32_t tlvType, const uint8_t* key,
413 const uint8_t* payload, size_t payloadSize,
414 const uint8_t* associatedData, size_t associatedDataSize,
Davide Pesaventoa34d6de2021-11-18 22:16:04 -0500415 std::vector<uint8_t>& encryptionIv)
Zhiyi Zhang4f1c0102020-12-21 15:08:09 -0800416{
Zhiyi Zhang5e74ecd2020-10-21 12:52:25 -0700417 // The spec of AES encrypted payload TLV used in NDNCERT:
418 // https://github.com/named-data/ndncert/wiki/NDNCERT-Protocol-0.3#242-aes-gcm-encryption
Zhiyi Zhang222810b2020-10-16 21:50:35 -0700419 Buffer encryptedPayload(payloadSize);
Zhiyi Zhangc5d93a92020-10-14 17:07:35 -0700420 uint8_t tag[16];
Zhiyi Zhang4f1c0102020-12-21 15:08:09 -0800421 if (encryptionIv.empty()) {
422 encryptionIv.resize(12, 0);
423 random::generateSecureBytes(encryptionIv.data(), 8);
424 }
Zhiyi Zhang11cf7eb2020-10-20 15:43:36 -0700425 size_t encryptedPayloadLen = aesGcm128Encrypt(payload, payloadSize, associatedData, associatedDataSize,
Zhiyi Zhang4f1c0102020-12-21 15:08:09 -0800426 key, encryptionIv.data(), encryptedPayload.data(), tag);
tylerliu1f480be2020-11-10 13:02:53 -0800427 Block content(tlvType);
Zhiyi Zhang4f1c0102020-12-21 15:08:09 -0800428 content.push_back(makeBinaryBlock(tlv::InitializationVector, encryptionIv.data(), encryptionIv.size()));
Zhiyi Zhangc5d93a92020-10-14 17:07:35 -0700429 content.push_back(makeBinaryBlock(tlv::AuthenticationTag, tag, 16));
Zhiyi Zhang222810b2020-10-16 21:50:35 -0700430 content.push_back(makeBinaryBlock(tlv::EncryptedPayload, encryptedPayload.data(), encryptedPayloadLen));
Zhiyi Zhangc5d93a92020-10-14 17:07:35 -0700431 content.encode();
Zhiyi Zhang4f1c0102020-12-21 15:08:09 -0800432 // update IV's counter
433 updateIv(encryptionIv, payloadSize);
Zhiyi Zhangc5d93a92020-10-14 17:07:35 -0700434 return content;
435}
436
437Buffer
Zhiyi Zhang4f1c0102020-12-21 15:08:09 -0800438decodeBlockWithAesGcm128(const Block& block, const uint8_t* key,
439 const uint8_t* associatedData, size_t associatedDataSize,
Davide Pesaventoa34d6de2021-11-18 22:16:04 -0500440 std::vector<uint8_t>& decryptionIv, const std::vector<uint8_t>& encryptionIv)
Zhiyi Zhangc5d93a92020-10-14 17:07:35 -0700441{
Zhiyi Zhang5e74ecd2020-10-21 12:52:25 -0700442 // The spec of AES encrypted payload TLV used in NDNCERT:
443 // https://github.com/named-data/ndncert/wiki/NDNCERT-Protocol-0.3#242-aes-gcm-encryption
Zhiyi Zhangc5d93a92020-10-14 17:07:35 -0700444 block.parse();
Zhiyi Zhangaeab4972020-10-22 22:20:40 -0700445 const auto& encryptedPayloadBlock = block.get(tlv::EncryptedPayload);
446 Buffer result(encryptedPayloadBlock.value_size());
Zhiyi Zhang3b9a5032021-02-18 11:15:09 -0800447 if (block.get(tlv::InitializationVector).value_size() != 12 ||
448 block.get(tlv::AuthenticationTag).value_size() != 16) {
Zhiyi Zhangde58e602021-02-17 23:09:02 -0800449 NDN_THROW(std::runtime_error("Error when decrypting the AES Encrypted Block: "
Zhiyi Zhang3b9a5032021-02-18 11:15:09 -0800450 "The observed IV or Authentication Tag is of an unexpected size."));
Zhiyi Zhangde58e602021-02-17 23:09:02 -0800451 }
Davide Pesaventoa34d6de2021-11-18 22:16:04 -0500452 std::vector<uint8_t> observedDecryptionIv(block.get(tlv::InitializationVector).value(),
453 block.get(tlv::InitializationVector).value() + 12);
Zhiyi Zhang3b9a5032021-02-18 11:15:09 -0800454 if (!encryptionIv.empty()) {
455 if (std::equal(observedDecryptionIv.begin(), observedDecryptionIv.begin() + 8, encryptionIv.begin())) {
Zhiyi Zhang4f1c0102020-12-21 15:08:09 -0800456 NDN_THROW(std::runtime_error("Error when decrypting the AES Encrypted Block: "
Zhiyi Zhang3b9a5032021-02-18 11:15:09 -0800457 "The observed IV's the random component should be different from ours."));
Zhiyi Zhangde58e602021-02-17 23:09:02 -0800458 }
Zhiyi Zhang4f1c0102020-12-21 15:08:09 -0800459 }
Zhiyi Zhang3b9a5032021-02-18 11:15:09 -0800460 if (!decryptionIv.empty()) {
Davide Pesaventoa34d6de2021-11-18 22:16:04 -0500461 if (loadBigU32(&observedDecryptionIv[8]) < loadBigU32(&decryptionIv[8]) ||
Zhiyi Zhang3b9a5032021-02-18 11:15:09 -0800462 !std::equal(observedDecryptionIv.begin(), observedDecryptionIv.begin() + 8, decryptionIv.begin())) {
463 NDN_THROW(std::runtime_error("Error when decrypting the AES Encrypted Block: "
464 "The observed IV's counter should be monotonically increasing "
465 "and the random component must be the same from the requester."));
466 }
467 }
468 decryptionIv = observedDecryptionIv;
Zhiyi Zhangaeab4972020-10-22 22:20:40 -0700469 auto resultLen = aesGcm128Decrypt(encryptedPayloadBlock.value(), encryptedPayloadBlock.value_size(),
Zhiyi Zhangf908f662020-10-21 12:55:10 -0700470 associatedData, associatedDataSize, block.get(tlv::AuthenticationTag).value(),
Zhiyi Zhang3b9a5032021-02-18 11:15:09 -0800471 key, decryptionIv.data(), result.data());
Zhiyi Zhangaeab4972020-10-22 22:20:40 -0700472 if (resultLen != encryptedPayloadBlock.value_size()) {
Zhiyi Zhangaeab4972020-10-22 22:20:40 -0700473 NDN_THROW(std::runtime_error("Error when decrypting the AES Encrypted Block: "
Zhiyi Zhang3b9a5032021-02-18 11:15:09 -0800474 "Decrypted payload is of an unexpected size."));
Zhiyi Zhangc5d93a92020-10-14 17:07:35 -0700475 }
Zhiyi Zhang4f1c0102020-12-21 15:08:09 -0800476 updateIv(decryptionIv, resultLen);
Zhiyi Zhangc5d93a92020-10-14 17:07:35 -0700477 return result;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700478}
479
Zhiyi Zhange4891b72020-10-10 15:11:57 -0700480} // namespace ndncert
481} // namespace ndn