-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathCryptoInterface.c
More file actions
494 lines (411 loc) · 14.3 KB
/
CryptoInterface.c
File metadata and controls
494 lines (411 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
/*
* Copyright (c) 2025 The Johns Hopkins University Applied Physics
* Laboratory LLC.
*
* This file is part of the Bundle Protocol Security Library (BSL).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This work was performed for the Jet Propulsion Laboratory, California
* Institute of Technology, sponsored by the United States Government under
* the prime contract 80NM0018D0004 between the Caltech and NASA under
* subcontract 1700763.
*/
/** @file
* Backend cryptography implementation
* @ingroup backend_dyn
*/
#include <BPSecLib_Private.h>
#include <CryptoInterface.h>
#include <m-dict.h>
#include <m-string.h>
#include <openssl/err.h>
#include <openssl/rand.h>
/**
* Struct to hold private key information
*/
typedef struct BSLB_CryptoKey_s
{
/// Pointer to OpenSSL PKEY struct (used in hmac ctx)
EVP_PKEY *pkey;
/// Pointer to raw key information (used in cipher ctx)
BSL_Data_t raw;
} BSLB_CryptoKey_t;
static int BSLB_CryptoKey_Deinit(BSLB_CryptoKey_t *key)
{
fflush(stdout); // NOLINT
EVP_PKEY_free(key->pkey);
BSL_Data_Deinit(&(key->raw));
return 0;
}
// NOLINTBEGIN
/// @cond Doxygen_Suppress
#define M_OPL_BSLB_CryptoKey_t() M_OPEXTEND(M_POD_OPLIST, CLEAR(API_2(BSLB_CryptoKey_Deinit)))
/// Stable dict of crypto keys (key: key ID | value: key)
DICT_DEF2(BSLB_CryptoKeyDict, string_t, STRING_OPLIST, BSLB_CryptoKey_t, M_OPL_BSLB_CryptoKey_t())
/// @endcond
/// Crypto key registry
static BSLB_CryptoKeyDict_t StaticKeyRegistry;
static pthread_mutex_t StaticCryptoMutex = PTHREAD_MUTEX_INITIALIZER;
// NOLINTEND
void BSL_CryptoInit(void)
{
BSLB_CryptoKeyDict_init(StaticKeyRegistry);
}
void BSL_CryptoDeinit(void)
{
BSLB_CryptoKeyDict_clear(StaticKeyRegistry);
}
int BSL_Crypto_UnwrapKey(BSL_Data_t *unwrapped_key_output, BSL_Data_t wrapped_key_plaintext, const char *key_id,
size_t aes_variant)
{
const EVP_CIPHER *cipher = (aes_variant == BSL_CRYPTO_AES_128) ? EVP_aes_128_wrap() : EVP_aes_256_wrap();
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
assert(ctx != NULL);
// Give the actual key extra margin on each side.
uint8_t keybuf[128];
uint8_t *key = &keybuf[16];
memset(keybuf, 0, sizeof(keybuf));
size_t keylen = 0;
assert(BSLB_Crypto_GetRegistryKey(key_id, (const uint8_t **)&key, &keylen) == 0);
assert(keylen > 0);
int dec_result = EVP_DecryptInit_ex(ctx, cipher, NULL, key, NULL);
assert(dec_result == 1);
EVP_CIPHER_CTX_set_padding(ctx, 0);
int unwrapped_key_len = 16;
int decrypt_res = EVP_DecryptUpdate(ctx, unwrapped_key_output->ptr, &unwrapped_key_len, wrapped_key_plaintext.ptr,
(int)wrapped_key_plaintext.len);
if (decrypt_res != 1)
{
BSL_LOG_ERR("EVP_DecryptUpdate: %s", ERR_error_string(ERR_get_error(), NULL));
EVP_CIPHER_CTX_free(ctx);
return -1;
}
unwrapped_key_output->len = (size_t)unwrapped_key_len;
int final_len = 0;
int res = EVP_DecryptFinal_ex(ctx, &unwrapped_key_output->ptr[unwrapped_key_output->len], &final_len);
if (res != 1)
{
BSL_LOG_ERR("Failed DecryptFinal: %s", ERR_error_string(ERR_get_error(), NULL));
EVP_CIPHER_CTX_free(ctx);
return -1;
}
unwrapped_key_output->len += (size_t)final_len;
EVP_CIPHER_CTX_free(ctx);
return 0;
}
int BSL_Crypto_WrapKey(BSL_Data_t *wrapped_key, BSL_Data_t cek, const char *content_key_id, size_t aes_variant)
{
const EVP_CIPHER *cipher = (aes_variant == BSL_CRYPTO_AES_128) ? EVP_aes_128_wrap() : EVP_aes_256_wrap();
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL)
{
BSL_LOG_ERR("Could not create cipher context");
return -1;
}
uint8_t keybuf[128];
uint8_t *key = &keybuf[16];
memset(keybuf, 0, sizeof(keybuf));
size_t keylen = 64;
// TODO(bvb) replace w error checking
BSL_LOG_INFO("Content key ID = %lu", cek);
int got_crypto_key = BSLB_Crypto_GetRegistryKey(content_key_id, (const uint8_t **)&key, &keylen);
assert(got_crypto_key == 0);
assert(keylen > 0);
int enc_result = EVP_EncryptInit_ex(ctx, cipher, NULL, cek.ptr, NULL);
if (!enc_result)
{
EVP_CIPHER_CTX_free(ctx);
return -1;
}
int len = (int)wrapped_key->len;
if (!EVP_EncryptUpdate(ctx, wrapped_key->ptr, &len,
// (int*)&wrapped_key->len,
key, (int)keylen))
{
EVP_CIPHER_CTX_free(ctx);
return -2;
}
wrapped_key->len = (size_t)len;
int final_len = 0;
if (!EVP_EncryptFinal_ex(ctx, &wrapped_key->ptr[wrapped_key->len], &final_len))
{
EVP_CIPHER_CTX_free(ctx);
return -1;
}
wrapped_key->len += (size_t)final_len;
EVP_CIPHER_CTX_free(ctx);
return 0;
}
int BSL_AuthCtx_Init(BSL_AuthCtx_t *hmac_ctx, const char *keyid, BSL_CryptoCipherSHAVariant_e sha_var)
{
CHK_ARG_NONNULL(hmac_ctx);
hmac_ctx->libhandle = EVP_MD_CTX_new();
CHK_PRECONDITION(hmac_ctx->libhandle != NULL);
hmac_ctx->SHA_variant = sha_var;
const EVP_MD *sha = NULL;
switch (hmac_ctx->SHA_variant)
{
case BSL_CRYPTO_SHA_256:
sha = EVP_sha256();
break;
case BSL_CRYPTO_SHA_384:
sha = EVP_sha384();
break;
case BSL_CRYPTO_SHA_512:
sha = EVP_sha512();
break;
default:
BSL_LOG_ERR("Invalid SHA variant");
return BSL_ERR_FAILURE;
}
string_t keyid_str;
string_init_set_str(keyid_str, keyid);
pthread_mutex_lock(&StaticCryptoMutex);
const BSLB_CryptoKey_t *key_info = BSLB_CryptoKeyDict_cget(StaticKeyRegistry, keyid_str);
if (key_info == NULL)
{
// Special case which should not happen
BSL_LOG_ERR("Failed to lookup Key ID %" PRId64, keyid);
pthread_mutex_unlock(&StaticCryptoMutex);
return BSL_ERR_NOT_FOUND;
}
int res = EVP_DigestSignInit(hmac_ctx->libhandle, NULL, sha, NULL, key_info->pkey);
pthread_mutex_unlock(&StaticCryptoMutex);
CHK_PROPERTY(res == 1);
hmac_ctx->block_size = (size_t)EVP_MD_CTX_block_size(hmac_ctx->libhandle);
return 0;
}
int BSL_AuthCtx_DigestBuffer(BSL_AuthCtx_t *hmac_ctx, const void *data, size_t data_len)
{
assert(data != NULL);
int res = EVP_DigestSignUpdate(hmac_ctx->libhandle, data, data_len);
CHK_PROPERTY(res == 1);
return 0;
}
int BSL_AuthCtx_DigestSeq(BSL_AuthCtx_t *hmac_ctx, BSL_SeqReader_t *reader)
{
uint8_t buf[hmac_ctx->block_size];
size_t block_size = hmac_ctx->block_size;
while (block_size == hmac_ctx->block_size)
{
BSL_SeqReader_Get(reader, buf, &block_size);
EVP_DigestSignUpdate(hmac_ctx->libhandle, buf, block_size);
}
return 0;
}
int BSL_AuthCtx_Finalize(BSL_AuthCtx_t *hmac_ctx, void **hmac, size_t *hmac_len)
{
size_t req = 0;
int res = EVP_DigestSignFinal(hmac_ctx->libhandle, NULL, &req);
CHK_PROPERTY(res == 1);
*hmac_len = req;
res = EVP_DigestSignFinal(hmac_ctx->libhandle, *hmac, hmac_len);
CHK_PROPERTY(res == 1);
return 0;
}
int BSL_AuthCtx_Deinit(BSL_AuthCtx_t *hmac_ctx)
{
EVP_MD_CTX_free(hmac_ctx->libhandle);
return 0;
}
int BSL_Cipher_Init(BSL_Cipher_t *cipher_ctx, BSL_CipherMode_e enc, BSL_CryptoCipherAESVariant_e aes_var,
const void *init_vec, int iv_len, BSL_Data_t content_enc_key)
{
assert(cipher_ctx != NULL);
assert(init_vec != NULL);
assert(content_enc_key.ptr != NULL);
assert(content_enc_key.len > 0);
cipher_ctx->libhandle = EVP_CIPHER_CTX_new();
cipher_ctx->enc = enc;
cipher_ctx->AES_variant = aes_var;
const EVP_CIPHER *cipher = NULL;
switch (cipher_ctx->AES_variant)
{
case BSL_CRYPTO_AES_128:
cipher = EVP_aes_128_gcm();
break;
case BSL_CRYPTO_AES_256:
cipher = EVP_aes_256_gcm();
break;
default:
BSL_LOG_ERR("Invalid AES variant");
return BSL_ERR_FAILURE;
}
int res =
EVP_CipherInit_ex(cipher_ctx->libhandle, cipher, NULL, NULL, NULL, (cipher_ctx->enc == BSL_CRYPTO_ENCRYPT));
CHK_PROPERTY(res == 1);
cipher_ctx->block_size = (size_t)EVP_CIPHER_CTX_block_size(cipher_ctx->libhandle);
res = EVP_CIPHER_CTX_ctrl(cipher_ctx->libhandle, EVP_CTRL_GCM_SET_IVLEN, iv_len, NULL);
CHK_PROPERTY(res == 1);
res = EVP_CipherInit_ex(cipher_ctx->libhandle, NULL, NULL, content_enc_key.ptr, init_vec, -1);
CHK_PROPERTY(res == 1);
return 0;
}
int BSL_Cipher_AddAAD(BSL_Cipher_t *cipher_ctx, const void *aad, int aad_len)
{
// len needs to be passed or function call will crash program, no NULL checking on that param it seems
int len = 0;
int res = EVP_CipherUpdate(cipher_ctx->libhandle, NULL, &len, aad, aad_len);
CHK_PROPERTY(res == 1);
return 0;
}
int BSL_Cipher_AddData(BSL_Cipher_t *cipher_ctx, BSL_Data_t plaintext, BSL_Data_t ciphertext)
{
assert(cipher_ctx != NULL);
int cipherlen = (int)ciphertext.len;
if (EVP_CipherUpdate(cipher_ctx->libhandle, ciphertext.ptr, &cipherlen, plaintext.ptr, (int)plaintext.len) != 1)
{
return -1;
}
return cipherlen;
}
int BSL_Cipher_AddSeq(BSL_Cipher_t *cipher_ctx, BSL_SeqReader_t *reader, BSL_SeqWriter_t *writer)
{
uint8_t read_buf[cipher_ctx->block_size];
uint8_t write_buf[cipher_ctx->block_size];
size_t block_size = cipher_ctx->block_size;
while (block_size == (cipher_ctx->block_size))
{
BSL_SeqReader_Get(reader, read_buf, &block_size);
int block_size_int = (int)block_size;
int res = EVP_CipherUpdate(cipher_ctx->libhandle, write_buf, &block_size_int, read_buf, block_size_int);
CHK_PROPERTY(res == 1);
block_size = (size_t)block_size_int;
BSL_SeqWriter_Put(writer, write_buf, &block_size);
}
return 0;
}
int BSL_Cipher_GetTag(BSL_Cipher_t *cipher_ctx, void **tag)
{
int res = EVP_CIPHER_CTX_ctrl(cipher_ctx->libhandle, EVP_CTRL_GCM_GET_TAG, BSL_CRYPTO_AESGCM_AUTH_TAG_LEN, *tag);
CHK_PROPERTY(res == 1);
return 0;
}
int BSL_Cipher_SetTag(BSL_Cipher_t *cipher_ctx, const void *tag)
{
int res =
EVP_CIPHER_CTX_ctrl(cipher_ctx->libhandle, EVP_CTRL_GCM_SET_TAG, BSL_CRYPTO_AESGCM_AUTH_TAG_LEN, (void *)tag);
BSL_LOG_INFO("Completed EVP_CIPHER_CTX_ctrl *tag=%p", (uint8_t *)tag);
CHK_PROPERTY(res == 1);
return 0;
}
int BSL_Cipher_FinalizeData(BSL_Cipher_t *cipher_ctx, BSL_Data_t *extra)
{
CHK_ARG_NONNULL(cipher_ctx);
CHK_ARG_EXPR(extra->ptr != NULL);
uint8_t buf[EVP_CIPHER_CTX_block_size(cipher_ctx->libhandle)];
CHK_PRECONDITION(extra->len >= sizeof(buf));
BSL_LOG_DEBUG("extra: ptr=0x%p len=%lu", extra->ptr, extra->len);
int len = 0;
int res = EVP_CipherFinal_ex(cipher_ctx->libhandle, buf, &len);
if (res != 1)
{
BSL_LOG_ERR("%s", ERR_error_string(ERR_get_error(), NULL));
}
CHK_PROPERTY(res == 1);
BSL_LOG_DEBUG("extra->len = %lu", extra->len);
memset(extra->ptr, 0, extra->len);
BSL_LOG_INFO("Completed EVP_CipherFinal_ex");
if (len > 0)
{
memcpy(extra->ptr, buf, sizeof(buf));
extra->len = len;
}
return 0;
}
int BSL_Cipher_FinalizeSeq(BSL_Cipher_t *cipher_ctx, BSL_SeqWriter_t *writer)
{
// finalize can add 1 cipher block
uint8_t buf[EVP_CIPHER_CTX_block_size(cipher_ctx->libhandle)];
int len = 0;
int res = EVP_CipherFinal_ex(cipher_ctx->libhandle, buf, &len);
CHK_PROPERTY(res == 1);
if (len > 0)
{
BSL_SeqWriter_Put(writer, buf, (size_t *)&len);
}
return 0;
}
int BSL_Cipher_Deinit(BSL_Cipher_t *cipher_ctx)
{
CHK_ARG_NONNULL(cipher_ctx);
EVP_CIPHER_CTX_free(cipher_ctx->libhandle);
memset(cipher_ctx, 0, sizeof(*cipher_ctx));
return BSL_SUCCESS;
}
int BSL_Crypto_GenKey(uint8_t *key_buffer, size_t key_length)
{
CHK_ARG_NONNULL(key_buffer);
CHK_ARG_EXPR(key_length == 16 || key_length == 32);
int key_length_int = (int)key_length;
if (RAND_bytes(key_buffer, key_length_int) != 1)
{
OPENSSL_cleanse(key_buffer, key_length_int);
return -2;
}
return BSL_SUCCESS;
}
int BSL_Crypto_GenIV(void *buf, int size)
{
CHK_ARG_NONNULL(buf);
if (!(size >= 8 && size <= 16))
{
return -1;
}
memset(buf, 0, size);
CHK_PROPERTY(RAND_bytes((unsigned char *)buf, size) == 1);
return 0;
}
int BSL_Crypto_AddRegistryKey(const char *keyid, const uint8_t *secret, size_t secret_len)
{
CHK_ARG_NONNULL(secret);
CHK_ARG_EXPR(secret_len > 0);
BSLB_CryptoKey_t key;
EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HMAC, NULL);
int res = EVP_PKEY_keygen_init(ctx);
CHK_PROPERTY(res == 1);
key.pkey = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, secret, (int)secret_len);
EVP_PKEY_CTX_free(ctx);
BSL_Data_Init(&key.raw);
int ecode = 0;
if ((ecode = BSL_Data_CopyFrom(&key.raw, secret_len, secret)) < 0)
{
BSL_LOG_ERR("Failed to copy key");
return ecode;
}
string_t keyid_str;
string_init_set_str(keyid_str, keyid);
pthread_mutex_lock(&StaticCryptoMutex);
BSLB_CryptoKeyDict_set_at(StaticKeyRegistry, keyid_str, key);
pthread_mutex_unlock(&StaticCryptoMutex);
return 0;
}
int BSLB_Crypto_GetRegistryKey(const char *keyid, const uint8_t **secret, size_t *secret_len)
{
CHK_ARG_NONNULL(secret);
// CHK_ARG_NONNULL(secret_len); // Note: secret_len CAN be NULL - this maybe should be fixed.
string_t keyid_str;
string_init_set_str(keyid_str, keyid);
pthread_mutex_lock(&StaticCryptoMutex);
const BSLB_CryptoKey_t *found = BSLB_CryptoKeyDict_cget(StaticKeyRegistry, keyid_str);
if (!found)
{
return BSL_ERR_NOT_FOUND;
}
*secret = found->raw.ptr;
if (secret_len)
{
*secret_len = found->raw.len;
}
pthread_mutex_unlock(&StaticCryptoMutex);
return BSL_SUCCESS;
}