-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
CHIPCryptoPAL.h
1573 lines (1384 loc) · 62.8 KB
/
CHIPCryptoPAL.h
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-2022 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:https://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
* Header that exposes the platform agnostic CHIP crypto primitives
*/
#pragma once
#if CHIP_HAVE_CONFIG_H
#include <crypto/CryptoBuildConfig.h>
#endif
#include <system/SystemConfig.h>
#include <lib/core/CHIPError.h>
#include <lib/core/CHIPVendorIdentifiers.hpp>
#include <lib/core/Optional.h>
#include <lib/support/CodeUtils.h>
#include <lib/support/Span.h>
#include <stddef.h>
#include <string.h>
namespace chip {
namespace Crypto {
constexpr size_t kMax_x509_Certificate_Length = 600;
constexpr size_t kP256_FE_Length = 32;
constexpr size_t kP256_ECDSA_Signature_Length_Raw = (2 * kP256_FE_Length);
constexpr size_t kP256_Point_Length = (2 * kP256_FE_Length + 1);
constexpr size_t kSHA256_Hash_Length = 32;
constexpr size_t kSHA1_Hash_Length = 20;
constexpr size_t kSubjectKeyIdentifierLength = kSHA1_Hash_Length;
constexpr size_t kAuthorityKeyIdentifierLength = kSHA1_Hash_Length;
constexpr size_t CHIP_CRYPTO_GROUP_SIZE_BYTES = kP256_FE_Length;
constexpr size_t CHIP_CRYPTO_PUBLIC_KEY_SIZE_BYTES = kP256_Point_Length;
constexpr size_t CHIP_CRYPTO_AEAD_MIC_LENGTH_BYTES = 16;
constexpr size_t CHIP_CRYPTO_SYMMETRIC_KEY_LENGTH_BYTES = 16;
constexpr size_t kMax_ECDH_Secret_Length = kP256_FE_Length;
constexpr size_t kMax_ECDSA_Signature_Length = kP256_ECDSA_Signature_Length_Raw;
constexpr size_t kMAX_FE_Length = kP256_FE_Length;
constexpr size_t kMAX_Point_Length = kP256_Point_Length;
constexpr size_t kMAX_Hash_Length = kSHA256_Hash_Length;
// Max CSR length should be relatively small since it's a single P256 key and
// no metadata is expected to be honored by the CA.
constexpr size_t kMAX_CSR_Length = 255;
constexpr size_t CHIP_CRYPTO_HASH_LEN_BYTES = kSHA256_Hash_Length;
constexpr size_t kSpake2p_Min_PBKDF_Salt_Length = 16;
constexpr size_t kSpake2p_Max_PBKDF_Salt_Length = 32;
constexpr uint32_t kSpake2p_Min_PBKDF_Iterations = 1000;
constexpr uint32_t kSpake2p_Max_PBKDF_Iterations = 100000;
constexpr size_t kP256_PrivateKey_Length = CHIP_CRYPTO_GROUP_SIZE_BYTES;
constexpr size_t kP256_PublicKey_Length = CHIP_CRYPTO_PUBLIC_KEY_SIZE_BYTES;
constexpr size_t kAES_CCM128_Key_Length = 128u / 8u;
constexpr size_t kAES_CCM128_Block_Length = kAES_CCM128_Key_Length;
// TODO: Remove AES-256 from CryptoPAL since not required by V1 spec
constexpr size_t kAES_CCM256_Key_Length = 256u / 8u;
constexpr size_t kAES_CCM256_Block_Length = kAES_CCM256_Key_Length;
/* These sizes are hardcoded here to remove header dependency on underlying crypto library
* in a public interface file. The validity of these sizes is verified by static_assert in
* the implementation files.
*/
constexpr size_t kMAX_Spake2p_Context_Size = 1024;
constexpr size_t kMAX_P256Keypair_Context_Size = 512;
constexpr size_t kEmitDerIntegerWithoutTagOverhead = 1; // 1 sign stuffer
constexpr size_t kEmitDerIntegerOverhead = 3; // Tag + Length byte + 1 sign stuffer
constexpr size_t kMAX_Hash_SHA256_Context_Size = CHIP_CONFIG_SHA256_CONTEXT_SIZE;
constexpr size_t kSpake2p_WS_Length = kP256_FE_Length + 8;
constexpr size_t kSpake2p_VerifierSerialized_Length = kP256_FE_Length + kP256_Point_Length;
constexpr char kVIDPrefixForCNEncoding[] = "Mvid:";
constexpr char kPIDPrefixForCNEncoding[] = "Mpid:";
constexpr size_t kVIDandPIDHexLength = sizeof(uint16_t) * 2;
constexpr size_t kMax_CommonNameAttr_Length = 64;
/*
* Overhead to encode a raw ECDSA signature in X9.62 format in ASN.1 DER
*
* Ecdsa-Sig-Value ::= SEQUENCE {
* r INTEGER,
* s INTEGER
* }
*
* --> SEQUENCE, universal constructed tag (0x30), length over 2 bytes, up to 255 (to support future larger sizes up to 512 bits)
* -> SEQ_OVERHEAD = 3 bytes
* --> INTEGER, universal primitive tag (0x02), length over 1 byte, one extra byte worst case
* over max for 0x00 when MSB is set.
* -> INT_OVERHEAD = 3 bytes
*
* There is 1 sequence of 2 integers. Overhead is SEQ_OVERHEAD + (2 * INT_OVERHEAD) = 3 + (2 * 3) = 9.
*/
constexpr size_t kMax_ECDSA_X9Dot62_Asn1_Overhead = 9;
constexpr size_t kMax_ECDSA_Signature_Length_Der = kMax_ECDSA_Signature_Length + kMax_ECDSA_X9Dot62_Asn1_Overhead;
static_assert(kMax_ECDH_Secret_Length >= kP256_FE_Length, "ECDH shared secret is too short for crypto suite");
static_assert(kMax_ECDSA_Signature_Length >= kP256_ECDSA_Signature_Length_Raw,
"ECDSA signature buffer length is too short for crypto suite");
constexpr size_t kCompressedFabricIdentifierSize = 8;
/**
* Spake2+ parameters for P256
* Defined in https://www.ietf.org/id/draft-bar-cfrg-spake2plus-01.html#name-ciphersuites
*/
const uint8_t spake2p_M_p256[65] = {
0x04, 0x88, 0x6e, 0x2f, 0x97, 0xac, 0xe4, 0x6e, 0x55, 0xba, 0x9d, 0xd7, 0x24, 0x25, 0x79, 0xf2, 0x99,
0x3b, 0x64, 0xe1, 0x6e, 0xf3, 0xdc, 0xab, 0x95, 0xaf, 0xd4, 0x97, 0x33, 0x3d, 0x8f, 0xa1, 0x2f, 0x5f,
0xf3, 0x55, 0x16, 0x3e, 0x43, 0xce, 0x22, 0x4e, 0x0b, 0x0e, 0x65, 0xff, 0x02, 0xac, 0x8e, 0x5c, 0x7b,
0xe0, 0x94, 0x19, 0xc7, 0x85, 0xe0, 0xca, 0x54, 0x7d, 0x55, 0xa1, 0x2e, 0x2d, 0x20,
};
const uint8_t spake2p_N_p256[65] = {
0x04, 0xd8, 0xbb, 0xd6, 0xc6, 0x39, 0xc6, 0x29, 0x37, 0xb0, 0x4d, 0x99, 0x7f, 0x38, 0xc3, 0x77, 0x07,
0x19, 0xc6, 0x29, 0xd7, 0x01, 0x4d, 0x49, 0xa2, 0x4b, 0x4f, 0x98, 0xba, 0xa1, 0x29, 0x2b, 0x49, 0x07,
0xd6, 0x0a, 0xa6, 0xbf, 0xad, 0xe4, 0x50, 0x08, 0xa6, 0x36, 0x33, 0x7f, 0x51, 0x68, 0xc6, 0x4d, 0x9b,
0xd3, 0x60, 0x34, 0x80, 0x8c, 0xd5, 0x64, 0x49, 0x0b, 0x1e, 0x65, 0x6e, 0xdb, 0xe7,
};
/**
* Spake2+ state machine to ensure proper execution of the protocol.
*/
enum class CHIP_SPAKE2P_STATE : uint8_t
{
PREINIT = 0, // Before any initialization
INIT, // First initialization
STARTED, // Prover & Verifier starts
R1, // Round one complete
R2, // Round two complete
KC, // Key confirmation complete
};
/**
* Spake2+ role.
*/
enum class CHIP_SPAKE2P_ROLE : uint8_t
{
VERIFIER = 0, // Accessory
PROVER = 1, // Commissioner
};
enum class SupportedECPKeyTypes : uint8_t
{
ECP256R1 = 0,
};
/** @brief Safely clears the first `len` bytes of memory area `buf`.
* @param buf Pointer to a memory buffer holding secret data that must be cleared.
* @param len Specifies secret data size in bytes.
**/
void ClearSecretData(uint8_t * buf, size_t len);
/**
* Helper for clearing a C array which auto-deduces the size.
*/
template <size_t N>
void ClearSecretData(uint8_t (&buf)[N])
{
ClearSecretData(buf, N);
}
template <typename Sig>
class ECPKey
{
public:
virtual ~ECPKey() {}
virtual SupportedECPKeyTypes Type() const = 0;
virtual size_t Length() const = 0;
virtual bool IsUncompressed() const = 0;
virtual operator const uint8_t *() const = 0;
virtual operator uint8_t *() = 0;
virtual const uint8_t * ConstBytes() const = 0;
virtual uint8_t * Bytes() = 0;
virtual CHIP_ERROR ECDSA_validate_msg_signature(const uint8_t * msg, const size_t msg_length, const Sig & signature) const = 0;
virtual CHIP_ERROR ECDSA_validate_hash_signature(const uint8_t * hash, const size_t hash_length,
const Sig & signature) const = 0;
};
template <size_t Cap>
class CapacityBoundBuffer
{
public:
~CapacityBoundBuffer()
{
// Sanitize after use
ClearSecretData(&bytes[0], Cap);
}
CapacityBoundBuffer & operator=(const CapacityBoundBuffer & other)
{
// Guard self assignment
if (this == &other)
return *this;
ClearSecretData(&bytes[0], Cap);
SetLength(other.Length());
::memcpy(Bytes(), other.Bytes(), other.Length());
return *this;
}
/** @brief Set current length of the buffer that's being used
* @return Returns error if new length is > capacity
**/
CHIP_ERROR SetLength(size_t len)
{
VerifyOrReturnError(len <= sizeof(bytes), CHIP_ERROR_INVALID_ARGUMENT);
length = len;
return CHIP_NO_ERROR;
}
/** @brief Returns current length of the buffer that's being used
* @return Returns 0 if SetLength() was never called
**/
size_t Length() const { return length; }
/** @brief Returns max capacity of the buffer
**/
static constexpr size_t Capacity() { return sizeof(bytes); }
/** @brief Returns pointer to start of underlying buffer
**/
uint8_t * Bytes() { return &bytes[0]; }
/** @brief Returns const pointer to start of underlying buffer
**/
const uint8_t * ConstBytes() const { return &bytes[0]; }
/** @brief Returns buffer pointer
**/
operator uint8_t *() { return bytes; }
operator const uint8_t *() const { return bytes; }
private:
uint8_t bytes[Cap];
size_t length = 0;
};
typedef CapacityBoundBuffer<kMax_ECDSA_Signature_Length> P256ECDSASignature;
typedef CapacityBoundBuffer<kMax_ECDH_Secret_Length> P256ECDHDerivedSecret;
class P256PublicKey : public ECPKey<P256ECDSASignature>
{
public:
P256PublicKey() {}
template <size_t N>
constexpr P256PublicKey(const uint8_t (&raw_value)[N])
{
static_assert(N == kP256_PublicKey_Length, "Can only array-initialize from proper bounds");
memcpy(&bytes[0], &raw_value[0], N);
}
template <size_t N>
constexpr P256PublicKey(const FixedByteSpan<N> & value)
{
static_assert(N == kP256_PublicKey_Length, "Can only initialize from proper sized byte span");
memcpy(&bytes[0], value.data(), N);
}
SupportedECPKeyTypes Type() const override { return SupportedECPKeyTypes::ECP256R1; }
size_t Length() const override { return kP256_PublicKey_Length; }
operator uint8_t *() override { return bytes; }
operator const uint8_t *() const override { return bytes; }
const uint8_t * ConstBytes() const override { return &bytes[0]; }
uint8_t * Bytes() override { return &bytes[0]; }
bool IsUncompressed() const override
{
constexpr uint8_t kUncompressedPointMarker = 0x04;
// SEC1 definition of an uncompressed point is (0x04 || X || Y) where X and Y are
// raw zero-padded big-endian large integers of the group size.
return (Length() == ((kP256_FE_Length * 2) + 1)) && (ConstBytes()[0] == kUncompressedPointMarker);
}
CHIP_ERROR ECDSA_validate_msg_signature(const uint8_t * msg, size_t msg_length,
const P256ECDSASignature & signature) const override;
CHIP_ERROR ECDSA_validate_hash_signature(const uint8_t * hash, size_t hash_length,
const P256ECDSASignature & signature) const override;
private:
uint8_t bytes[kP256_PublicKey_Length];
};
template <typename PK, typename Secret, typename Sig>
class ECPKeypair
{
public:
virtual ~ECPKeypair() {}
/** @brief Generate a new Certificate Signing Request (CSR).
* @param csr Newly generated CSR in DER format
* @param csr_length The caller provides the length of input buffer (csr). The function returns the actual length of generated
*CSR.
* @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
**/
virtual CHIP_ERROR NewCertificateSigningRequest(uint8_t * csr, size_t & csr_length) const = 0;
/**
* @brief A function to sign a msg using ECDSA
* @param msg Message that needs to be signed
* @param msg_length Length of message
* @param out_signature Buffer that will hold the output signature. The signature consists of: 2 EC elements (r and s),
* in raw <r,s> point form (see SEC1).
* @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
**/
virtual CHIP_ERROR ECDSA_sign_msg(const uint8_t * msg, size_t msg_length, Sig & out_signature) const = 0;
/**
* @brief A function to sign a hash using ECDSA
* @param hash Hash that needs to be signed
* @param hash_length Length of hash
* @param out_signature Buffer that will hold the output signature. The signature consists of: 2 EC elements (r and s),
* in raw <r,s> point form (see SEC1).
* @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
**/
virtual CHIP_ERROR ECDSA_sign_hash(const uint8_t * hash, size_t hash_length, Sig & out_signature) const = 0;
/** @brief A function to derive a shared secret using ECDH
* @param remote_public_key Public key of remote peer with which we are trying to establish secure channel. remote_public_key is
* ASN.1 DER encoded as padded big-endian field elements as described in SEC 1: Elliptic Curve Cryptography
* [https://www.secg.org/sec1-v2.pdf]
* @param out_secret Buffer to write out secret into. This is a byte array representing the x coordinate of the shared secret.
* @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
**/
virtual CHIP_ERROR ECDH_derive_secret(const PK & remote_public_key, Secret & out_secret) const = 0;
virtual const PK & Pubkey() const = 0;
};
struct alignas(size_t) P256KeypairContext
{
uint8_t mBytes[kMAX_P256Keypair_Context_Size];
};
typedef CapacityBoundBuffer<kP256_PublicKey_Length + kP256_PrivateKey_Length> P256SerializedKeypair;
class P256KeypairBase : public ECPKeypair<P256PublicKey, P256ECDHDerivedSecret, P256ECDSASignature>
{
public:
/**
* @brief Initialize the keypair.
* @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
**/
virtual CHIP_ERROR Initialize() = 0;
/**
* @brief Serialize the keypair.
* @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
**/
virtual CHIP_ERROR Serialize(P256SerializedKeypair & output) const = 0;
/**
* @brief Deserialize the keypair.
* @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
**/
virtual CHIP_ERROR Deserialize(P256SerializedKeypair & input) = 0;
};
class P256Keypair : public P256KeypairBase
{
public:
P256Keypair() {}
~P256Keypair() override;
/**
* @brief Initialize the keypair.
* @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
**/
CHIP_ERROR Initialize() override;
/**
* @brief Serialize the keypair.
* @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
**/
CHIP_ERROR Serialize(P256SerializedKeypair & output) const override;
/**
* @brief Deserialize the keypair.
* @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
**/
CHIP_ERROR Deserialize(P256SerializedKeypair & input) override;
/**
* @brief Generate a new Certificate Signing Request (CSR).
* @param csr Newly generated CSR in DER format
* @param csr_length The caller provides the length of input buffer (csr). The function returns the actual length of generated
*CSR.
* @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
**/
CHIP_ERROR NewCertificateSigningRequest(uint8_t * csr, size_t & csr_length) const override;
/**
* @brief A function to sign a msg using ECDSA
* @param msg Message that needs to be signed
* @param msg_length Length of message
* @param out_signature Buffer that will hold the output signature. The signature consists of: 2 EC elements (r and s),
* in raw <r,s> point form (see SEC1).
* @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
**/
CHIP_ERROR ECDSA_sign_msg(const uint8_t * msg, size_t msg_length, P256ECDSASignature & out_signature) const override;
/**
* @brief A function to sign a hash using ECDSA
* @param hash Hash that needs to be signed
* @param hash_length Length of hash
* @param out_signature Buffer that will hold the output signature. The signature consists of: 2 EC elements (r and s),
* in raw <r,s> point form (see SEC1).
* @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
**/
CHIP_ERROR ECDSA_sign_hash(const uint8_t * hash, size_t hash_length, P256ECDSASignature & out_signature) const override;
/**
* @brief A function to derive a shared secret using ECDH
*
* This implements the CHIP_Crypto_ECDH(PrivateKey myPrivateKey, PublicKey theirPublicKey) cryptographic primitive
* from the specification, using this class's private key from `mKeypair` as `myPrivateKey` and the remote
* public key from `remote_public_key` as `theirPublicKey`.
*
* @param remote_public_key Public key of remote peer with which we are trying to establish secure channel. remote_public_key is
* ASN.1 DER encoded as padded big-endian field elements as described in SEC 1: Elliptic Curve Cryptography
* [https://www.secg.org/sec1-v2.pdf]
* @param out_secret Buffer to write out secret into. This is a byte array representing the x coordinate of the shared secret.
* @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
**/
CHIP_ERROR ECDH_derive_secret(const P256PublicKey & remote_public_key, P256ECDHDerivedSecret & out_secret) const override;
/** @brief Return public key for the keypair.
**/
const P256PublicKey & Pubkey() const override { return mPublicKey; }
/** Release resources associated with this key pair */
void Clear();
private:
P256PublicKey mPublicKey;
mutable P256KeypairContext mKeypair;
bool mInitialized = false;
};
/**
* @brief A data structure for holding an AES CCM128 symmetric key, without the ownership of it.
*/
using AesCcm128KeySpan = FixedByteSpan<Crypto::kAES_CCM128_Key_Length>;
class AesCcm128Key
{
public:
AesCcm128Key() {}
~AesCcm128Key()
{
// Sanitize after use
ClearSecretData(&bytes[0], Length());
}
template <size_t N>
constexpr AesCcm128Key(const uint8_t (&raw_value)[N])
{
static_assert(N == kAES_CCM128_Key_Length, "Can only array-initialize from proper bounds");
memcpy(&bytes[0], &raw_value[0], N);
}
template <size_t N>
constexpr AesCcm128Key(const FixedByteSpan<N> & value)
{
static_assert(N == kAES_CCM128_Key_Length, "Can only initialize from proper sized byte span");
memcpy(&bytes[0], value.data(), N);
}
size_t Length() const { return sizeof(bytes); }
operator uint8_t *() { return bytes; }
operator const uint8_t *() const { return bytes; }
const uint8_t * ConstBytes() const { return &bytes[0]; }
AesCcm128KeySpan Span() const { return AesCcm128KeySpan(bytes); }
uint8_t * Bytes() { return &bytes[0]; }
private:
uint8_t bytes[kAES_CCM128_Key_Length];
};
/**
* @brief Convert a raw ECDSA signature to ASN.1 signature (per X9.62) as used by TLS libraries.
*
* Errors are:
* - CHIP_ERROR_INVALID_ARGUMENT on any argument being invalid (e.g. nullptr), wrong sizes,
* wrong or unsupported format,
* - CHIP_ERROR_BUFFER_TOO_SMALL on running out of space at runtime.
* - CHIP_ERROR_INTERNAL on any unexpected processing error.
*
* @param[in] fe_length_bytes Field Element length in bytes (e.g. 32 for P256 curve)
* @param[in] raw_sig Raw signature of <r,s> concatenated
* @param[out] out_asn1_sig ASN.1 DER signature format output buffer. Size must have space for at least
* kMax_ECDSA_X9Dot62_Asn1_Overhead. On CHIP_NO_ERROR, the out_asn1_sig buffer will be re-assigned
* to have the correct size based on variable-length output.
* @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
*/
CHIP_ERROR EcdsaRawSignatureToAsn1(size_t fe_length_bytes, const ByteSpan & raw_sig, MutableByteSpan & out_asn1_sig);
/**
* @brief Convert an ASN.1 DER signature (per X9.62) as used by TLS libraries to SEC1 raw format
*
* Errors are:
* - CHIP_ERROR_INVALID_ARGUMENT on any argument being invalid (e.g. nullptr), wrong sizes,
* wrong or unsupported format,
* - CHIP_ERROR_BUFFER_TOO_SMALL on running out of space at runtime.
* - CHIP_ERROR_INTERNAL on any unexpected processing error.
*
* @param[in] fe_length_bytes Field Element length in bytes (e.g. 32 for P256 curve)
* @param[in] asn1_sig ASN.1 DER signature input
* @param[out] out_raw_sig Raw signature of <r,s> concatenated format output buffer. Size must be at
* least >= `2 * fe_length_bytes`. On CHIP_NO_ERROR, the out_raw_sig buffer will be re-assigned
* to have the correct size (2 * fe_length_bytes).
* @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
*/
CHIP_ERROR EcdsaAsn1SignatureToRaw(size_t fe_length_bytes, const ByteSpan & asn1_sig, MutableByteSpan & out_raw_sig);
/**
* @brief Utility to emit a DER-encoded INTEGER given a raw unsigned large integer
* in big-endian order. The `out_der_integer` span is updated to reflect the final
* variable length, including tag and length, and must have at least `kEmitDerIntegerOverhead`
* extra space in addition to the `raw_integer.size()`.
* @param[in] raw_integer Bytes of a large unsigned integer in big-endian, possibly including leading zeroes
* @param[out] out_der_integer Buffer to receive the DER-encoded integer
* @return Returns CHIP_ERROR_INVALID_ARGUMENT or CHIP_ERROR_BUFFER_TOO_SMALL on error, CHIP_NO_ERROR otherwise.
*/
CHIP_ERROR ConvertIntegerRawToDer(const ByteSpan & raw_integer, MutableByteSpan & out_der_integer);
/**
* @brief Utility to emit a DER-encoded INTEGER given a raw unsigned large integer
* in big-endian order. The `out_der_integer` span is updated to reflect the final
* variable length, excluding tag and length, and must have at least `kEmitDerIntegerWithoutTagOverhead`
* extra space in addition to the `raw_integer.size()`.
* @param[in] raw_integer Bytes of a large unsigned integer in big-endian, possibly including leading zeroes
* @param[out] out_der_integer Buffer to receive the DER-encoded integer
* @return Returns CHIP_ERROR_INVALID_ARGUMENT or CHIP_ERROR_BUFFER_TOO_SMALL on error, CHIP_NO_ERROR otherwise.
*/
CHIP_ERROR ConvertIntegerRawToDerWithoutTag(const ByteSpan & raw_integer, MutableByteSpan & out_der_integer);
/**
* @brief A function that implements AES-CCM encryption
*
* This implements the CHIP_Crypto_AEAD_GenerateEncrypt() cryptographic primitive
* from the specification. For an empty plaintext, the user of the API can provide
* an empty string, or a nullptr, and provide plaintext_length as 0. The output buffer,
* ciphertext can also be an empty string, or a nullptr for this case.
*
* @param plaintext Plaintext to encrypt
* @param plaintext_length Length of plain_text
* @param aad Additional authentication data
* @param aad_length Length of additional authentication data
* @param key Encryption key
* @param key_length Length of encryption key (in bytes)
* @param nonce Encryption nonce
* @param nonce_length Length of encryption nonce
* @param ciphertext Buffer to write ciphertext into. Caller must ensure this is large enough to hold the ciphertext
* @param tag Buffer to write tag into. Caller must ensure this is large enough to hold the tag
* @param tag_length Expected length of tag
* @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
* */
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 * nonce, size_t nonce_length, uint8_t * ciphertext,
uint8_t * tag, size_t tag_length);
/**
* @brief A function that implements AES-CCM decryption
*
* This implements the CHIP_Crypto_AEAD_DecryptVerify() cryptographic primitive
* from the specification. For an empty ciphertext, the user of the API can provide
* an empty string, or a nullptr, and provide ciphertext_length as 0. The output buffer,
* plaintext can also be an empty string, or a nullptr for this case.
*
* @param ciphertext Ciphertext to decrypt
* @param ciphertext_length Length of ciphertext
* @param aad Additional authentical data.
* @param aad_length Length of additional authentication data
* @param tag Tag to use to decrypt
* @param tag_length Length of tag
* @param key Decryption key
* @param key_length Length of Decryption key (in bytes)
* @param nonce Encryption nonce
* @param nonce_length Length of encryption nonce
* @param plaintext Buffer to write plaintext into
* @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
**/
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 * nonce,
size_t nonce_length, uint8_t * plaintext);
/**
* @brief Generate a PKCS#10 CSR, usable for Matter, from a P256Keypair.
*
* This uses first principles ASN.1 encoding to avoid relying on the CHIPCryptoPAL backend
* itself, other than to provide an implementation of a P256Keypair * that supports
* at least `::Pubkey()` and `::ECDSA_sign_msg`. This allows using it with
* OS/Platform-bridged private key handling, without requiring a specific
* implementation of other bits like ASN.1.
*
* The CSR will have subject OU set to `CSA`. This is needed since omiting
* subject altogether often trips CSR parsing code. The profile at the CA can
* be configured to ignore CSR requested subject.
*
* @param keypair The key pair for which a CSR should be generated. Must not be null.
* @param csr_span Span to hold the resulting CSR. Must be at least kMAX_CSR_Length. Otherwise returns CHIP_ERROR_BUFFER_TOO_SMALL.
* It will get resized to actual size needed on success.
* @return Returns a CHIP_ERROR from P256Keypair or ASN.1 backend on error, CHIP_NO_ERROR otherwise
**/
CHIP_ERROR GenerateCertificateSigningRequest(const P256Keypair * keypair, MutableByteSpan & csr_span);
/**
* @brief Verify the Certificate Signing Request (CSR). If successfully verified, it outputs the public key from the CSR.
* @param csr CSR in DER format
* @param csr_length The length of the CSR
* @param pubkey The public key from the verified CSR
* @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
**/
CHIP_ERROR VerifyCertificateSigningRequest(const uint8_t * csr, size_t csr_length, P256PublicKey & pubkey);
/**
* @brief A function that implements SHA-256 hash
*
* This implements the CHIP_Crypto_Hash() cryptographic primitive
* in the the specification.
*
* @param data The data to hash
* @param data_length Length of the data
* @param out_buffer Pointer to buffer to write output into
* @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
**/
CHIP_ERROR Hash_SHA256(const uint8_t * data, size_t data_length, uint8_t * out_buffer);
/**
* @brief A function that implements SHA-1 hash
* @param data The data to hash
* @param data_length Length of the data
* @param out_buffer Pointer to buffer to write output into
* @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
**/
CHIP_ERROR Hash_SHA1(const uint8_t * data, size_t data_length, uint8_t * out_buffer);
/**
* @brief A class that defines stream based implementation of SHA-256 hash
* It's expected that the object of this class can be safely copied.
* All implementations must check for std::is_trivially_copyable.
**/
struct alignas(size_t) HashSHA256OpaqueContext
{
uint8_t mOpaque[kMAX_Hash_SHA256_Context_Size];
};
class Hash_SHA256_stream
{
public:
Hash_SHA256_stream();
~Hash_SHA256_stream();
/**
* @brief Re-initialize digest computation to an empty context.
*
* @return CHIP_ERROR_INTERNAL on failure to initialize the context,
* CHIP_NO_ERROR otherwise.
*/
CHIP_ERROR Begin();
/**
* @brief Add some data to the digest computation, updating internal state.
*
* @param[in] data The span of bytes to include in the digest update process.
*
* @return CHIP_ERROR_INTERNAL on failure to ingest the data, CHIP_NO_ERROR otherwise.
*/
CHIP_ERROR AddData(const ByteSpan data);
/**
* @brief Get the intermediate padded digest for the current state of the stream.
*
* More data can be added before finish is called.
*
* @param[in,out] out_buffer Output buffer to receive the digest. `out_buffer` must
* be at least `kSHA256_Hash_Length` bytes long. The `out_buffer` size
* will be set to `kSHA256_Hash_Length` on success.
*
* @return CHIP_ERROR_INTERNAL on failure to compute the digest, CHIP_ERROR_BUFFER_TOO_SMALL
* if out_buffer is too small, CHIP_NO_ERROR otherwise.
*/
CHIP_ERROR GetDigest(MutableByteSpan & out_buffer);
/**
* @brief Finalize the stream digest computation, getting the final digest.
*
* @param[in,out] out_buffer Output buffer to receive the digest. `out_buffer` must
* be at least `kSHA256_Hash_Length` bytes long. The `out_buffer` size
* will be set to `kSHA256_Hash_Length` on success.
*
* @return CHIP_ERROR_INTERNAL on failure to compute the digest, CHIP_ERROR_BUFFER_TOO_SMALL
* if out_buffer is too small, CHIP_NO_ERROR otherwise.
*/
CHIP_ERROR Finish(MutableByteSpan & out_buffer);
/**
* @brief Clear-out internal digest data to avoid lingering the state.
*/
void Clear();
private:
HashSHA256OpaqueContext mContext;
};
class HKDF_sha
{
public:
HKDF_sha() {}
virtual ~HKDF_sha() {}
/**
* @brief A function that implements SHA-256 based HKDF
*
* This implements the CHIP_Crypto_KDF() cryptographic primitive
* in the the specification.
*
* Error values are:
* - CHIP_ERROR_INVALID_ARGUMENT: for any bad arguments or nullptr input on
* any pointer.
* - CHIP_ERROR_INTERNAL: for any unexpected error arising in the underlying
* cryptographic layers.
*
* @param secret The secret to use as the key to the HKDF
* @param secret_length Length of the secret
* @param salt Optional salt to use as input to the HKDF
* @param salt_length Length of the salt
* @param info Optional info to use as input to the HKDF
* @param info_length Length of the info
* @param out_buffer Pointer to buffer to write output into.
* @param out_length Size of the underlying out_buffer. That length of output key material will be generated in out_buffer.
* @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
**/
virtual CHIP_ERROR HKDF_SHA256(const uint8_t * secret, size_t secret_length, const uint8_t * salt, size_t salt_length,
const uint8_t * info, size_t info_length, uint8_t * out_buffer, size_t out_length);
};
class HMAC_sha
{
public:
HMAC_sha() {}
virtual ~HMAC_sha() {}
/**
* @brief A function that implements SHA-256 based HMAC per FIPS1981.
*
* This implements the CHIP_Crypto_HMAC() cryptographic primitive
* in the the specification.
*
* The `out_length` must be at least kSHA256_Hash_Length, and only
* kSHA256_Hash_Length bytes are written to out_buffer.
*
* Error values are:
* - CHIP_ERROR_INVALID_ARGUMENT: for any bad arguments or nullptr input on
* any pointer.
* - CHIP_ERROR_INTERNAL: for any unexpected error arising in the underlying
* cryptographic layers.
*
* @param key The key to use for the HMAC operation
* @param key_length Length of the key
* @param message Message over which to compute the HMAC
* @param message_length Length of the message over which to compute the HMAC
* @param out_buffer Pointer to buffer into which to write the output.
* @param out_length Underlying size of the `out_buffer`.
* @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
**/
virtual CHIP_ERROR 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);
};
/**
* @brief A cryptographically secure random number generator based on NIST SP800-90A
* @param out_buffer Buffer into which to write random bytes
* @param out_length Number of random bytes to generate
* @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
**/
CHIP_ERROR DRBG_get_bytes(uint8_t * out_buffer, size_t out_length);
/** @brief Entropy callback function
* @param data Callback-specific data pointer
* @param output Output data to fill
* @param len Length of output buffer
* @param olen The actual amount of data that was written to output buffer
* @return 0 if success
*/
typedef int (*entropy_source)(void * data, uint8_t * output, size_t len, size_t * olen);
/** @brief A function to add entropy sources to crypto library
* @param fn_source Function pointer to the entropy source
* @param p_source Data that should be provided when fn_source is called
* @param threshold Minimum required from source before entropy is released
* @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
**/
CHIP_ERROR add_entropy_source(entropy_source fn_source, void * p_source, size_t threshold);
class PBKDF2_sha256
{
public:
PBKDF2_sha256() {}
virtual ~PBKDF2_sha256() {}
/** @brief Function to derive key using password. SHA256 hashing algorithm is used for calculating hmac.
* @param password password used for key derivation
* @param plen length of buffer containing password
* @param salt salt to use as input to the KDF
* @param slen length of salt
* @param iteration_count number of iterations to run
* @param key_length length of output key
* @param output output buffer where the key will be written
* @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
**/
virtual CHIP_ERROR 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);
};
/**
* The below class implements the draft 01 version of the Spake2+ protocol as
* defined in https://www.ietf.org/id/draft-bar-cfrg-spake2plus-01.html.
*
* The following describes the protocol flows:
*
* Commissioner Accessory
* ------------ ---------
*
* Init
* BeginProver
* ComputeRoundOne ------------->
* Init
* BeginVerifier
* /- ComputeRoundOne
* <------------- ComputeRoundTwo
* ComputeRoundTwo ------------->
* KeyConfirm KeyConfirm
* GetKeys GetKeys
*
**/
class Spake2p
{
public:
Spake2p(size_t fe_size, size_t point_size, size_t hash_size);
virtual ~Spake2p() {}
/**
* @brief Initialize Spake2+ with some context specific information.
*
* @param context The context is arbitrary but should include information about the
* protocol being run, contain the transcript for negotiation, include
* the PKBDF parameters, etc.
* @param context_len The length of the context.
*
* @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
**/
virtual CHIP_ERROR Init(const uint8_t * context, size_t context_len);
/**
* @brief Free Spake2+ underlying objects.
**/
virtual void Clear() = 0;
/**
* @brief Start the Spake2+ process as a verifier (i.e. an accessory being provisioned).
*
* @param my_identity The verifier identity. May be NULL if identities are not established.
* @param my_identity_len The verifier identity length.
* @param peer_identity The peer identity. May be NULL if identities are not established.
* @param peer_identity_len The peer identity length.
* @param w0in The input w0 (a parameter baked into the device or computed with ComputeW0).
* @param w0in_len The input w0 length.
* @param Lin The input L (a parameter baked into the device or computed with ComputeL).
* @param Lin_len The input L length.
*
* @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
**/
virtual CHIP_ERROR BeginVerifier(const uint8_t * my_identity, size_t my_identity_len, const uint8_t * peer_identity,
size_t peer_identity_len, const uint8_t * w0in, size_t w0in_len, const uint8_t * Lin,
size_t Lin_len);
/**
* @brief Start the Spake2+ process as a prover (i.e. a commissioner).
*
* @param my_identity The prover identity. May be NULL if identities are not established.
* @param my_identity_len The prover identity length.
* @param peer_identity The peer identity. May be NULL if identities are not established.
* @param peer_identity_len The peer identity length.
* @param w0in The input w0 (an output from the PBKDF).
* @param w0in_len The input w0 length.
* @param w1in The input w1 (an output from the PBKDF).
* @param w1in_len The input w1 length.
*
* @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
**/
virtual CHIP_ERROR BeginProver(const uint8_t * my_identity, size_t my_identity_len, const uint8_t * peer_identity,
size_t peer_identity_len, const uint8_t * w0in, size_t w0in_len, const uint8_t * w1in,
size_t w1in_len);
/**
* @brief Compute the first round of the protocol.
*
* @param pab X value from commissioner.
* @param pab_len X length.
* @param out The output first round Spake2+ contribution.
* @param out_len The output first round Spake2+ contribution length.
*
* @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
**/
virtual CHIP_ERROR ComputeRoundOne(const uint8_t * pab, size_t pab_len, uint8_t * out, size_t * out_len);
/**
* @brief Compute the second round of the protocol.
*
* @param in The peer first round Spake2+ contribution.
* @param in_len The peer first round Spake2+ contribution length.
* @param out The output second round Spake2+ contribution.
* @param out_len The output second round Spake2+ contribution length.
*
* @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
**/
virtual CHIP_ERROR ComputeRoundTwo(const uint8_t * in, size_t in_len, uint8_t * out, size_t * out_len);
/**
* @brief Confirm that each party computed the same keys.
*
* @param in The peer second round Spake2+ contribution.
* @param in_len The peer second round Spake2+ contribution length.
*
* @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
**/
virtual CHIP_ERROR KeyConfirm(const uint8_t * in, size_t in_len);
/**
* @brief Return the shared secret.
*
* @param out The output secret.
* @param out_len The output secret length.
*
* @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
**/
CHIP_ERROR GetKeys(uint8_t * out, size_t * out_len);
CHIP_ERROR InternalHash(const uint8_t * in, size_t in_len);
CHIP_ERROR WriteMN();
CHIP_ERROR GenerateKeys();
/**
* @brief Load a field element.
*
* @param in The input big endian field element.
* @param in_len The size of the input buffer in bytes.
* @param fe A pointer to an initialized implementation dependant field element.
*
* @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise
**/
virtual CHIP_ERROR FELoad(const uint8_t * in, size_t in_len, void * fe) = 0;
/**
* @brief Write a field element in big-endian format.
*
* @param fe The field element to write.
* @param out The output buffer.
* @param out_len The length of the output buffer.
*
* @return Returns a CHIP_ERROR on error, CHIP_NO_ERROR otherwise