-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathCHIPCryptoPALOpenSSL.cpp
1922 lines (1497 loc) · 68.2 KB
/
CHIPCryptoPALOpenSSL.cpp
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
*
* Copyright (c) 2020-2021 Project CHIP Authors
*
* 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.
*/
/**
* @file
* openSSL based implementation of CHIP crypto primitives
*/
#include "CHIPCryptoPAL.h"
#include <type_traits>
#include <openssl/bn.h>
#include <openssl/conf.h>
#include <openssl/ec.h>
#include <openssl/ecdsa.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>
#include <openssl/kdf.h>
#include <openssl/ossl_typ.h>
#include <openssl/pem.h>
#include <openssl/rand.h>
#include <openssl/sha.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <lib/core/CHIPSafeCasts.h>
#include <lib/support/BufferWriter.h>
#include <lib/support/CHIPArgParser.hpp>
#include <lib/support/CodeUtils.h>
#include <lib/support/SafeInt.h>
#include <lib/support/SafePointerCast.h>
#include <lib/support/logging/CHIPLogging.h>
#include <string.h>
namespace chip {
namespace Crypto {
#define kKeyLengthInBits 256
typedef struct stack_st_X509 X509_LIST;
enum class DigestType
{
SHA256
};
enum class ECName
{
None = 0,
P256v1 = 1,
};
static int _nidForCurve(ECName name)
{
switch (name)
{
case ECName::P256v1:
return EC_curve_nist2nid("P-256");
break;
default:
return NID_undef;
break;
}
}
static bool _isValidTagLength(size_t tag_length)
{
return tag_length == 8 || tag_length == 12 || tag_length == 16;
}
static bool _isValidKeyLength(size_t length)
{
// 16 bytes key for AES-CCM-128, 32 for AES-CCM-256
return length == 16 || length == 32;
}
static void _logSSLError()
{
unsigned long ssl_err_code = ERR_get_error();
while (ssl_err_code != 0)
{
const char * err_str_lib = ERR_lib_error_string(ssl_err_code);
const char * err_str_routine = ERR_func_error_string(ssl_err_code);
const char * err_str_reason = ERR_reason_error_string(ssl_err_code);
if (err_str_lib)
{
ChipLogError(Crypto, " ssl err %s %s %s\n", err_str_lib, err_str_routine, err_str_reason);
}
ssl_err_code = ERR_get_error();
}
}
static const EVP_MD * _digestForType(DigestType digestType)
{
switch (digestType)
{
case DigestType::SHA256:
return EVP_sha256();
break;
default:
return nullptr;
break;
}
}
CHIP_ERROR AES_CCM_encrypt(const uint8_t * plaintext, size_t plaintext_length, const uint8_t * aad, size_t aad_length,
const uint8_t * key, size_t key_length, const uint8_t * iv, size_t iv_length, uint8_t * ciphertext,
uint8_t * tag, size_t tag_length)
{
EVP_CIPHER_CTX * context = nullptr;
int bytesWritten = 0;
size_t ciphertext_length = 0;
CHIP_ERROR error = CHIP_NO_ERROR;
int result = 1;
const EVP_CIPHER * type = nullptr;
// Placeholder location for avoiding null params for plaintexts when
// size is zero.
uint8_t placeholder_empty_plaintext = 0;
// Ciphertext block to hold a finalized ciphertext block if output
// `ciphertext` buffer is nullptr or plaintext_length is zero (i.e.
// we are only doing auth and don't care about output).
uint8_t placeholder_ciphertext[kAES_CCM256_Block_Length];
bool ciphertext_was_null = (ciphertext == nullptr);
if (plaintext_length == 0)
{
if (plaintext == nullptr)
{
plaintext = &placeholder_empty_plaintext;
}
// Make sure we have at least 1 full block size buffer for the
// extraction of final block (required by OpenSSL EVP_EncryptFinal_ex)
if (ciphertext_was_null)
{
ciphertext = &placeholder_ciphertext[0];
}
}
VerifyOrExit((key_length == kAES_CCM128_Key_Length) || (key_length == kAES_CCM256_Key_Length),
error = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit((plaintext_length != 0) || ciphertext_was_null, error = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(plaintext != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(ciphertext != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(key != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(_isValidKeyLength(key_length), error = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(iv != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(iv_length > 0, error = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(CanCastTo<int>(iv_length), error = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(tag != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(_isValidTagLength(tag_length), error = CHIP_ERROR_INVALID_ARGUMENT);
// TODO: Remove suport for AES-256 since not in 1.0
// Determine crypto type by key length
type = (key_length == kAES_CCM128_Key_Length) ? EVP_aes_128_ccm() : EVP_aes_256_ccm();
context = EVP_CIPHER_CTX_new();
VerifyOrExit(context != nullptr, error = CHIP_ERROR_INTERNAL);
// Pass in cipher
result = EVP_EncryptInit_ex(context, type, nullptr, nullptr, nullptr);
VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL);
// Pass in IV length. Cast is safe because we checked with CanCastTo.
result = EVP_CIPHER_CTX_ctrl(context, EVP_CTRL_CCM_SET_IVLEN, static_cast<int>(iv_length), nullptr);
VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL);
// Pass in tag length. Cast is safe because we checked _isValidTagLength.
result = EVP_CIPHER_CTX_ctrl(context, EVP_CTRL_CCM_SET_TAG, static_cast<int>(tag_length), nullptr);
VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL);
// Pass in key + iv
result = EVP_EncryptInit_ex(context, nullptr, nullptr, Uint8::to_const_uchar(key), Uint8::to_const_uchar(iv));
VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL);
// Pass in plain text length
VerifyOrExit(CanCastTo<int>(plaintext_length), error = CHIP_ERROR_INVALID_ARGUMENT);
result = EVP_EncryptUpdate(context, nullptr, &bytesWritten, nullptr, static_cast<int>(plaintext_length));
VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL);
// Pass in AAD
if (aad_length > 0 && aad != nullptr)
{
VerifyOrExit(CanCastTo<int>(aad_length), error = CHIP_ERROR_INVALID_ARGUMENT);
result = EVP_EncryptUpdate(context, nullptr, &bytesWritten, Uint8::to_const_uchar(aad), static_cast<int>(aad_length));
VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL);
}
// Encrypt
VerifyOrExit(CanCastTo<int>(plaintext_length), error = CHIP_ERROR_INVALID_ARGUMENT);
result = EVP_EncryptUpdate(context, Uint8::to_uchar(ciphertext), &bytesWritten, Uint8::to_const_uchar(plaintext),
static_cast<int>(plaintext_length));
VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL);
VerifyOrExit((ciphertext_was_null && bytesWritten == 0) || (bytesWritten >= 0), error = CHIP_ERROR_INTERNAL);
ciphertext_length = static_cast<unsigned int>(bytesWritten);
// Finalize encryption
result = EVP_EncryptFinal_ex(context, ciphertext + ciphertext_length, &bytesWritten);
VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL);
VerifyOrExit(bytesWritten >= 0 && bytesWritten <= static_cast<int>(plaintext_length), error = CHIP_ERROR_INTERNAL);
// Get tag
VerifyOrExit(CanCastTo<int>(tag_length), error = CHIP_ERROR_INVALID_ARGUMENT);
result = EVP_CIPHER_CTX_ctrl(context, EVP_CTRL_CCM_GET_TAG, static_cast<int>(tag_length), Uint8::to_uchar(tag));
VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL);
exit:
if (context != nullptr)
{
EVP_CIPHER_CTX_free(context);
context = nullptr;
}
return error;
}
CHIP_ERROR AES_CCM_decrypt(const uint8_t * ciphertext, size_t ciphertext_length, const uint8_t * aad, size_t aad_length,
const uint8_t * tag, size_t tag_length, const uint8_t * key, size_t key_length, const uint8_t * iv,
size_t iv_length, uint8_t * plaintext)
{
EVP_CIPHER_CTX * context = nullptr;
CHIP_ERROR error = CHIP_NO_ERROR;
int bytesOutput = 0;
int result = 1;
const EVP_CIPHER * type = nullptr;
// Placeholder location for avoiding null params for ciphertext when
// size is zero.
uint8_t placeholder_empty_ciphertext = 0;
// Plaintext block to hold a finalized plaintext block if output
// `plaintext` buffer is nullptr or ciphertext_length is zero (i.e.
// we are only doing auth and don't care about output).
uint8_t placeholder_plaintext[kAES_CCM256_Block_Length];
bool plaintext_was_null = (plaintext == nullptr);
if (ciphertext_length == 0)
{
if (ciphertext == nullptr)
{
ciphertext = &placeholder_empty_ciphertext;
}
// Make sure we have at least 1 full block size buffer for the
// extraction of final block (required by OpenSSL EVP_DecryptFinal_ex)
if (plaintext_was_null)
{
plaintext = &placeholder_plaintext[0];
}
}
VerifyOrExit((key_length == kAES_CCM128_Key_Length) || (key_length == kAES_CCM256_Key_Length),
error = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(ciphertext != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(plaintext != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(tag != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(_isValidTagLength(tag_length), error = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(key != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(_isValidKeyLength(key_length), error = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(iv != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(iv_length > 0, error = CHIP_ERROR_INVALID_ARGUMENT);
// TODO: Remove suport for AES-256 since not in 1.0
// Determine crypto type by key length
type = (key_length == kAES_CCM128_Key_Length) ? EVP_aes_128_ccm() : EVP_aes_256_ccm();
context = EVP_CIPHER_CTX_new();
VerifyOrExit(context != nullptr, error = CHIP_ERROR_INTERNAL);
// Pass in cipher
result = EVP_DecryptInit_ex(context, type, nullptr, nullptr, nullptr);
VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL);
// Pass in IV length
VerifyOrExit(CanCastTo<int>(iv_length), error = CHIP_ERROR_INVALID_ARGUMENT);
result = EVP_CIPHER_CTX_ctrl(context, EVP_CTRL_CCM_SET_IVLEN, static_cast<int>(iv_length), nullptr);
VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL);
// Pass in expected tag
// Removing "const" from |tag| here should hopefully be safe as
// we're writing the tag, not reading.
VerifyOrExit(CanCastTo<int>(tag_length), error = CHIP_ERROR_INVALID_ARGUMENT);
result = EVP_CIPHER_CTX_ctrl(context, EVP_CTRL_CCM_SET_TAG, static_cast<int>(tag_length),
const_cast<void *>(static_cast<const void *>(tag)));
VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL);
// Pass in key + iv
result = EVP_DecryptInit_ex(context, nullptr, nullptr, Uint8::to_const_uchar(key), Uint8::to_const_uchar(iv));
VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL);
// Pass in cipher text length
VerifyOrExit(CanCastTo<int>(ciphertext_length), error = CHIP_ERROR_INVALID_ARGUMENT);
result = EVP_DecryptUpdate(context, nullptr, &bytesOutput, nullptr, static_cast<int>(ciphertext_length));
VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL);
VerifyOrExit(bytesOutput <= static_cast<int>(ciphertext_length), error = CHIP_ERROR_INTERNAL);
// Pass in aad
if (aad_length > 0 && aad != nullptr)
{
VerifyOrExit(CanCastTo<int>(aad_length), error = CHIP_ERROR_INVALID_ARGUMENT);
result = EVP_DecryptUpdate(context, nullptr, &bytesOutput, Uint8::to_const_uchar(aad), static_cast<int>(aad_length));
VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL);
VerifyOrExit(bytesOutput <= static_cast<int>(aad_length), error = CHIP_ERROR_INTERNAL);
}
// Pass in ciphertext. We wont get anything if validation fails.
VerifyOrExit(CanCastTo<int>(ciphertext_length), error = CHIP_ERROR_INVALID_ARGUMENT);
result = EVP_DecryptUpdate(context, Uint8::to_uchar(plaintext), &bytesOutput, Uint8::to_const_uchar(ciphertext),
static_cast<int>(ciphertext_length));
if (plaintext_was_null)
{
VerifyOrExit(bytesOutput <= static_cast<int>(sizeof(placeholder_plaintext)), error = CHIP_ERROR_INTERNAL);
}
VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL);
exit:
if (context != nullptr)
{
EVP_CIPHER_CTX_free(context);
context = nullptr;
}
return error;
}
CHIP_ERROR Hash_SHA256(const uint8_t * data, const size_t data_length, uint8_t * out_buffer)
{
// zero data length hash is supported.
VerifyOrReturnError(data != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrReturnError(out_buffer != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
SHA256(data, data_length, Uint8::to_uchar(out_buffer));
return CHIP_NO_ERROR;
}
CHIP_ERROR Hash_SHA1(const uint8_t * data, const size_t data_length, uint8_t * out_buffer)
{
// zero data length hash is supported.
VerifyOrReturnError(data != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrReturnError(out_buffer != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
SHA1(data, data_length, Uint8::to_uchar(out_buffer));
return CHIP_NO_ERROR;
}
Hash_SHA256_stream::Hash_SHA256_stream() {}
Hash_SHA256_stream::~Hash_SHA256_stream()
{
Clear();
}
static_assert(kMAX_Hash_SHA256_Context_Size >= sizeof(SHA256_CTX),
"kMAX_Hash_SHA256_Context_Size is too small for the size of underlying SHA256_CTX");
static inline SHA256_CTX * to_inner_hash_sha256_context(HashSHA256OpaqueContext * context)
{
return SafePointerCast<SHA256_CTX *>(context);
}
CHIP_ERROR Hash_SHA256_stream::Begin()
{
SHA256_CTX * const context = to_inner_hash_sha256_context(&mContext);
const int result = SHA256_Init(context);
VerifyOrReturnError(result == 1, CHIP_ERROR_INTERNAL);
return CHIP_NO_ERROR;
}
CHIP_ERROR Hash_SHA256_stream::AddData(const ByteSpan data)
{
SHA256_CTX * const context = to_inner_hash_sha256_context(&mContext);
const int result = SHA256_Update(context, Uint8::to_const_uchar(data.data()), data.size());
VerifyOrReturnError(result == 1, CHIP_ERROR_INTERNAL);
return CHIP_NO_ERROR;
}
CHIP_ERROR Hash_SHA256_stream::GetDigest(MutableByteSpan & out_buffer)
{
SHA256_CTX * context = to_inner_hash_sha256_context(&mContext);
// Back-up context as we are about to finalize the hash to extract digest.
SHA256_CTX previous_ctx = *context;
// Pad + compute digest, then finalize context. It is restored next line to continue.
CHIP_ERROR result = Finish(out_buffer);
// Restore context prior to finalization.
*context = previous_ctx;
return result;
}
CHIP_ERROR Hash_SHA256_stream::Finish(MutableByteSpan & out_buffer)
{
VerifyOrReturnError(out_buffer.size() >= kSHA256_Hash_Length, CHIP_ERROR_BUFFER_TOO_SMALL);
SHA256_CTX * const context = to_inner_hash_sha256_context(&mContext);
const int result = SHA256_Final(Uint8::to_uchar(out_buffer.data()), context);
VerifyOrReturnError(result == 1, CHIP_ERROR_INTERNAL);
out_buffer = out_buffer.SubSpan(0, kSHA256_Hash_Length);
return CHIP_NO_ERROR;
}
void Hash_SHA256_stream::Clear()
{
OPENSSL_cleanse(this, sizeof(*this));
}
CHIP_ERROR HKDF_sha::HKDF_SHA256(const uint8_t * secret, const size_t secret_length, const uint8_t * salt, const size_t salt_length,
const uint8_t * info, const size_t info_length, uint8_t * out_buffer, size_t out_length)
{
CHIP_ERROR error = CHIP_NO_ERROR;
int result = 1;
EVP_PKEY_CTX * const context = EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, nullptr);
VerifyOrExit(context != nullptr, error = CHIP_ERROR_INTERNAL);
VerifyOrExit(secret != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(secret_length > 0, error = CHIP_ERROR_INVALID_ARGUMENT);
// Salt is optional
if (salt_length > 0)
{
VerifyOrExit(salt != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT);
}
VerifyOrExit(info_length > 0, error = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(info != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(out_length > 0, error = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(out_buffer != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT);
result = EVP_PKEY_derive_init(context);
VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL);
result = EVP_PKEY_CTX_set_hkdf_md(context, EVP_sha256());
VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL);
VerifyOrExit(CanCastTo<int>(secret_length), error = CHIP_ERROR_INVALID_ARGUMENT);
result = EVP_PKEY_CTX_set1_hkdf_key(context, Uint8::to_const_uchar(secret), static_cast<int>(secret_length));
VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL);
if (salt_length > 0 && salt != nullptr)
{
VerifyOrExit(CanCastTo<int>(salt_length), error = CHIP_ERROR_INVALID_ARGUMENT);
result = EVP_PKEY_CTX_set1_hkdf_salt(context, Uint8::to_const_uchar(salt), static_cast<int>(salt_length));
VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL);
}
VerifyOrExit(CanCastTo<int>(info_length), error = CHIP_ERROR_INVALID_ARGUMENT);
result = EVP_PKEY_CTX_add1_hkdf_info(context, Uint8::to_const_uchar(info), static_cast<int>(info_length));
VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL);
result = EVP_PKEY_CTX_hkdf_mode(context, EVP_PKEY_HKDEF_MODE_EXTRACT_AND_EXPAND);
VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL);
// Get the OKM (Output Key Material)
result = EVP_PKEY_derive(context, Uint8::to_uchar(out_buffer), &out_length);
VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL);
exit:
if (context != nullptr)
{
EVP_PKEY_CTX_free(context);
}
return error;
}
CHIP_ERROR HMAC_sha::HMAC_SHA256(const uint8_t * key, size_t key_length, const uint8_t * message, size_t message_length,
uint8_t * out_buffer, size_t out_length)
{
VerifyOrReturnError(key != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrReturnError(key_length > 0, CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrReturnError(message != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrReturnError(message_length > 0, CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrReturnError(out_length >= kSHA256_Hash_Length, CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrReturnError(out_buffer != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
CHIP_ERROR error = CHIP_ERROR_INTERNAL;
int error_openssl = 0;
unsigned int mac_out_len = 0;
HMAC_CTX * mac_ctx = HMAC_CTX_new();
VerifyOrExit(mac_ctx != nullptr, error = CHIP_ERROR_INTERNAL);
error_openssl = HMAC_Init_ex(mac_ctx, Uint8::to_const_uchar(key), static_cast<int>(key_length), EVP_sha256(), nullptr);
VerifyOrExit(error_openssl == 1, error = CHIP_ERROR_INTERNAL);
error_openssl = HMAC_Update(mac_ctx, Uint8::to_const_uchar(message), message_length);
VerifyOrExit(error_openssl == 1, error = CHIP_ERROR_INTERNAL);
mac_out_len = static_cast<unsigned int>(CHIP_CRYPTO_HASH_LEN_BYTES);
error_openssl = HMAC_Final(mac_ctx, Uint8::to_uchar(out_buffer), &mac_out_len);
VerifyOrExit(error_openssl == 1, error = CHIP_ERROR_INTERNAL);
error = CHIP_NO_ERROR;
exit:
HMAC_CTX_free(mac_ctx);
return error;
}
CHIP_ERROR PBKDF2_sha256::pbkdf2_sha256(const uint8_t * password, size_t plen, const uint8_t * salt, size_t slen,
unsigned int iteration_count, uint32_t key_length, uint8_t * output)
{
CHIP_ERROR error = CHIP_NO_ERROR;
int result = 1;
const EVP_MD * md = nullptr;
VerifyOrExit(password != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(plen > 0, error = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(salt != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(slen >= kMin_Salt_Length, error = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(slen <= kMax_Salt_Length, error = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(key_length > 0, error = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(output != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT);
md = _digestForType(DigestType::SHA256);
VerifyOrExit(md != nullptr, error = CHIP_ERROR_INTERNAL);
VerifyOrExit(CanCastTo<int>(plen), error = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(CanCastTo<int>(slen), error = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(CanCastTo<int>(iteration_count), error = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(CanCastTo<int>(key_length), error = CHIP_ERROR_INVALID_ARGUMENT);
result = PKCS5_PBKDF2_HMAC(Uint8::to_const_char(password), static_cast<int>(plen), Uint8::to_const_uchar(salt),
static_cast<int>(slen), static_cast<int>(iteration_count), md, static_cast<int>(key_length),
Uint8::to_uchar(output));
VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL);
exit:
if (error != CHIP_NO_ERROR)
{
_logSSLError();
}
return error;
}
CHIP_ERROR add_entropy_source(entropy_source fn_source, void * p_source, size_t threshold)
{
return CHIP_NO_ERROR;
}
CHIP_ERROR DRBG_get_bytes(uint8_t * out_buffer, const size_t out_length)
{
VerifyOrReturnError(out_buffer != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrReturnError(out_length > 0, CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrReturnError(CanCastTo<int>(out_length), CHIP_ERROR_INVALID_ARGUMENT);
const int result = RAND_priv_bytes(Uint8::to_uchar(out_buffer), static_cast<int>(out_length));
VerifyOrReturnError(result == 1, CHIP_ERROR_INTERNAL);
return CHIP_NO_ERROR;
}
ECName MapECName(SupportedECPKeyTypes keyType)
{
switch (keyType)
{
case SupportedECPKeyTypes::ECP256R1:
return ECName::P256v1;
default:
return ECName::None;
}
}
static inline void from_EC_KEY(EC_KEY * key, P256KeypairContext * context)
{
*SafePointerCast<EC_KEY **>(context) = key;
}
static inline EC_KEY * to_EC_KEY(P256KeypairContext * context)
{
return *SafePointerCast<EC_KEY **>(context);
}
static inline const EC_KEY * to_const_EC_KEY(const P256KeypairContext * context)
{
return *SafePointerCast<const EC_KEY * const *>(context);
}
CHIP_ERROR P256Keypair::ECDSA_sign_msg(const uint8_t * msg, const size_t msg_length, P256ECDSASignature & out_signature)
{
VerifyOrReturnError((msg != nullptr) && (msg_length > 0), CHIP_ERROR_INVALID_ARGUMENT);
uint8_t digest[kSHA256_Hash_Length];
memset(&digest[0], 0, sizeof(digest));
ReturnErrorOnFailure(Hash_SHA256(msg, msg_length, &digest[0]));
return ECDSA_sign_hash(&digest[0], sizeof(digest), out_signature);
}
CHIP_ERROR P256Keypair::ECDSA_sign_hash(const uint8_t * hash, const size_t hash_length, P256ECDSASignature & out_signature)
{
ERR_clear_error();
CHIP_ERROR error = CHIP_NO_ERROR;
int nid = NID_undef;
EC_KEY * ec_key = nullptr;
ECDSA_SIG * sig = nullptr;
const BIGNUM * r = nullptr;
const BIGNUM * s = nullptr;
static_assert(P256ECDSASignature::Capacity() >= kP256_ECDSA_Signature_Length_Raw, "P256ECDSASignature must be large enough");
VerifyOrExit(mInitialized, error = CHIP_ERROR_INCORRECT_STATE);
VerifyOrExit(hash != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(hash_length == kSHA256_Hash_Length, error = CHIP_ERROR_INVALID_ARGUMENT);
nid = _nidForCurve(MapECName(mPublicKey.Type()));
VerifyOrExit(nid != NID_undef, error = CHIP_ERROR_INVALID_ARGUMENT);
ec_key = to_EC_KEY(&mKeypair);
VerifyOrExit(ec_key != nullptr, error = CHIP_ERROR_INTERNAL);
sig = ECDSA_do_sign(Uint8::to_const_uchar(hash), static_cast<int>(hash_length), ec_key);
VerifyOrExit(sig != nullptr, error = CHIP_ERROR_INTERNAL);
ECDSA_SIG_get0(sig, &r, &s);
VerifyOrExit((r != nullptr) || (s != nullptr) || (BN_num_bytes(r) == kP256_FE_Length) || (BN_num_bytes(s) == kP256_FE_Length),
error = CHIP_ERROR_INTERNAL);
// Concatenate r and s to output. Sizes were checked above.
VerifyOrExit(out_signature.SetLength(kP256_ECDSA_Signature_Length_Raw) == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL);
BN_bn2binpad(r, out_signature.Bytes() + 0u, kP256_FE_Length);
BN_bn2binpad(s, out_signature.Bytes() + kP256_FE_Length, kP256_FE_Length);
exit:
if (sig != nullptr)
{
// SIG owns the memory of r, s
ECDSA_SIG_free(sig);
}
if (error != CHIP_NO_ERROR)
{
_logSSLError();
}
return error;
}
CHIP_ERROR P256PublicKey::ECDSA_validate_msg_signature(const uint8_t * msg, const size_t msg_length,
const P256ECDSASignature & signature) const
{
VerifyOrReturnError((msg != nullptr) && (msg_length > 0), CHIP_ERROR_INVALID_ARGUMENT);
uint8_t digest[kSHA256_Hash_Length];
memset(&digest[0], 0, sizeof(digest));
ReturnErrorOnFailure(Hash_SHA256(msg, msg_length, &digest[0]));
return ECDSA_validate_hash_signature(&digest[0], sizeof(digest), signature);
}
CHIP_ERROR P256PublicKey::ECDSA_validate_hash_signature(const uint8_t * hash, const size_t hash_length,
const P256ECDSASignature & signature) const
{
ERR_clear_error();
CHIP_ERROR error = CHIP_ERROR_INTERNAL;
int nid = NID_undef;
EC_KEY * ec_key = nullptr;
EC_POINT * key_point = nullptr;
EC_GROUP * ec_group = nullptr;
ECDSA_SIG * ec_sig = nullptr;
BIGNUM * r = nullptr;
BIGNUM * s = nullptr;
int result = 0;
VerifyOrExit(hash != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(hash_length == kSHA256_Hash_Length, error = CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrExit(signature.Length() == kP256_ECDSA_Signature_Length_Raw, error = CHIP_ERROR_INVALID_ARGUMENT);
nid = _nidForCurve(MapECName(Type()));
VerifyOrExit(nid != NID_undef, error = CHIP_ERROR_INVALID_ARGUMENT);
ec_group = EC_GROUP_new_by_curve_name(nid);
VerifyOrExit(ec_group != nullptr, error = CHIP_ERROR_NO_MEMORY);
key_point = EC_POINT_new(ec_group);
VerifyOrExit(key_point != nullptr, error = CHIP_ERROR_NO_MEMORY);
result = EC_POINT_oct2point(ec_group, key_point, Uint8::to_const_uchar(*this), Length(), nullptr);
VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL);
ec_key = EC_KEY_new_by_curve_name(nid);
VerifyOrExit(ec_key != nullptr, error = CHIP_ERROR_NO_MEMORY);
result = EC_KEY_set_public_key(ec_key, key_point);
VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL);
result = EC_KEY_check_key(ec_key);
VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL);
// Build-up the signature object from raw <r,s> tuple
r = BN_bin2bn(Uint8::to_const_uchar(signature.ConstBytes()) + 0u, kP256_FE_Length, nullptr);
VerifyOrExit(r != nullptr, error = CHIP_ERROR_NO_MEMORY);
s = BN_bin2bn(Uint8::to_const_uchar(signature.ConstBytes()) + kP256_FE_Length, kP256_FE_Length, nullptr);
VerifyOrExit(s != nullptr, error = CHIP_ERROR_NO_MEMORY);
ec_sig = ECDSA_SIG_new();
VerifyOrExit(ec_sig != nullptr, error = CHIP_ERROR_NO_MEMORY);
result = ECDSA_SIG_set0(ec_sig, r, s);
VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL);
result = ECDSA_do_verify(Uint8::to_const_uchar(hash), static_cast<int>(hash_length), ec_sig, ec_key);
VerifyOrExit(result == 1, error = CHIP_ERROR_INVALID_SIGNATURE);
error = CHIP_NO_ERROR;
exit:
_logSSLError();
if (ec_sig != nullptr)
{
ECDSA_SIG_free(ec_sig);
// After ECDSA_SIG_set0 succeeds, r and s memory is managed by ECDSA_SIG object.
// We set to nullptr so that we don't try to double-free
r = nullptr;
s = nullptr;
}
if (s != nullptr)
{
BN_clear_free(s);
}
if (r != nullptr)
{
BN_clear_free(r);
}
if (ec_key != nullptr)
{
EC_KEY_free(ec_key);
}
if (key_point != nullptr)
{
EC_POINT_clear_free(key_point);
}
if (ec_group != nullptr)
{
EC_GROUP_free(ec_group);
}
return error;
}
// helper function to populate octet key into EVP_PKEY out_evp_pkey. Caller must free out_evp_pkey
static CHIP_ERROR _create_evp_key_from_binary_p256_key(const P256PublicKey & key, EVP_PKEY ** out_evp_pkey)
{
CHIP_ERROR error = CHIP_NO_ERROR;
EC_KEY * ec_key = nullptr;
int result = -1;
EC_POINT * point = nullptr;
EC_GROUP * group = nullptr;
int nid = NID_undef;
VerifyOrExit(*out_evp_pkey == nullptr, error = CHIP_ERROR_INVALID_ARGUMENT);
nid = _nidForCurve(MapECName(key.Type()));
VerifyOrExit(nid != NID_undef, error = CHIP_ERROR_INTERNAL);
ec_key = EC_KEY_new_by_curve_name(nid);
VerifyOrExit(ec_key != nullptr, error = CHIP_ERROR_INTERNAL);
group = EC_GROUP_new_by_curve_name(nid);
VerifyOrExit(group != nullptr, error = CHIP_ERROR_INTERNAL);
point = EC_POINT_new(group);
VerifyOrExit(point != nullptr, error = CHIP_ERROR_INTERNAL);
result = EC_POINT_oct2point(group, point, Uint8::to_const_uchar(key), key.Length(), nullptr);
VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL);
result = EC_KEY_set_public_key(ec_key, point);
VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL);
*out_evp_pkey = EVP_PKEY_new();
VerifyOrExit(*out_evp_pkey != nullptr, error = CHIP_ERROR_INTERNAL);
result = EVP_PKEY_set1_EC_KEY(*out_evp_pkey, ec_key);
VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL);
exit:
if (ec_key != nullptr)
{
EC_KEY_free(ec_key);
ec_key = nullptr;
}
if (error != CHIP_NO_ERROR && *out_evp_pkey)
{
EVP_PKEY_free(*out_evp_pkey);
out_evp_pkey = nullptr;
}
if (point != nullptr)
{
EC_POINT_free(point);
point = nullptr;
}
if (group != nullptr)
{
EC_GROUP_free(group);
group = nullptr;
}
return error;
}
CHIP_ERROR P256Keypair::ECDH_derive_secret(const P256PublicKey & remote_public_key, P256ECDHDerivedSecret & out_secret) const
{
ERR_clear_error();
CHIP_ERROR error = CHIP_NO_ERROR;
int result = -1;
EVP_PKEY * local_key = nullptr;
EVP_PKEY * remote_key = nullptr;
EVP_PKEY_CTX * context = nullptr;
size_t out_buf_length = 0;
EC_KEY * ec_key = EC_KEY_dup(to_const_EC_KEY(&mKeypair));
VerifyOrExit(ec_key != nullptr, error = CHIP_ERROR_INTERNAL);
VerifyOrExit(mInitialized, error = CHIP_ERROR_INCORRECT_STATE);
local_key = EVP_PKEY_new();
VerifyOrExit(local_key != nullptr, error = CHIP_ERROR_INTERNAL);
result = EVP_PKEY_set1_EC_KEY(local_key, ec_key);
VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL);
error = _create_evp_key_from_binary_p256_key(remote_public_key, &remote_key);
SuccessOrExit(error);
context = EVP_PKEY_CTX_new(local_key, nullptr);
VerifyOrExit(context != nullptr, error = CHIP_ERROR_INTERNAL);
result = EVP_PKEY_derive_init(context);
VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL);
result = EVP_PKEY_derive_set_peer(context, remote_key);
VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL);
out_buf_length = (out_secret.Length() == 0) ? out_secret.Capacity() : out_secret.Length();
result = EVP_PKEY_derive(context, Uint8::to_uchar(out_secret), &out_buf_length);
VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL);
SuccessOrExit(out_secret.SetLength(out_buf_length));
exit:
if (ec_key != nullptr)
{
EC_KEY_free(ec_key);
ec_key = nullptr;
}
if (local_key != nullptr)
{
EVP_PKEY_free(local_key);
local_key = nullptr;
}
if (remote_key != nullptr)
{
EVP_PKEY_free(remote_key);
remote_key = nullptr;
}
if (context != nullptr)
{
EVP_PKEY_CTX_free(context);
context = nullptr;
}
_logSSLError();
return error;
}
void ClearSecretData(uint8_t * buf, size_t len)
{
OPENSSL_cleanse(buf, len);
}
static CHIP_ERROR P256PublicKeyFromECKey(EC_KEY * ec_key, P256PublicKey & pubkey)
{
ERR_clear_error();
CHIP_ERROR error = CHIP_NO_ERROR;
int nid = NID_undef;
ECName curve = MapECName(pubkey.Type());
EC_GROUP * group = nullptr;
size_t pubkey_size = 0;
const EC_POINT * pubkey_ecp = EC_KEY_get0_public_key(ec_key);
VerifyOrExit(pubkey_ecp != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT);
nid = _nidForCurve(curve);
VerifyOrExit(nid != NID_undef, error = CHIP_ERROR_INVALID_ARGUMENT);
group = EC_GROUP_new_by_curve_name(nid);
VerifyOrExit(group != nullptr, error = CHIP_ERROR_INTERNAL);
pubkey_size =
EC_POINT_point2oct(group, pubkey_ecp, POINT_CONVERSION_UNCOMPRESSED, Uint8::to_uchar(pubkey), pubkey.Length(), nullptr);
pubkey_ecp = nullptr;
VerifyOrExit(pubkey_size == pubkey.Length(), error = CHIP_ERROR_INVALID_ARGUMENT);
exit:
if (group != nullptr)
{
EC_GROUP_free(group);
group = nullptr;
}
_logSSLError();
return error;
}
CHIP_ERROR P256Keypair::Initialize()
{
ERR_clear_error();
Clear();
CHIP_ERROR error = CHIP_NO_ERROR;
int result = 0;
EC_KEY * ec_key = nullptr;
ECName curve = MapECName(mPublicKey.Type());
int nid = _nidForCurve(curve);
VerifyOrExit(nid != NID_undef, error = CHIP_ERROR_INVALID_ARGUMENT);
ec_key = EC_KEY_new_by_curve_name(nid);
VerifyOrExit(ec_key != nullptr, error = CHIP_ERROR_INTERNAL);
result = EC_KEY_generate_key(ec_key);
VerifyOrExit(result == 1, error = CHIP_ERROR_INTERNAL);
error = P256PublicKeyFromECKey(ec_key, mPublicKey);
SuccessOrExit(error);
from_EC_KEY(ec_key, &mKeypair);
mInitialized = true;
ec_key = nullptr;
exit:
if (ec_key != nullptr)
{
EC_KEY_free(ec_key);
ec_key = nullptr;
}
_logSSLError();
return error;
}
CHIP_ERROR P256Keypair::Serialize(P256SerializedKeypair & output) const
{
CHIP_ERROR error = CHIP_NO_ERROR;
const EC_KEY * ec_key = to_const_EC_KEY(&mKeypair);
uint8_t privkey[kP256_PrivateKey_Length];
int privkey_size = 0;
const BIGNUM * privkey_bn = EC_KEY_get0_private_key(ec_key);
VerifyOrExit(privkey_bn != nullptr, error = CHIP_ERROR_INTERNAL);
privkey_size = BN_bn2binpad(privkey_bn, privkey, sizeof(privkey));
privkey_bn = nullptr;
VerifyOrExit(privkey_size > 0, error = CHIP_ERROR_INTERNAL);
VerifyOrExit((size_t) privkey_size == sizeof(privkey), error = CHIP_ERROR_INTERNAL);
{
size_t len = output.Length() == 0 ? output.Capacity() : output.Length();
Encoding::BufferWriter bbuf(output, len);