blob: 91d90e3b0d1e79d54ab3ce874ddb38a374559f60 [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
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>
Zhiyi Zhangaeab4972020-10-22 22:20:40 -070024#include <cstring>
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>
Zhiyi Zhangdc25ddf2020-10-20 14:28:55 -070031#include <openssl/ec.h>
32#include <openssl/err.h>
Zhiyi Zhangdc25ddf2020-10-20 14:28:55 -070033#include <openssl/hmac.h>
34#include <openssl/kdf.h>
35#include <openssl/pem.h>
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070036
37namespace ndn {
38namespace ndncert {
39
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070040ECDHState::ECDHState()
41{
Zhiyi Zhangf12ee302020-10-14 17:46:44 -070042 auto EC_NID = NID_X9_62_prime256v1;
Zhiyi Zhangbed854c2020-10-20 18:25:35 -070043 // params context
44 EVP_PKEY_CTX* ctx_params = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, nullptr);
Zhiyi Zhang6701f3c2021-02-18 17:38:42 -080045 EVP_PKEY_paramgen_init(ctx_params);
46 EVP_PKEY_CTX_set_ec_paramgen_curve_nid(ctx_params, EC_NID);
Zhiyi Zhangbed854c2020-10-20 18:25:35 -070047 // generate params
48 EVP_PKEY* params = nullptr;
Zhiyi Zhang6701f3c2021-02-18 17:38:42 -080049 EVP_PKEY_paramgen(ctx_params, &params);
Zhiyi Zhangbed854c2020-10-20 18:25:35 -070050 // key generation context
Zhiyi Zhangf908f662020-10-21 12:55:10 -070051 EVP_PKEY_CTX* ctx_keygen = EVP_PKEY_CTX_new(params, nullptr);
Zhiyi Zhang6701f3c2021-02-18 17:38:42 -080052 EVP_PKEY_keygen_init(ctx_keygen);
53 auto resultCode = EVP_PKEY_keygen(ctx_keygen, &m_privkey);
Zhiyi Zhangbed854c2020-10-20 18:25:35 -070054 EVP_PKEY_CTX_free(ctx_keygen);
55 EVP_PKEY_free(params);
56 EVP_PKEY_CTX_free(ctx_params);
Zhiyi Zhang6701f3c2021-02-18 17:38:42 -080057 if (resultCode <= 0) {
58 NDN_THROW(std::runtime_error("Error in initiating ECDH"));
59 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070060}
61
62ECDHState::~ECDHState()
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070063{
Zhiyi Zhangbed854c2020-10-20 18:25:35 -070064 if (m_privkey != nullptr) {
65 EVP_PKEY_free(m_privkey);
66 }
67}
68
Zhiyi Zhang3b9a5032021-02-18 11:15:09 -080069const std::vector <uint8_t>&
Zhiyi Zhangbed854c2020-10-20 18:25:35 -070070ECDHState::getSelfPubKey()
71{
72 auto privECKey = EVP_PKEY_get1_EC_KEY(m_privkey);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070073 auto ecPoint = EC_KEY_get0_public_key(privECKey);
Zhiyi Zhangbed854c2020-10-20 18:25:35 -070074 auto group = EC_KEY_get0_group(privECKey);
Zhiyi Zhang5e74ecd2020-10-21 12:52:25 -070075 auto requiredBufLen = EC_POINT_point2oct(group, ecPoint, POINT_CONVERSION_UNCOMPRESSED, nullptr, 0, nullptr);
Zhiyi Zhangbed854c2020-10-20 18:25:35 -070076 m_pubKey.resize(requiredBufLen);
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -080077 auto resultCode = EC_POINT_point2oct(group, ecPoint, POINT_CONVERSION_UNCOMPRESSED,
78 m_pubKey.data(), requiredBufLen, nullptr);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070079 EC_KEY_free(privECKey);
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -080080 if (resultCode == 0) {
81 NDN_THROW(std::runtime_error("Error in getting EC Public Key in the format of octet string"));
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070082 }
Zhiyi Zhangbed854c2020-10-20 18:25:35 -070083 return m_pubKey;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070084}
85
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -080086const std::vector<uint8_t>&
Zhiyi Zhang3b9a5032021-02-18 11:15:09 -080087ECDHState::deriveSecret(const std::vector <uint8_t>& peerKey)
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070088{
Zhiyi Zhangbed854c2020-10-20 18:25:35 -070089 // prepare self private key
90 auto privECKey = EVP_PKEY_get1_EC_KEY(m_privkey);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070091 auto group = EC_KEY_get0_group(privECKey);
Zhiyi Zhangbed854c2020-10-20 18:25:35 -070092 EC_KEY_free(privECKey);
93 // prepare the peer public key
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -070094 auto peerPoint = EC_POINT_new(group);
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -080095 EC_POINT_oct2point(group, peerPoint, peerKey.data(), peerKey.size(), nullptr);
Zhiyi Zhangdef00e42020-10-20 22:41:56 -070096 EC_KEY* ecPeerkey = EC_KEY_new();
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -080097 EC_KEY_set_group(ecPeerkey, group);
98 EC_KEY_set_public_key(ecPeerkey, peerPoint);
Zhiyi Zhangdef00e42020-10-20 22:41:56 -070099 EVP_PKEY* evpPeerkey = EVP_PKEY_new();
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800100 EVP_PKEY_set1_EC_KEY(evpPeerkey, ecPeerkey);
Zhiyi Zhangbed854c2020-10-20 18:25:35 -0700101 EC_KEY_free(ecPeerkey);
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700102 EC_POINT_free(peerPoint);
Zhiyi Zhangbed854c2020-10-20 18:25:35 -0700103 // ECDH context
Zhiyi Zhangdef00e42020-10-20 22:41:56 -0700104 EVP_PKEY_CTX* ctx = EVP_PKEY_CTX_new(m_privkey, nullptr);
Zhiyi Zhangdef00e42020-10-20 22:41:56 -0700105 // Initialize
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800106 EVP_PKEY_derive_init(ctx);
Zhiyi Zhangdef00e42020-10-20 22:41:56 -0700107 // Provide the peer public key
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800108 EVP_PKEY_derive_set_peer(ctx, evpPeerkey);
Zhiyi Zhangdef00e42020-10-20 22:41:56 -0700109 // Determine buffer length for shared secret
Zhiyi Zhangbed854c2020-10-20 18:25:35 -0700110 size_t secretLen = 0;
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800111 EVP_PKEY_derive(ctx, nullptr, &secretLen);
Zhiyi Zhangdef00e42020-10-20 22:41:56 -0700112 m_secret.resize(secretLen);
113 // Derive the shared secret
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800114 auto resultCode = EVP_PKEY_derive(ctx, m_secret.data(), &secretLen);
Zhiyi Zhangbed854c2020-10-20 18:25:35 -0700115 EVP_PKEY_CTX_free(ctx);
116 EVP_PKEY_free(evpPeerkey);
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800117 if (resultCode == 0) {
118 NDN_THROW(std::runtime_error("Error when calling ECDH"));
119 }
Zhiyi Zhangbed854c2020-10-20 18:25:35 -0700120 return m_secret;
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800121
122// // prepare self private key
123// auto privECKey = EVP_PKEY_get1_EC_KEY(m_privkey);
124// if (privECKey == nullptr) {
125// NDN_THROW(std::runtime_error("Cannot not get key when calling EVP_PKEY_get1_EC_KEY()"));
126// }
127// auto group = EC_KEY_get0_group(privECKey);
128// EC_KEY_free(privECKey);
129// // prepare the peer public key
130// auto peerPoint = EC_POINT_new(group);
131// if (peerPoint == nullptr) {
132// NDN_THROW(std::runtime_error("Cannot create the EC_POINT for peer key when calling EC_POINT_new()"));
133// }
134// if (EC_POINT_oct2point(group, peerPoint, peerKey.data(), peerKey.size(), nullptr) == 0) {
135// EC_POINT_free(peerPoint);
136// NDN_THROW(std::runtime_error("Cannot convert peer's key into a EC point when calling EC_POINT_oct2point()"));
137// }
138// EC_KEY* ecPeerkey = EC_KEY_new();
139// if (ecPeerkey == nullptr) {
140// EC_POINT_free(peerPoint);
141// NDN_THROW(std::runtime_error("Cannot create EC_KEY for peer key when calling EC_KEY_new()"));
142// }
143// if (EC_KEY_set_group(ecPeerkey, group) != 1) {
144// EC_POINT_free(peerPoint);
145// NDN_THROW(std::runtime_error("Cannot set group for peer key's EC_KEY when calling EC_KEY_set_group()"));
146// }
147// if (EC_KEY_set_public_key(ecPeerkey, peerPoint) == 0) {
148// EC_KEY_free(ecPeerkey);
149// EC_POINT_free(peerPoint);
150// NDN_THROW(
151// std::runtime_error("Cannot initialize peer EC_KEY with the EC_POINT when calling EC_KEY_set_public_key()"));
152// }
153// EVP_PKEY* evpPeerkey = EVP_PKEY_new();
154// if (EVP_PKEY_set1_EC_KEY(evpPeerkey, ecPeerkey) == 0) {
155// EC_KEY_free(ecPeerkey);
156// EC_POINT_free(peerPoint);
157// NDN_THROW(std::runtime_error("Cannot create EVP_PKEY for peer key when calling EVP_PKEY_new()"));
158// }
159// EC_KEY_free(ecPeerkey);
160// EC_POINT_free(peerPoint);
161// // ECDH context
162// EVP_PKEY_CTX* ctx = EVP_PKEY_CTX_new(m_privkey, nullptr);
163// if (ctx == nullptr) {
164// EVP_PKEY_free(evpPeerkey);
165// NDN_THROW(std::runtime_error("Cannot create context for ECDH when calling EVP_PKEY_CTX_new()"));
166// }
167// // Initialize
168// if (1 != EVP_PKEY_derive_init(ctx)) {
169// EVP_PKEY_CTX_free(ctx);
170// EVP_PKEY_free(evpPeerkey);
171// NDN_THROW(std::runtime_error("Cannot initialize context for ECDH when calling EVP_PKEY_derive_init()"));
172// }
173// // Provide the peer public key
174// if (1 != EVP_PKEY_derive_set_peer(ctx, evpPeerkey)) {
175// EVP_PKEY_CTX_free(ctx);
176// EVP_PKEY_free(evpPeerkey);
177// NDN_THROW(std::runtime_error("Cannot set peer key for ECDH when calling EVP_PKEY_derive_set_peer()"));
178// }
179// // Determine buffer length for shared secret
180// size_t secretLen = 0;
181// if (1 != EVP_PKEY_derive(ctx, nullptr, &secretLen)) {
182// EVP_PKEY_CTX_free(ctx);
183// EVP_PKEY_free(evpPeerkey);
184// NDN_THROW(std::runtime_error("Cannot determine the needed buffer length when calling EVP_PKEY_derive()"));
185// }
186// m_secret.resize(secretLen);
187// // Derive the shared secret
188// if (1 != (EVP_PKEY_derive(ctx, m_secret.data(), &secretLen))) {
189// EVP_PKEY_CTX_free(ctx);
190// EVP_PKEY_free(evpPeerkey);
191// NDN_THROW(std::runtime_error("Cannot derive ECDH secret when calling EVP_PKEY_derive()"));
192// }
193// EVP_PKEY_CTX_free(ctx);
194// EVP_PKEY_free(evpPeerkey);
195// return m_secret;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700196}
197
Zhiyi Zhangf12ee302020-10-14 17:46:44 -0700198void
Zhiyi Zhang11cf7eb2020-10-20 15:43:36 -0700199hmacSha256(const uint8_t* data, size_t dataLen,
Zhiyi Zhang199508a2020-10-21 10:45:50 -0700200 const uint8_t* key, size_t keyLen,
201 uint8_t* result)
Davide Pesavento368341b2019-08-13 23:57:50 -0400202{
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800203 auto ret = HMAC(EVP_sha256(), key, keyLen, data, dataLen, result, nullptr);
Zhiyi Zhangf12ee302020-10-14 17:46:44 -0700204 if (ret == nullptr) {
Zhiyi Zhang5c059452020-10-16 17:43:31 -0700205 NDN_THROW(std::runtime_error("Error computing HMAC when calling HMAC()"));
Zhiyi Zhangf12ee302020-10-14 17:46:44 -0700206 }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700207}
208
Zhiyi Zhang159ba632020-10-20 15:09:12 -0700209size_t
Zhiyi Zhang11cf7eb2020-10-20 15:43:36 -0700210hkdf(const uint8_t* secret, size_t secretLen, const uint8_t* salt,
211 size_t saltLen, uint8_t* output, size_t outputLen,
212 const uint8_t* info, size_t infoLen)
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700213{
Zhiyi Zhangf908f662020-10-21 12:55:10 -0700214 EVP_PKEY_CTX* pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, nullptr);
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800215 EVP_PKEY_derive_init(pctx);
216 EVP_PKEY_CTX_set_hkdf_md(pctx, EVP_sha256());
217 EVP_PKEY_CTX_set1_hkdf_salt(pctx, salt, saltLen);
218 EVP_PKEY_CTX_set1_hkdf_key(pctx, secret, secretLen);
219 EVP_PKEY_CTX_add1_hkdf_info(pctx, info, infoLen);
Zhiyi Zhang11cf7eb2020-10-20 15:43:36 -0700220 size_t outLen = outputLen;
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800221 auto resultCode = EVP_PKEY_derive(pctx, output, &outLen);
Zhiyi Zhang222810b2020-10-16 21:50:35 -0700222 EVP_PKEY_CTX_free(pctx);
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800223 if (resultCode == 0) {
224 NDN_THROW(std::runtime_error("Error when calling HKDF"));
225 }
Zhiyi Zhang159ba632020-10-20 15:09:12 -0700226 return outLen;
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800227
228// if (EVP_PKEY_derive_init(pctx) <= 0) {
229// EVP_PKEY_CTX_free(pctx);
230// NDN_THROW(std::runtime_error("HKDF: Cannot init ctx when calling EVP_PKEY_derive_init()"));
231// }
232// if (EVP_PKEY_CTX_set_hkdf_md(pctx, EVP_sha256()) <= 0) {
233// EVP_PKEY_CTX_free(pctx);
234// NDN_THROW(std::runtime_error("HKDF: Cannot set md when calling EVP_PKEY_CTX_set_hkdf_md()"));
235// }
236// if (EVP_PKEY_CTX_set1_hkdf_salt(pctx, salt, saltLen) <= 0) {
237// EVP_PKEY_CTX_free(pctx);
238// NDN_THROW(std::runtime_error("HKDF: Cannot set salt when calling EVP_PKEY_CTX_set1_hkdf_salt()"));
239// }
240// if (EVP_PKEY_CTX_set1_hkdf_key(pctx, secret, secretLen) <= 0) {
241// EVP_PKEY_CTX_free(pctx);
242// NDN_THROW(std::runtime_error("HKDF: Cannot set secret when calling EVP_PKEY_CTX_set1_hkdf_key()"));
243// }
244// if (EVP_PKEY_CTX_add1_hkdf_info(pctx, info, infoLen) <= 0) {
245// EVP_PKEY_CTX_free(pctx);
246// NDN_THROW(std::runtime_error("HKDF: Cannot set info when calling EVP_PKEY_CTX_add1_hkdf_info()"));
247// }
248// size_t outLen = outputLen;
249// if (EVP_PKEY_derive(pctx, output, &outLen) <= 0) {
250// EVP_PKEY_CTX_free(pctx);
251// NDN_THROW(std::runtime_error("HKDF: Cannot derive result when calling EVP_PKEY_derive()"));
252// }
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700253}
254
Zhiyi Zhange5a07c92020-10-21 10:51:37 -0700255size_t
Zhiyi Zhang11cf7eb2020-10-20 15:43:36 -0700256aesGcm128Encrypt(const uint8_t* plaintext, size_t plaintextLen, const uint8_t* associated, size_t associatedLen,
Zhiyi Zhangf908f662020-10-21 12:55:10 -0700257 const uint8_t* key, const uint8_t* iv, uint8_t* ciphertext, uint8_t* tag)
Zhiyi Zhanga67fa462020-04-19 13:48:03 -0700258{
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800259 int len = 0;
260 size_t ciphertextLen = 0;
261 EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
262 EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), nullptr, nullptr, nullptr);
263 EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 12, nullptr);
264 EVP_EncryptInit_ex(ctx, nullptr, nullptr, key, iv);
265 EVP_EncryptUpdate(ctx, nullptr, &len, associated, associatedLen);
266 EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintextLen);
Zhiyi Zhang11cf7eb2020-10-20 15:43:36 -0700267 ciphertextLen = len;
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800268 EVP_EncryptFinal_ex(ctx, ciphertext + len, &len);
269 auto resultCode = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, 16, tag);
Zhiyi Zhanga67fa462020-04-19 13:48:03 -0700270 EVP_CIPHER_CTX_free(ctx);
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800271 if (resultCode == 0) {
272 NDN_THROW(std::runtime_error("Error in encryption plaintext with AES GCM"));
273 }
Zhiyi Zhang11cf7eb2020-10-20 15:43:36 -0700274 return ciphertextLen;
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800275
276// if (!(ctx = EVP_CIPHER_CTX_new())) {
277// NDN_THROW(std::runtime_error("Cannot create and initialise the context when calling EVP_CIPHER_CTX_new()"));
278// }
279// if (1 != EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), nullptr, nullptr, nullptr)) {
280// EVP_CIPHER_CTX_free(ctx);
281// NDN_THROW(std::runtime_error("Cannot initialize the encryption operation when calling EVP_EncryptInit_ex()"));
282// }
283// if (1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 12, nullptr)) {
284// EVP_CIPHER_CTX_free(ctx);
285// NDN_THROW(std::runtime_error("Cannot set IV length when calling EVP_CIPHER_CTX_ctrl()"));
286// }
287// if (1 != EVP_EncryptInit_ex(ctx, nullptr, nullptr, key, iv)) {
288// EVP_CIPHER_CTX_free(ctx);
289// NDN_THROW(std::runtime_error("Cannot initialize key and IV when calling EVP_EncryptInit_ex()"));
290// }
291// if (1 != EVP_EncryptUpdate(ctx, nullptr, &len, associated, associatedLen)) {
292// EVP_CIPHER_CTX_free(ctx);
293// NDN_THROW(std::runtime_error("Cannot set associated authentication data when calling EVP_EncryptUpdate()"));
294// }
295// if (1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintextLen)) {
296// EVP_CIPHER_CTX_free(ctx);
297// NDN_THROW(std::runtime_error("Cannot encrypt when calling EVP_EncryptUpdate()"));
298// }
299// ciphertextLen = len;
300// if (1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) {
301// EVP_CIPHER_CTX_free(ctx);
302// NDN_THROW(std::runtime_error("Cannot finalise the encryption when calling EVP_EncryptFinal_ex()"));
303// }
304// ciphertextLen += len;
305// if (1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, 16, tag)) {
306// EVP_CIPHER_CTX_free(ctx);
307// NDN_THROW(std::runtime_error("Cannot get tag when calling EVP_CIPHER_CTX_ctrl()"));
308// }
Zhiyi Zhanga67fa462020-04-19 13:48:03 -0700309}
310
Zhiyi Zhange5a07c92020-10-21 10:51:37 -0700311size_t
Zhiyi Zhang11cf7eb2020-10-20 15:43:36 -0700312aesGcm128Decrypt(const uint8_t* ciphertext, size_t ciphertextLen, const uint8_t* associated, size_t associatedLen,
Zhiyi Zhangf908f662020-10-21 12:55:10 -0700313 const uint8_t* tag, const uint8_t* key, const uint8_t* iv, uint8_t* plaintext)
Zhiyi Zhanga67fa462020-04-19 13:48:03 -0700314{
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800315 int len = 0;
316 size_t plaintextLen = 0;
317 EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
318 EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), nullptr, nullptr, nullptr);
319 EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 12, nullptr);
320 EVP_DecryptInit_ex(ctx, nullptr, nullptr, key, iv);
321 EVP_DecryptUpdate(ctx, nullptr, &len, associated, associatedLen);
322 EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertextLen);
Zhiyi Zhang11cf7eb2020-10-20 15:43:36 -0700323 plaintextLen = len;
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800324 EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, 16, const_cast<void*>(reinterpret_cast<const void*>(tag)));
325 auto resultCode = EVP_DecryptFinal_ex(ctx, plaintext + len, &len);
326 plaintextLen += len;
Zhiyi Zhanga67fa462020-04-19 13:48:03 -0700327 EVP_CIPHER_CTX_free(ctx);
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800328 if (resultCode == 0) {
329 NDN_THROW(std::runtime_error("Error in decrypting ciphertext with AES GCM"));
Zhiyi Zhanga67fa462020-04-19 13:48:03 -0700330 }
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800331 return plaintextLen;
332
333// if (!(ctx = EVP_CIPHER_CTX_new())) {
334// NDN_THROW(std::runtime_error("Cannot create and initialise the context when calling EVP_CIPHER_CTX_new()"));
335// }
336// if (!EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), nullptr, nullptr, nullptr)) {
337// EVP_CIPHER_CTX_free(ctx);
338// NDN_THROW(std::runtime_error("Cannot initialise the decryption operation when calling EVP_DecryptInit_ex()"));
339// }
340// if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 12, nullptr)) {
341// EVP_CIPHER_CTX_free(ctx);
342// NDN_THROW(std::runtime_error("Cannot set IV length when calling EVP_CIPHER_CTX_ctrl"));
343// }
344// if (!EVP_DecryptInit_ex(ctx, nullptr, nullptr, key, iv)) {
345// EVP_CIPHER_CTX_free(ctx);
346// NDN_THROW(std::runtime_error("Cannot initialise key and IV when calling EVP_DecryptInit_ex()"));
347// }
348// if (!EVP_DecryptUpdate(ctx, nullptr, &len, associated, associatedLen)) {
349// EVP_CIPHER_CTX_free(ctx);
350// NDN_THROW(std::runtime_error("Cannot set associated authentication data when calling EVP_EncryptUpdate()"));
351// }
352// if (!EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertextLen)) {
353// EVP_CIPHER_CTX_free(ctx);
354// NDN_THROW(std::runtime_error("Cannot decrypt when calling EVP_DecryptUpdate()"));
355// }
356// plaintextLen = len;
357// if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, 16, const_cast<void*>(reinterpret_cast<const void*>(tag)))) {
358// EVP_CIPHER_CTX_free(ctx);
359// NDN_THROW(std::runtime_error("Cannot set tag value when calling EVP_CIPHER_CTX_ctrl()"));
360// }
Zhiyi Zhanga67fa462020-04-19 13:48:03 -0700361}
362
Zhiyi Zhang886a2262020-12-24 15:19:33 -0800363// Can be removed after boost version 1.72, replaced by boost::endian::load_big_u32
364static uint32_t
Zhiyi Zhang3b9a5032021-02-18 11:15:09 -0800365loadBigU32(const std::vector <uint8_t>& iv, size_t pos)
Zhiyi Zhang886a2262020-12-24 15:19:33 -0800366{
367 uint32_t result = iv[pos] << 24 | iv[pos + 1] << 16 | iv[pos + 2] << 8 | iv[pos + 3];
368 return result;
369}
370
371// Can be removed after boost version 1.72, replaced by boost::endian::store_big_u32
372static void
373storeBigU32(uint8_t* iv, uint32_t counter)
374{
375 uint32_t temp = boost::endian::native_to_big(counter);
376 std::memcpy(iv, reinterpret_cast<const uint8_t*>(&temp), 4);
377 return;
378}
379
Zhiyi Zhang4f1c0102020-12-21 15:08:09 -0800380static void
Zhiyi Zhang3b9a5032021-02-18 11:15:09 -0800381updateIv(std::vector <uint8_t>& iv, size_t payloadSize)
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700382{
Zhiyi Zhang886a2262020-12-24 15:19:33 -0800383 // uint32_t counter = boost::endian::load_big_u32(&iv[8]);
384 uint32_t counter = loadBigU32(iv, 8);
Zhiyi Zhang199508a2020-10-21 10:45:50 -0700385 uint32_t increment = (payloadSize + 15) / 16;
Zhiyi Zhang4f1c0102020-12-21 15:08:09 -0800386 if (std::numeric_limits<uint32_t>::max() - counter <= increment) {
Zhiyi Zhangaeab4972020-10-22 22:20:40 -0700387 NDN_THROW(std::runtime_error("Error incrementing the AES block counter: "
Zhiyi Zhange11a2d62020-10-22 09:59:12 -0700388 "too many blocks have been encrypted for the same request instance"));
Zhiyi Zhang159ba632020-10-20 15:09:12 -0700389 }
390 else {
391 counter += increment;
392 }
Zhiyi Zhang886a2262020-12-24 15:19:33 -0800393 // boost::endian::store_big_u32(&iv[8], counter);
394 storeBigU32(&iv[8], counter);
Zhiyi Zhang4f1c0102020-12-21 15:08:09 -0800395}
Zhiyi Zhangc5d93a92020-10-14 17:07:35 -0700396
Zhiyi Zhang4f1c0102020-12-21 15:08:09 -0800397Block
Zhiyi Zhangc1e98152020-12-21 16:15:39 -0800398encodeBlockWithAesGcm128(uint32_t tlvType, const uint8_t* key,
399 const uint8_t* payload, size_t payloadSize,
400 const uint8_t* associatedData, size_t associatedDataSize,
Zhiyi Zhang3b9a5032021-02-18 11:15:09 -0800401 std::vector <uint8_t>& encryptionIv)
Zhiyi Zhang4f1c0102020-12-21 15:08:09 -0800402{
Zhiyi Zhang5e74ecd2020-10-21 12:52:25 -0700403 // The spec of AES encrypted payload TLV used in NDNCERT:
404 // https://github.com/named-data/ndncert/wiki/NDNCERT-Protocol-0.3#242-aes-gcm-encryption
Zhiyi Zhang222810b2020-10-16 21:50:35 -0700405 Buffer encryptedPayload(payloadSize);
Zhiyi Zhangc5d93a92020-10-14 17:07:35 -0700406 uint8_t tag[16];
Zhiyi Zhang4f1c0102020-12-21 15:08:09 -0800407 if (encryptionIv.empty()) {
408 encryptionIv.resize(12, 0);
409 random::generateSecureBytes(encryptionIv.data(), 8);
410 }
Zhiyi Zhang11cf7eb2020-10-20 15:43:36 -0700411 size_t encryptedPayloadLen = aesGcm128Encrypt(payload, payloadSize, associatedData, associatedDataSize,
Zhiyi Zhang4f1c0102020-12-21 15:08:09 -0800412 key, encryptionIv.data(), encryptedPayload.data(), tag);
tylerliu1f480be2020-11-10 13:02:53 -0800413 Block content(tlvType);
Zhiyi Zhang4f1c0102020-12-21 15:08:09 -0800414 content.push_back(makeBinaryBlock(tlv::InitializationVector, encryptionIv.data(), encryptionIv.size()));
Zhiyi Zhangc5d93a92020-10-14 17:07:35 -0700415 content.push_back(makeBinaryBlock(tlv::AuthenticationTag, tag, 16));
Zhiyi Zhang222810b2020-10-16 21:50:35 -0700416 content.push_back(makeBinaryBlock(tlv::EncryptedPayload, encryptedPayload.data(), encryptedPayloadLen));
Zhiyi Zhangc5d93a92020-10-14 17:07:35 -0700417 content.encode();
Zhiyi Zhang4f1c0102020-12-21 15:08:09 -0800418 // update IV's counter
419 updateIv(encryptionIv, payloadSize);
Zhiyi Zhangc5d93a92020-10-14 17:07:35 -0700420 return content;
421}
422
423Buffer
Zhiyi Zhang4f1c0102020-12-21 15:08:09 -0800424decodeBlockWithAesGcm128(const Block& block, const uint8_t* key,
425 const uint8_t* associatedData, size_t associatedDataSize,
Zhiyi Zhang1e5d6772021-02-18 17:35:46 -0800426 std::vector <uint8_t>& decryptionIv, const std::vector <uint8_t>& encryptionIv)
Zhiyi Zhangc5d93a92020-10-14 17:07:35 -0700427{
Zhiyi Zhang5e74ecd2020-10-21 12:52:25 -0700428 // The spec of AES encrypted payload TLV used in NDNCERT:
429 // https://github.com/named-data/ndncert/wiki/NDNCERT-Protocol-0.3#242-aes-gcm-encryption
Zhiyi Zhangc5d93a92020-10-14 17:07:35 -0700430 block.parse();
Zhiyi Zhangaeab4972020-10-22 22:20:40 -0700431 const auto& encryptedPayloadBlock = block.get(tlv::EncryptedPayload);
432 Buffer result(encryptedPayloadBlock.value_size());
Zhiyi Zhang3b9a5032021-02-18 11:15:09 -0800433 if (block.get(tlv::InitializationVector).value_size() != 12 ||
434 block.get(tlv::AuthenticationTag).value_size() != 16) {
Zhiyi Zhangde58e602021-02-17 23:09:02 -0800435 NDN_THROW(std::runtime_error("Error when decrypting the AES Encrypted Block: "
Zhiyi Zhang3b9a5032021-02-18 11:15:09 -0800436 "The observed IV or Authentication Tag is of an unexpected size."));
Zhiyi Zhangde58e602021-02-17 23:09:02 -0800437 }
Zhiyi Zhang3b9a5032021-02-18 11:15:09 -0800438 std::vector <uint8_t> observedDecryptionIv(block.get(tlv::InitializationVector).value(),
439 block.get(tlv::InitializationVector).value() + 12);
440 if (!encryptionIv.empty()) {
441 if (std::equal(observedDecryptionIv.begin(), observedDecryptionIv.begin() + 8, encryptionIv.begin())) {
Zhiyi Zhang4f1c0102020-12-21 15:08:09 -0800442 NDN_THROW(std::runtime_error("Error when decrypting the AES Encrypted Block: "
Zhiyi Zhang3b9a5032021-02-18 11:15:09 -0800443 "The observed IV's the random component should be different from ours."));
Zhiyi Zhangde58e602021-02-17 23:09:02 -0800444 }
Zhiyi Zhang4f1c0102020-12-21 15:08:09 -0800445 }
Zhiyi Zhang3b9a5032021-02-18 11:15:09 -0800446 if (!decryptionIv.empty()) {
447 if (loadBigU32(observedDecryptionIv, 8) < loadBigU32(decryptionIv, 8) ||
448 !std::equal(observedDecryptionIv.begin(), observedDecryptionIv.begin() + 8, decryptionIv.begin())) {
449 NDN_THROW(std::runtime_error("Error when decrypting the AES Encrypted Block: "
450 "The observed IV's counter should be monotonically increasing "
451 "and the random component must be the same from the requester."));
452 }
453 }
454 decryptionIv = observedDecryptionIv;
Zhiyi Zhangaeab4972020-10-22 22:20:40 -0700455 auto resultLen = aesGcm128Decrypt(encryptedPayloadBlock.value(), encryptedPayloadBlock.value_size(),
Zhiyi Zhangf908f662020-10-21 12:55:10 -0700456 associatedData, associatedDataSize, block.get(tlv::AuthenticationTag).value(),
Zhiyi Zhang3b9a5032021-02-18 11:15:09 -0800457 key, decryptionIv.data(), result.data());
Zhiyi Zhangaeab4972020-10-22 22:20:40 -0700458 if (resultLen != encryptedPayloadBlock.value_size()) {
Zhiyi Zhangaeab4972020-10-22 22:20:40 -0700459 NDN_THROW(std::runtime_error("Error when decrypting the AES Encrypted Block: "
Zhiyi Zhang3b9a5032021-02-18 11:15:09 -0800460 "Decrypted payload is of an unexpected size."));
Zhiyi Zhangc5d93a92020-10-14 17:07:35 -0700461 }
Zhiyi Zhang4f1c0102020-12-21 15:08:09 -0800462 updateIv(decryptionIv, resultLen);
Zhiyi Zhangc5d93a92020-10-14 17:07:35 -0700463 return result;
Zhiyi Zhangaf7c2902019-03-14 22:13:21 -0700464}
465
Zhiyi Zhange4891b72020-10-10 15:11:57 -0700466} // namespace ndncert
467} // namespace ndn