-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
CASESession.cpp
1512 lines (1170 loc) · 61.1 KB
/
CASESession.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) 2021 Project CHIP Authors
* All rights reserved.
*
* 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
* This file implements the the CHIP CASE Session object that provides
* APIs for constructing a secure session using a certificate from the device's
* operational credentials.
*
*/
#include <protocols/secure_channel/CASESession.h>
#include <inttypes.h>
#include <string.h>
#include <lib/core/CHIPEncoding.h>
#include <lib/core/CHIPSafeCasts.h>
#include <lib/support/CHIPMem.h>
#include <lib/support/CodeUtils.h>
#include <lib/support/SafeInt.h>
#include <lib/support/ScopedBuffer.h>
#include <lib/support/TypeTraits.h>
#include <protocols/Protocols.h>
#include <protocols/secure_channel/StatusReport.h>
#include <system/TLVPacketBufferBackingStore.h>
#include <transport/SessionManager.h>
namespace chip {
using namespace Crypto;
using namespace Credentials;
using namespace Messaging;
using namespace Encoding;
using namespace Protocols::SecureChannel;
constexpr uint8_t kKDFSR2Info[] = { 0x53, 0x69, 0x67, 0x6d, 0x61, 0x32 };
constexpr uint8_t kKDFSR3Info[] = { 0x53, 0x69, 0x67, 0x6d, 0x61, 0x33 };
constexpr size_t kKDFInfoLength = sizeof(kKDFSR2Info);
constexpr uint8_t kKDFSEInfo[] = { 0x53, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x4b, 0x65, 0x79, 0x73 };
constexpr size_t kKDFSEInfoLength = sizeof(kKDFSEInfo);
constexpr uint8_t kKDFS1RKeyInfo[] = { 0x53, 0x69, 0x67, 0x6d, 0x61, 0x31, 0x5f, 0x52, 0x65, 0x73, 0x75, 0x6d, 0x65 };
constexpr uint8_t kKDFS2RKeyInfo[] = { 0x53, 0x69, 0x67, 0x6d, 0x61, 0x32, 0x5f, 0x52, 0x65, 0x73, 0x75, 0x6d, 0x65 };
constexpr uint8_t kResume1MIC_Nonce[] =
/* "NCASE_SigmaR1" */ { 0x4e, 0x43, 0x41, 0x53, 0x45, 0x5f, 0x53, 0x69, 0x67, 0x6d, 0x61, 0x53, 0x31 };
constexpr uint8_t kResume2MIC_Nonce[] =
/* "NCASE_SigmaR2" */ { 0x4e, 0x43, 0x41, 0x53, 0x45, 0x5f, 0x53, 0x69, 0x67, 0x6d, 0x61, 0x53, 0x32 };
constexpr uint8_t kTBEData2_Nonce[] =
/* "NCASE_Sigma2N" */ { 0x4e, 0x43, 0x41, 0x53, 0x45, 0x5f, 0x53, 0x69, 0x67, 0x6d, 0x61, 0x32, 0x4e };
constexpr uint8_t kTBEData3_Nonce[] =
/* "NCASE_Sigma3N" */ { 0x4e, 0x43, 0x41, 0x53, 0x45, 0x5f, 0x53, 0x69, 0x67, 0x6d, 0x61, 0x33, 0x4e };
constexpr size_t kTBEDataNonceLength = sizeof(kTBEData2_Nonce);
static_assert(sizeof(kTBEData2_Nonce) == sizeof(kTBEData3_Nonce), "TBEData2_Nonce and TBEData3_Nonce must be same size");
// TODO: move this constant over to src/crypto/CHIPCryptoPAL.h - name it CHIP_CRYPTO_AEAD_MIC_LENGTH_BYTES
constexpr size_t kTAGSize = 16;
enum
{
kTag_TBEData_SenderNOC = 1,
kTag_TBEData_SenderICAC = 2,
kTag_TBEData_Signature = 3,
kTag_TBEData_ResumptionID = 4,
};
#ifdef ENABLE_HSM_HKDF
using HKDF_sha_crypto = HKDF_shaHSM;
#else
using HKDF_sha_crypto = HKDF_sha;
#endif
// Wait at most 10 seconds for the response from the peer.
// This timeout value assumes the underlying transport is reliable.
// The session establishment fails if the response is not received within timeout window.
static constexpr ExchangeContext::Timeout kSigma_Response_Timeout = 10000;
CASESession::CASESession()
{
mTrustedRootId = CertificateKeyId();
}
CASESession::~CASESession()
{
// Let's clear out any security state stored in the object, before destroying it.
Clear();
}
void CASESession::Clear()
{
// This function zeroes out and resets the memory used by the object.
// It's done so that no security related information will be leaked.
mCommissioningHash.Clear();
mPairingComplete = false;
PairingSession::Clear();
mState = kInitialized;
CloseExchange();
}
void CASESession::CloseExchange()
{
if (mExchangeCtxt != nullptr)
{
mExchangeCtxt->Close();
mExchangeCtxt = nullptr;
}
}
CHIP_ERROR CASESession::Serialize(CASESessionSerialized & output)
{
uint16_t serializedLen = 0;
CASESessionSerializable serializable;
VerifyOrReturnError(BASE64_ENCODED_LEN(sizeof(serializable)) <= sizeof(output.inner), CHIP_ERROR_INVALID_ARGUMENT);
ReturnErrorOnFailure(ToSerializable(serializable));
serializedLen = chip::Base64Encode(Uint8::to_const_uchar(reinterpret_cast<uint8_t *>(&serializable)),
static_cast<uint16_t>(sizeof(serializable)), Uint8::to_char(output.inner));
VerifyOrReturnError(serializedLen > 0, CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrReturnError(serializedLen < sizeof(output.inner), CHIP_ERROR_INVALID_ARGUMENT);
output.inner[serializedLen] = '\0';
return CHIP_NO_ERROR;
}
CHIP_ERROR CASESession::Deserialize(CASESessionSerialized & input)
{
CASESessionSerializable serializable;
size_t maxlen = BASE64_ENCODED_LEN(sizeof(serializable));
size_t len = strnlen(Uint8::to_char(input.inner), maxlen);
uint16_t deserializedLen = 0;
VerifyOrReturnError(len < sizeof(CASESessionSerialized), CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrReturnError(CanCastTo<uint16_t>(len), CHIP_ERROR_INVALID_ARGUMENT);
memset(&serializable, 0, sizeof(serializable));
deserializedLen =
Base64Decode(Uint8::to_const_char(input.inner), static_cast<uint16_t>(len), Uint8::to_uchar((uint8_t *) &serializable));
VerifyOrReturnError(deserializedLen > 0, CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrReturnError(deserializedLen <= sizeof(serializable), CHIP_ERROR_INVALID_ARGUMENT);
ReturnErrorOnFailure(FromSerializable(serializable));
return CHIP_NO_ERROR;
}
CHIP_ERROR CASESession::ToSerializable(CASESessionSerializable & serializable)
{
const NodeId peerNodeId = GetPeerNodeId();
VerifyOrReturnError(CanCastTo<uint16_t>(mSharedSecret.Length()), CHIP_ERROR_INTERNAL);
VerifyOrReturnError(CanCastTo<uint16_t>(sizeof(mMessageDigest)), CHIP_ERROR_INTERNAL);
VerifyOrReturnError(CanCastTo<uint16_t>(sizeof(mIPK)), CHIP_ERROR_INTERNAL);
VerifyOrReturnError(CanCastTo<uint64_t>(peerNodeId), CHIP_ERROR_INTERNAL);
memset(&serializable, 0, sizeof(serializable));
serializable.mSharedSecretLen = LittleEndian::HostSwap16(static_cast<uint16_t>(mSharedSecret.Length()));
serializable.mMessageDigestLen = LittleEndian::HostSwap16(static_cast<uint16_t>(sizeof(mMessageDigest)));
serializable.mIPKLen = LittleEndian::HostSwap16(static_cast<uint16_t>(sizeof(mIPK)));
serializable.mPairingComplete = (mPairingComplete) ? 1 : 0;
serializable.mPeerNodeId = LittleEndian::HostSwap64(peerNodeId);
serializable.mLocalSessionId = LittleEndian::HostSwap16(GetLocalSessionId());
serializable.mPeerSessionId = LittleEndian::HostSwap16(GetPeerSessionId());
memcpy(serializable.mResumptionId, mResumptionId, sizeof(mResumptionId));
memcpy(serializable.mSharedSecret, mSharedSecret, mSharedSecret.Length());
memcpy(serializable.mMessageDigest, mMessageDigest, sizeof(mMessageDigest));
memcpy(serializable.mIPK, mIPK, sizeof(mIPK));
return CHIP_NO_ERROR;
}
CHIP_ERROR CASESession::FromSerializable(const CASESessionSerializable & serializable)
{
mPairingComplete = (serializable.mPairingComplete == 1);
uint16_t length = LittleEndian::HostSwap16(serializable.mSharedSecretLen);
ReturnErrorOnFailure(mSharedSecret.SetLength(static_cast<size_t>(length)));
memset(mSharedSecret, 0, sizeof(mSharedSecret.Capacity()));
memcpy(mSharedSecret, serializable.mSharedSecret, length);
length = LittleEndian::HostSwap16(serializable.mMessageDigestLen);
VerifyOrReturnError(length <= sizeof(mMessageDigest), CHIP_ERROR_INVALID_ARGUMENT);
memcpy(mMessageDigest, serializable.mMessageDigest, length);
length = LittleEndian::HostSwap16(serializable.mIPKLen);
VerifyOrReturnError(length <= sizeof(mIPK), CHIP_ERROR_INVALID_ARGUMENT);
memcpy(mIPK, serializable.mIPK, length);
SetPeerNodeId(LittleEndian::HostSwap64(serializable.mPeerNodeId));
SetLocalSessionId(LittleEndian::HostSwap16(serializable.mLocalSessionId));
SetPeerSessionId(LittleEndian::HostSwap16(serializable.mPeerSessionId));
memcpy(mResumptionId, serializable.mResumptionId, sizeof(mResumptionId));
return CHIP_NO_ERROR;
}
CHIP_ERROR CASESession::Init(uint16_t mySessionId, SessionEstablishmentDelegate * delegate)
{
VerifyOrReturnError(delegate != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
Clear();
ReturnErrorOnFailure(mCommissioningHash.Begin());
mDelegate = delegate;
SetLocalSessionId(mySessionId);
mValidContext.Reset();
mValidContext.mRequiredKeyUsages.Set(KeyUsageFlags::kDigitalSignature);
mValidContext.mRequiredKeyPurposes.Set(KeyPurposeFlags::kServerAuth);
return CHIP_NO_ERROR;
}
CHIP_ERROR
CASESession::ListenForSessionEstablishment(uint16_t mySessionId, Transport::FabricTable * fabrics,
SessionEstablishmentDelegate * delegate)
{
VerifyOrReturnError(fabrics != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
ReturnErrorOnFailure(Init(mySessionId, delegate));
mFabricsTable = fabrics;
mPairingComplete = false;
ChipLogDetail(SecureChannel, "Waiting for Sigma1 msg");
return CHIP_NO_ERROR;
}
CHIP_ERROR CASESession::EstablishSession(const Transport::PeerAddress peerAddress, Transport::FabricInfo * fabric,
NodeId peerNodeId, uint16_t mySessionId, ExchangeContext * exchangeCtxt,
SessionEstablishmentDelegate * delegate)
{
CHIP_ERROR err = CHIP_NO_ERROR;
// Return early on error here, as we have not initalized any state yet
ReturnErrorCodeIf(exchangeCtxt == nullptr, CHIP_ERROR_INVALID_ARGUMENT);
ReturnErrorCodeIf(fabric == nullptr, CHIP_ERROR_INVALID_ARGUMENT);
err = Init(mySessionId, delegate);
// We are setting the exchange context specifically before checking for error.
// This is to make sure the exchange will get closed if Init() returned an error.
mExchangeCtxt = exchangeCtxt;
// From here onwards, let's go to exit on error, as some state might have already
// been initialized
SuccessOrExit(err);
mFabricInfo = fabric;
mExchangeCtxt->SetResponseTimeout(kSigma_Response_Timeout);
SetPeerAddress(peerAddress);
SetPeerNodeId(peerNodeId);
err = SendSigma1();
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
Clear();
}
return err;
}
void CASESession::OnResponseTimeout(ExchangeContext * ec)
{
VerifyOrReturn(ec != nullptr, ChipLogError(SecureChannel, "CASESession::OnResponseTimeout was called by null exchange"));
VerifyOrReturn(mExchangeCtxt == ec, ChipLogError(SecureChannel, "CASESession::OnResponseTimeout exchange doesn't match"));
ChipLogError(SecureChannel, "CASESession timed out while waiting for a response from the peer. Current state was %" PRIu8,
mState);
mDelegate->OnSessionEstablishmentError(CHIP_ERROR_TIMEOUT);
// Null out mExchangeCtxt so that Clear() doesn't try closing it. The
// exchange will handle that.
mExchangeCtxt = nullptr;
Clear();
}
CHIP_ERROR CASESession::DeriveSecureSession(CryptoContext & session, CryptoContext::SessionRole role)
{
size_t saltlen;
(void) kKDFSEInfo;
(void) kKDFSEInfoLength;
VerifyOrReturnError(mPairingComplete, CHIP_ERROR_INCORRECT_STATE);
// Generate Salt for Encryption keys
saltlen = sizeof(mIPK) + kSHA256_Hash_Length;
chip::Platform::ScopedMemoryBuffer<uint8_t> msg_salt;
ReturnErrorCodeIf(!msg_salt.Alloc(saltlen), CHIP_ERROR_NO_MEMORY);
{
Encoding::LittleEndian::BufferWriter bbuf(msg_salt.Get(), saltlen);
bbuf.Put(mIPK, sizeof(mIPK));
bbuf.Put(mMessageDigest, sizeof(mMessageDigest));
VerifyOrReturnError(bbuf.Fit(), CHIP_ERROR_BUFFER_TOO_SMALL);
}
ReturnErrorOnFailure(session.InitFromSecret(ByteSpan(mSharedSecret, mSharedSecret.Length()), ByteSpan(msg_salt.Get(), saltlen),
CryptoContext::SessionInfoType::kSessionEstablishment, role));
return CHIP_NO_ERROR;
}
CHIP_ERROR CASESession::SendSigma1()
{
size_t data_len = EstimateTLVStructOverhead(kSigmaParamRandomNumberSize + sizeof(uint16_t) + kSHA256_Hash_Length +
kP256_PublicKey_Length + kCASEResumptionIDSize + kTAGSize,
7);
System::PacketBufferTLVWriter tlvWriter;
System::PacketBufferHandle msg_R1;
TLV::TLVType outerContainerType = TLV::kTLVType_NotSpecified;
// uint8_t initiatorRandom[kSigmaParamRandomNumberSize] = { 0 };
uint8_t destinationIdentifier[kSHA256_Hash_Length] = { 0 };
// Generate an ephemeral keypair
#ifdef ENABLE_HSM_CASE_EPHEMERAL_KEY
mEphemeralKey.SetKeyId(CASE_EPHEMERAL_KEY);
#endif
ReturnErrorOnFailure(mEphemeralKey.Initialize());
// Fill in the random value
ReturnErrorOnFailure(DRBG_get_bytes(mInitiatorRandom, sizeof(mInitiatorRandom)));
// Construct Sigma1 Msg
msg_R1 = System::PacketBufferHandle::New(data_len);
VerifyOrReturnError(!msg_R1.IsNull(), CHIP_ERROR_NO_MEMORY);
tlvWriter.Init(std::move(msg_R1));
ReturnErrorOnFailure(tlvWriter.StartContainer(TLV::AnonymousTag, TLV::kTLVType_Structure, outerContainerType));
ReturnErrorOnFailure(tlvWriter.PutBytes(TLV::ContextTag(1), mInitiatorRandom, sizeof(mInitiatorRandom)));
// Retrieve Session Identifier
ReturnErrorOnFailure(tlvWriter.Put(TLV::ContextTag(2), GetLocalSessionId(), true));
// Generate a Destination Identifier
{
MutableByteSpan destinationIdSpan(destinationIdentifier);
ReturnErrorCodeIf(mFabricInfo == nullptr, CHIP_ERROR_INCORRECT_STATE);
memcpy(mIPK, GetIPKList()->data(), sizeof(mIPK));
ReturnErrorOnFailure(
mFabricInfo->GenerateDestinationID(ByteSpan(mIPK), ByteSpan(mInitiatorRandom), GetPeerNodeId(), destinationIdSpan));
}
ReturnErrorOnFailure(tlvWriter.PutBytes(TLV::ContextTag(3), destinationIdentifier, sizeof(destinationIdentifier)));
ReturnErrorOnFailure(
tlvWriter.PutBytes(TLV::ContextTag(4), mEphemeralKey.Pubkey(), static_cast<uint32_t>(mEphemeralKey.Pubkey().Length())));
// If CASE session was previously established using the current state information, let's fill in the session resumption
// information in the the Sigma1 request. It'll speed up the session establishment process if the peer can resume the old
// session.
if (mPairingComplete)
{
ReturnErrorOnFailure(tlvWriter.PutBytes(TLV::ContextTag(6), mResumptionId, kCASEResumptionIDSize));
chip::Platform::ScopedMemoryBuffer<uint8_t> initiatorResume1MIC;
ReturnErrorCodeIf(!initiatorResume1MIC.Alloc(kTAGSize), CHIP_ERROR_NO_MEMORY);
MutableByteSpan resumeMICSpan(initiatorResume1MIC.Get(), kTAGSize);
ReturnErrorOnFailure(GenerateSigmaResumeMIC(ByteSpan(mInitiatorRandom), ByteSpan(mResumptionId), ByteSpan(kKDFS1RKeyInfo),
ByteSpan(kResume1MIC_Nonce), resumeMICSpan));
ReturnErrorOnFailure(tlvWriter.Put(TLV::ContextTag(7), resumeMICSpan));
}
ReturnErrorOnFailure(tlvWriter.EndContainer(outerContainerType));
ReturnErrorOnFailure(tlvWriter.Finalize(&msg_R1));
ReturnErrorOnFailure(mCommissioningHash.AddData(ByteSpan{ msg_R1->Start(), msg_R1->DataLength() }));
mState = kSentSigma1;
// Call delegate to send the msg to peer
ReturnErrorOnFailure(mExchangeCtxt->SendMessage(Protocols::SecureChannel::MsgType::CASE_Sigma1, std::move(msg_R1),
SendFlags(SendMessageFlags::kExpectResponse)));
ChipLogDetail(SecureChannel, "Sent Sigma1 msg");
return CHIP_NO_ERROR;
}
CHIP_ERROR CASESession::HandleSigma1_and_SendSigma2(System::PacketBufferHandle && msg)
{
ReturnErrorOnFailure(HandleSigma1(std::move(msg)));
return CHIP_NO_ERROR;
}
CHIP_ERROR CASESession::HandleSigma1(System::PacketBufferHandle && msg)
{
CHIP_ERROR err = CHIP_NO_ERROR;
System::PacketBufferTLVReader tlvReader;
TLV::TLVType containerType = TLV::kTLVType_Structure;
uint16_t initiatorSessionId;
uint8_t destinationIdentifier[kSHA256_Hash_Length];
uint8_t initiatorRandom[kSigmaParamRandomNumberSize];
uint32_t decodeTagIdSeq = 0;
ChipLogDetail(SecureChannel, "Received Sigma1 msg");
bool sessionResumptionRequested = false;
uint8_t resumptionID[kCASEResumptionIDSize];
MutableByteSpan resumptionIDSpan(resumptionID);
uint8_t initiatorResume1MIC[kTAGSize];
MutableByteSpan resume1MICSpan(initiatorResume1MIC);
SuccessOrExit(err = ParseSessionResumptionRequest(msg, sessionResumptionRequested, resumptionIDSpan, resume1MICSpan));
SuccessOrExit(err = mCommissioningHash.AddData(ByteSpan{ msg->Start(), msg->DataLength() }));
tlvReader.Init(std::move(msg));
SuccessOrExit(err = tlvReader.Next(containerType, TLV::AnonymousTag));
SuccessOrExit(err = tlvReader.EnterContainer(containerType));
SuccessOrExit(err = tlvReader.Next());
VerifyOrExit(TLV::TagNumFromTag(tlvReader.GetTag()) == ++decodeTagIdSeq, err = CHIP_ERROR_INVALID_TLV_TAG);
SuccessOrExit(err = tlvReader.GetBytes(initiatorRandom, sizeof(initiatorRandom)));
SuccessOrExit(err = tlvReader.Next());
VerifyOrExit(TLV::TagNumFromTag(tlvReader.GetTag()) == ++decodeTagIdSeq, err = CHIP_ERROR_INVALID_TLV_TAG);
SuccessOrExit(err = tlvReader.Get(initiatorSessionId));
ChipLogDetail(SecureChannel, "Peer assigned session key ID %d", initiatorSessionId);
SetPeerSessionId(initiatorSessionId);
if (sessionResumptionRequested && memcmp(resumptionID, mResumptionId, kCASEResumptionIDSize) == 0)
{
// Cross check resume1MIC with the shared secret
SuccessOrExit(err = ValidateSigmaResumeMIC(resume1MICSpan, ByteSpan(initiatorRandom), ByteSpan(mResumptionId),
ByteSpan(kKDFS1RKeyInfo), ByteSpan(kResume1MIC_Nonce)));
// Send Sigma2Resume message to the initiator
SuccessOrExit(err = SendSigma2Resume(ByteSpan(initiatorRandom)));
}
else
{
const ByteSpan * ipkListSpan = GetIPKList();
FabricIndex fabricIndex = Transport::kUndefinedFabricIndex;
memcpy(mIPK, ipkListSpan->data(), sizeof(mIPK));
SuccessOrExit(err = tlvReader.Next());
VerifyOrExit(TLV::TagNumFromTag(tlvReader.GetTag()) == ++decodeTagIdSeq, err = CHIP_ERROR_INVALID_TLV_TAG);
SuccessOrExit(err = tlvReader.GetBytes(destinationIdentifier, sizeof(destinationIdentifier)));
VerifyOrExit(mFabricsTable != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
fabricIndex = mFabricsTable->FindDestinationIDCandidate(ByteSpan(destinationIdentifier), ByteSpan(initiatorRandom),
ipkListSpan, GetIPKListEntries());
VerifyOrExit(fabricIndex != Transport::kUndefinedFabricIndex, err = CHIP_ERROR_CERT_NOT_TRUSTED);
mFabricInfo = mFabricsTable->FindFabricWithIndex(fabricIndex);
VerifyOrExit(mFabricInfo != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
SuccessOrExit(err = tlvReader.Next());
VerifyOrExit(TLV::TagNumFromTag(tlvReader.GetTag()) == ++decodeTagIdSeq, err = CHIP_ERROR_INVALID_TLV_TAG);
SuccessOrExit(err = tlvReader.GetBytes(mRemotePubKey, static_cast<uint32_t>(mRemotePubKey.Length())));
SuccessOrExit(err = SendSigma2());
}
exit:
if (err == CHIP_ERROR_CERT_NOT_TRUSTED)
{
SendStatusReport(mExchangeCtxt, kProtocolCodeNoSharedRoot);
mState = kInitialized;
}
else if (err != CHIP_NO_ERROR)
{
SendStatusReport(mExchangeCtxt, kProtocolCodeInvalidParam);
mState = kInitialized;
}
return err;
}
CHIP_ERROR CASESession::SendSigma2Resume(const ByteSpan & initiatorRandom)
{
size_t data_len = EstimateTLVStructOverhead(kCASEResumptionIDSize + kTAGSize + sizeof(uint16_t), 7);
System::PacketBufferTLVWriter tlvWriter;
System::PacketBufferHandle msg_R2_resume;
TLV::TLVType outerContainerType = TLV::kTLVType_NotSpecified;
msg_R2_resume = System::PacketBufferHandle::New(data_len);
VerifyOrReturnError(!msg_R2_resume.IsNull(), CHIP_ERROR_NO_MEMORY);
tlvWriter.Init(std::move(msg_R2_resume));
// Generate a new resumption ID
ReturnErrorOnFailure(DRBG_get_bytes(mResumptionId, sizeof(mResumptionId)));
ReturnErrorOnFailure(tlvWriter.StartContainer(TLV::AnonymousTag, TLV::kTLVType_Structure, outerContainerType));
ReturnErrorOnFailure(tlvWriter.PutBytes(TLV::ContextTag(1), mResumptionId, kCASEResumptionIDSize));
chip::Platform::ScopedMemoryBuffer<uint8_t> sigma2ResumeMIC;
ReturnErrorCodeIf(!sigma2ResumeMIC.Alloc(kTAGSize), CHIP_ERROR_NO_MEMORY);
MutableByteSpan resumeMICSpan(sigma2ResumeMIC.Get(), kTAGSize);
ReturnErrorOnFailure(GenerateSigmaResumeMIC(initiatorRandom, ByteSpan(mResumptionId), ByteSpan(kKDFS2RKeyInfo),
ByteSpan(kResume2MIC_Nonce), resumeMICSpan));
ReturnErrorOnFailure(tlvWriter.Put(TLV::ContextTag(2), resumeMICSpan));
ReturnErrorOnFailure(tlvWriter.Put(TLV::ContextTag(3), GetLocalSessionId(), true));
// TODO: Add support for optional MRP parameters
ReturnErrorOnFailure(tlvWriter.EndContainer(outerContainerType));
ReturnErrorOnFailure(tlvWriter.Finalize(&msg_R2_resume));
mState = kSentSigma2Resume;
// Call delegate to send the msg to peer
ReturnErrorOnFailure(mExchangeCtxt->SendMessage(Protocols::SecureChannel::MsgType::CASE_Sigma2Resume, std::move(msg_R2_resume),
SendFlags(SendMessageFlags::kExpectResponse)));
ChipLogDetail(SecureChannel, "Sent Sigma2Resume msg");
return CHIP_NO_ERROR;
}
CHIP_ERROR CASESession::SendSigma2()
{
VerifyOrReturnError(mFabricInfo != nullptr, CHIP_ERROR_INCORRECT_STATE);
ByteSpan icaCert;
ReturnErrorOnFailure(mFabricInfo->GetICACert(icaCert));
ByteSpan nocCert;
ReturnErrorOnFailure(mFabricInfo->GetNOCCert(nocCert));
mTrustedRootId = mFabricInfo->GetTrustedRootId();
VerifyOrReturnError(!mTrustedRootId.empty(), CHIP_ERROR_INTERNAL);
// Fill in the random value
uint8_t msg_rand[kSigmaParamRandomNumberSize];
ReturnErrorOnFailure(DRBG_get_bytes(&msg_rand[0], sizeof(msg_rand)));
// Generate an ephemeral keypair
#ifdef ENABLE_HSM_CASE_EPHEMERAL_KEY
mEphemeralKey.SetKeyId(CASE_EPHEMERAL_KEY);
#endif
ReturnErrorOnFailure(mEphemeralKey.Initialize());
// Generate a Shared Secret
ReturnErrorOnFailure(mEphemeralKey.ECDH_derive_secret(mRemotePubKey, mSharedSecret));
uint8_t msg_salt[kIPKSize + kSigmaParamRandomNumberSize + kP256_PublicKey_Length + kSHA256_Hash_Length];
MutableByteSpan saltSpan(msg_salt);
ReturnErrorOnFailure(ConstructSaltSigma2(ByteSpan(msg_rand), mEphemeralKey.Pubkey(), ByteSpan(mIPK), saltSpan));
HKDF_sha_crypto mHKDF;
uint8_t sr2k[kAEADKeySize];
ReturnErrorOnFailure(mHKDF.HKDF_SHA256(mSharedSecret, mSharedSecret.Length(), saltSpan.data(), saltSpan.size(), kKDFSR2Info,
kKDFInfoLength, sr2k, kAEADKeySize));
// Construct Sigma2 TBS Data
size_t msg_r2_signed_len = EstimateTLVStructOverhead(nocCert.size() + icaCert.size() + kP256_PublicKey_Length * 2, 4);
chip::Platform::ScopedMemoryBuffer<uint8_t> msg_R2_Signed;
VerifyOrReturnError(msg_R2_Signed.Alloc(msg_r2_signed_len), CHIP_ERROR_NO_MEMORY);
ReturnErrorOnFailure(ConstructTBSData(nocCert, icaCert, ByteSpan(mEphemeralKey.Pubkey(), mEphemeralKey.Pubkey().Length()),
ByteSpan(mRemotePubKey, mRemotePubKey.Length()), msg_R2_Signed.Get(), msg_r2_signed_len));
// Generate a Signature
VerifyOrReturnError(mFabricInfo->GetOperationalKey() != nullptr, CHIP_ERROR_INCORRECT_STATE);
P256ECDSASignature tbsData2Signature;
ReturnErrorOnFailure(
mFabricInfo->GetOperationalKey()->ECDSA_sign_msg(msg_R2_Signed.Get(), msg_r2_signed_len, tbsData2Signature));
// Construct Sigma2 TBE Data
size_t msg_r2_signed_enc_len =
EstimateTLVStructOverhead(nocCert.size() + icaCert.size() + tbsData2Signature.Length() + kCASEResumptionIDSize, 4);
chip::Platform::ScopedMemoryBuffer<uint8_t> msg_R2_Encrypted;
VerifyOrReturnError(msg_R2_Encrypted.Alloc(msg_r2_signed_enc_len + kTAGSize), CHIP_ERROR_NO_MEMORY);
TLV::TLVWriter tlvWriter;
TLV::TLVType outerContainerType = TLV::kTLVType_NotSpecified;
tlvWriter.Init(msg_R2_Encrypted.Get(), msg_r2_signed_enc_len);
ReturnErrorOnFailure(tlvWriter.StartContainer(TLV::AnonymousTag, TLV::kTLVType_Structure, outerContainerType));
ReturnErrorOnFailure(tlvWriter.Put(TLV::ContextTag(kTag_TBEData_SenderNOC), nocCert));
if (!icaCert.empty())
{
ReturnErrorOnFailure(tlvWriter.Put(TLV::ContextTag(kTag_TBEData_SenderICAC), icaCert));
}
ReturnErrorOnFailure(tlvWriter.PutBytes(TLV::ContextTag(kTag_TBEData_Signature), tbsData2Signature,
static_cast<uint32_t>(tbsData2Signature.Length())));
// Generate a new resumption ID
ReturnErrorOnFailure(DRBG_get_bytes(mResumptionId, sizeof(mResumptionId)));
ReturnErrorOnFailure(tlvWriter.PutBytes(TLV::ContextTag(kTag_TBEData_ResumptionID), mResumptionId,
static_cast<uint32_t>(sizeof(mResumptionId))));
ReturnErrorOnFailure(tlvWriter.EndContainer(outerContainerType));
ReturnErrorOnFailure(tlvWriter.Finalize());
msg_r2_signed_enc_len = static_cast<size_t>(tlvWriter.GetLengthWritten());
// Generate the encrypted data blob
ReturnErrorOnFailure(AES_CCM_encrypt(msg_R2_Encrypted.Get(), msg_r2_signed_enc_len, nullptr, 0, sr2k, kAEADKeySize,
kTBEData2_Nonce, kTBEDataNonceLength, msg_R2_Encrypted.Get(),
msg_R2_Encrypted.Get() + msg_r2_signed_enc_len, kTAGSize));
// Construct Sigma2 Msg
size_t data_len = EstimateTLVStructOverhead(
kSigmaParamRandomNumberSize + sizeof(uint16_t) + kP256_PublicKey_Length + msg_r2_signed_enc_len + kTAGSize, 4);
System::PacketBufferHandle msg_R2 = System::PacketBufferHandle::New(data_len);
VerifyOrReturnError(!msg_R2.IsNull(), CHIP_ERROR_NO_MEMORY);
System::PacketBufferTLVWriter tlvWriterMsg2;
outerContainerType = TLV::kTLVType_NotSpecified;
tlvWriterMsg2.Init(std::move(msg_R2));
ReturnErrorOnFailure(tlvWriterMsg2.StartContainer(TLV::AnonymousTag, TLV::kTLVType_Structure, outerContainerType));
ReturnErrorOnFailure(tlvWriterMsg2.PutBytes(TLV::ContextTag(1), &msg_rand[0], sizeof(msg_rand)));
ReturnErrorOnFailure(tlvWriterMsg2.Put(TLV::ContextTag(2), GetLocalSessionId(), true));
ReturnErrorOnFailure(
tlvWriterMsg2.PutBytes(TLV::ContextTag(3), mEphemeralKey.Pubkey(), static_cast<uint32_t>(mEphemeralKey.Pubkey().Length())));
ReturnErrorOnFailure(tlvWriterMsg2.PutBytes(TLV::ContextTag(4), msg_R2_Encrypted.Get(),
static_cast<uint32_t>(msg_r2_signed_enc_len + kTAGSize)));
ReturnErrorOnFailure(tlvWriterMsg2.EndContainer(outerContainerType));
ReturnErrorOnFailure(tlvWriterMsg2.Finalize(&msg_R2));
ReturnErrorOnFailure(mCommissioningHash.AddData(ByteSpan{ msg_R2->Start(), msg_R2->DataLength() }));
mState = kSentSigma2;
// Call delegate to send the msg to peer
ReturnErrorOnFailure(mExchangeCtxt->SendMessage(Protocols::SecureChannel::MsgType::CASE_Sigma2, std::move(msg_R2),
SendFlags(SendMessageFlags::kExpectResponse)));
ChipLogDetail(SecureChannel, "Sent Sigma2 msg");
return CHIP_NO_ERROR;
}
CHIP_ERROR CASESession::HandleSigma2Resume(System::PacketBufferHandle && msg)
{
CHIP_ERROR err = CHIP_NO_ERROR;
System::PacketBufferTLVReader tlvReader;
TLV::TLVType containerType = TLV::kTLVType_Structure;
uint16_t responderSessionId;
uint32_t decodeTagIdSeq = 0;
ChipLogDetail(SecureChannel, "Received Sigma2Resume msg");
uint8_t sigma2ResumeMIC[kTAGSize];
tlvReader.Init(std::move(msg));
SuccessOrExit(err = tlvReader.Next(containerType, TLV::AnonymousTag));
SuccessOrExit(err = tlvReader.EnterContainer(containerType));
SuccessOrExit(err = tlvReader.Next());
VerifyOrExit(TLV::TagNumFromTag(tlvReader.GetTag()) == ++decodeTagIdSeq, err = CHIP_ERROR_INVALID_TLV_TAG);
SuccessOrExit(err = tlvReader.GetBytes(mResumptionId, kCASEResumptionIDSize));
SuccessOrExit(err = tlvReader.Next());
VerifyOrExit(TLV::TagNumFromTag(tlvReader.GetTag()) == ++decodeTagIdSeq, err = CHIP_ERROR_INVALID_TLV_TAG);
SuccessOrExit(err = tlvReader.GetBytes(sigma2ResumeMIC, kTAGSize));
SuccessOrExit(err = ValidateSigmaResumeMIC(ByteSpan(sigma2ResumeMIC), ByteSpan(mInitiatorRandom), ByteSpan(mResumptionId),
ByteSpan(kKDFS2RKeyInfo), ByteSpan(kResume2MIC_Nonce)));
SuccessOrExit(err = tlvReader.Next());
VerifyOrExit(TLV::TagNumFromTag(tlvReader.GetTag()) == ++decodeTagIdSeq, err = CHIP_ERROR_INVALID_TLV_TAG);
SuccessOrExit(err = tlvReader.Get(responderSessionId));
ChipLogDetail(SecureChannel, "Peer assigned session key ID %d", responderSessionId);
SetPeerSessionId(responderSessionId);
SendStatusReport(mExchangeCtxt, kProtocolCodeSuccess);
mPairingComplete = true;
// Forget our exchange, as no additional messages are expected from the peer
mExchangeCtxt = nullptr;
// Call delegate to indicate pairing completion
mDelegate->OnSessionEstablished();
exit:
if (err != CHIP_NO_ERROR)
{
SendStatusReport(mExchangeCtxt, kProtocolCodeInvalidParam);
}
return err;
}
CHIP_ERROR CASESession::HandleSigma2_and_SendSigma3(System::PacketBufferHandle && msg)
{
ReturnErrorOnFailure(HandleSigma2(std::move(msg)));
ReturnErrorOnFailure(SendSigma3());
return CHIP_NO_ERROR;
}
CHIP_ERROR CASESession::HandleSigma2(System::PacketBufferHandle && msg)
{
CHIP_ERROR err = CHIP_NO_ERROR;
System::PacketBufferTLVReader tlvReader;
TLV::TLVReader decryptedDataTlvReader;
TLV::TLVType containerType = TLV::kTLVType_Structure;
const uint8_t * buf = msg->Start();
size_t buflen = msg->DataLength();
uint8_t msg_salt[kIPKSize + kSigmaParamRandomNumberSize + kP256_PublicKey_Length + kSHA256_Hash_Length];
chip::Platform::ScopedMemoryBuffer<uint8_t> msg_R2_Encrypted;
size_t msg_r2_encrypted_len = 0;
size_t msg_r2_encrypted_len_with_tag = 0;
chip::Platform::ScopedMemoryBuffer<uint8_t> msg_R2_Signed;
size_t msg_r2_signed_len;
uint8_t sr2k[kAEADKeySize];
P256ECDSASignature tbsData2Signature;
P256PublicKey remoteCredential;
uint8_t responderRandom[kSigmaParamRandomNumberSize];
ByteSpan responderNOC;
ByteSpan responderICAC;
uint16_t responderSessionId;
uint32_t decodeTagIdSeq = 0;
VerifyOrExit(buf != nullptr, err = CHIP_ERROR_MESSAGE_INCOMPLETE);
ChipLogDetail(SecureChannel, "Received Sigma2 msg");
tlvReader.Init(std::move(msg));
SuccessOrExit(err = tlvReader.Next(containerType, TLV::AnonymousTag));
SuccessOrExit(err = tlvReader.EnterContainer(containerType));
// Retrieve Responder's Random value
SuccessOrExit(err = tlvReader.Next());
VerifyOrExit(TLV::TagNumFromTag(tlvReader.GetTag()) == ++decodeTagIdSeq, err = CHIP_ERROR_INVALID_TLV_TAG);
SuccessOrExit(err = tlvReader.GetBytes(responderRandom, sizeof(responderRandom)));
// Assign Session Key ID
SuccessOrExit(err = tlvReader.Next());
VerifyOrExit(TLV::TagNumFromTag(tlvReader.GetTag()) == ++decodeTagIdSeq, err = CHIP_ERROR_INVALID_TLV_TAG);
SuccessOrExit(err = tlvReader.Get(responderSessionId));
ChipLogDetail(SecureChannel, "Peer assigned session key ID %d", responderSessionId);
SetPeerSessionId(responderSessionId);
// Retrieve Responder's Ephemeral Pubkey
SuccessOrExit(err = tlvReader.Next());
VerifyOrExit(TLV::TagNumFromTag(tlvReader.GetTag()) == ++decodeTagIdSeq, err = CHIP_ERROR_INVALID_TLV_TAG);
SuccessOrExit(err = tlvReader.GetBytes(mRemotePubKey, static_cast<uint32_t>(mRemotePubKey.Length())));
// Generate a Shared Secret
SuccessOrExit(err = mEphemeralKey.ECDH_derive_secret(mRemotePubKey, mSharedSecret));
// Generate the S2K key
{
MutableByteSpan saltSpan(msg_salt);
err = ConstructSaltSigma2(ByteSpan(responderRandom), mRemotePubKey, ByteSpan(mIPK), saltSpan);
SuccessOrExit(err);
HKDF_sha_crypto mHKDF;
err = mHKDF.HKDF_SHA256(mSharedSecret, mSharedSecret.Length(), saltSpan.data(), saltSpan.size(), kKDFSR2Info,
kKDFInfoLength, sr2k, kAEADKeySize);
SuccessOrExit(err);
}
SuccessOrExit(err = mCommissioningHash.AddData(ByteSpan{ buf, buflen }));
// Generate decrypted data
SuccessOrExit(err = tlvReader.Next());
VerifyOrExit(TLV::TagNumFromTag(tlvReader.GetTag()) == ++decodeTagIdSeq, err = CHIP_ERROR_INVALID_TLV_TAG);
VerifyOrExit(msg_R2_Encrypted.Alloc(tlvReader.GetLength()), err = CHIP_ERROR_NO_MEMORY);
msg_r2_encrypted_len_with_tag = tlvReader.GetLength();
VerifyOrExit(msg_r2_encrypted_len_with_tag > kTAGSize, err = CHIP_ERROR_INVALID_TLV_ELEMENT);
SuccessOrExit(err = tlvReader.GetBytes(msg_R2_Encrypted.Get(), static_cast<uint32_t>(msg_r2_encrypted_len_with_tag)));
msg_r2_encrypted_len = msg_r2_encrypted_len_with_tag - kTAGSize;
SuccessOrExit(err = AES_CCM_decrypt(msg_R2_Encrypted.Get(), msg_r2_encrypted_len, nullptr, 0,
msg_R2_Encrypted.Get() + msg_r2_encrypted_len, kTAGSize, sr2k, kAEADKeySize,
kTBEData2_Nonce, kTBEDataNonceLength, msg_R2_Encrypted.Get()));
decryptedDataTlvReader.Init(msg_R2_Encrypted.Get(), msg_r2_encrypted_len);
containerType = TLV::kTLVType_Structure;
SuccessOrExit(err = decryptedDataTlvReader.Next(containerType, TLV::AnonymousTag));
SuccessOrExit(err = decryptedDataTlvReader.EnterContainer(containerType));
SuccessOrExit(err = decryptedDataTlvReader.Next(TLV::kTLVType_ByteString, TLV::ContextTag(kTag_TBEData_SenderNOC)));
SuccessOrExit(err = decryptedDataTlvReader.Get(responderNOC));
SuccessOrExit(err = decryptedDataTlvReader.Next());
if (TLV::TagNumFromTag(decryptedDataTlvReader.GetTag()) == kTag_TBEData_SenderICAC)
{
VerifyOrExit(decryptedDataTlvReader.GetType() == TLV::kTLVType_ByteString, err = CHIP_ERROR_WRONG_TLV_TYPE);
SuccessOrExit(err = decryptedDataTlvReader.Get(responderICAC));
SuccessOrExit(err = decryptedDataTlvReader.Next(TLV::kTLVType_ByteString, TLV::ContextTag(kTag_TBEData_Signature)));
}
// Validate responder identity located in msg_r2_encrypted
// Constructing responder identity
SuccessOrExit(err = Validate_and_RetrieveResponderID(responderNOC, responderICAC, remoteCredential));
// Construct msg_R2_Signed and validate the signature in msg_r2_encrypted
msg_r2_signed_len =
EstimateTLVStructOverhead(sizeof(uint16_t) + responderNOC.size() + responderICAC.size() + kP256_PublicKey_Length * 2, 4);
VerifyOrExit(msg_R2_Signed.Alloc(msg_r2_signed_len), err = CHIP_ERROR_NO_MEMORY);
SuccessOrExit(err = ConstructTBSData(responderNOC, responderICAC, ByteSpan(mRemotePubKey, mRemotePubKey.Length()),
ByteSpan(mEphemeralKey.Pubkey(), mEphemeralKey.Pubkey().Length()), msg_R2_Signed.Get(),
msg_r2_signed_len));
VerifyOrExit(TLV::TagNumFromTag(decryptedDataTlvReader.GetTag()) == kTag_TBEData_Signature, err = CHIP_ERROR_INVALID_TLV_TAG);
VerifyOrExit(tbsData2Signature.Capacity() >= decryptedDataTlvReader.GetLength(), err = CHIP_ERROR_INVALID_TLV_ELEMENT);
tbsData2Signature.SetLength(decryptedDataTlvReader.GetLength());
SuccessOrExit(err = decryptedDataTlvReader.GetBytes(tbsData2Signature, tbsData2Signature.Length()));
// Validate signature
SuccessOrExit(err = remoteCredential.ECDSA_validate_msg_signature(msg_R2_Signed.Get(), msg_r2_signed_len, tbsData2Signature));
// Retrieve session resumption ID
SuccessOrExit(err = decryptedDataTlvReader.Next(TLV::kTLVType_ByteString, TLV::ContextTag(kTag_TBEData_ResumptionID)));
SuccessOrExit(err = decryptedDataTlvReader.GetBytes(mResumptionId, static_cast<uint32_t>(sizeof(mResumptionId))));
exit:
if (err != CHIP_NO_ERROR)
{
SendStatusReport(mExchangeCtxt, kProtocolCodeInvalidParam);
}
return err;
}
CHIP_ERROR CASESession::SendSigma3()
{
CHIP_ERROR err = CHIP_NO_ERROR;
MutableByteSpan messageDigestSpan(mMessageDigest);
System::PacketBufferHandle msg_R3;
size_t data_len;
chip::Platform::ScopedMemoryBuffer<uint8_t> msg_R3_Encrypted;
size_t msg_r3_encrypted_len;
uint8_t msg_salt[kIPKSize + kSHA256_Hash_Length];
uint8_t sr3k[kAEADKeySize];
chip::Platform::ScopedMemoryBuffer<uint8_t> msg_R3_Signed;
size_t msg_r3_signed_len;
P256ECDSASignature tbsData3Signature;
ChipLogDetail(SecureChannel, "Sending Sigma3");
ByteSpan icaCert;
ByteSpan nocCert;
VerifyOrExit(mFabricInfo != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
SuccessOrExit(err = mFabricInfo->GetICACert(icaCert));
SuccessOrExit(err = mFabricInfo->GetNOCCert(nocCert));
mTrustedRootId = mFabricInfo->GetTrustedRootId();
VerifyOrExit(!mTrustedRootId.empty(), err = CHIP_ERROR_INTERNAL);
// Prepare Sigma3 TBS Data Blob
msg_r3_signed_len = EstimateTLVStructOverhead(icaCert.size() + nocCert.size() + kP256_PublicKey_Length * 2, 4);
VerifyOrExit(msg_R3_Signed.Alloc(msg_r3_signed_len), err = CHIP_ERROR_NO_MEMORY);
SuccessOrExit(err = ConstructTBSData(nocCert, icaCert, ByteSpan(mEphemeralKey.Pubkey(), mEphemeralKey.Pubkey().Length()),
ByteSpan(mRemotePubKey, mRemotePubKey.Length()), msg_R3_Signed.Get(), msg_r3_signed_len));
// Generate a signature
VerifyOrExit(mFabricInfo->GetOperationalKey() != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = mFabricInfo->GetOperationalKey()->ECDSA_sign_msg(msg_R3_Signed.Get(), msg_r3_signed_len, tbsData3Signature);
SuccessOrExit(err);
// Prepare Sigma3 TBE Data Blob
msg_r3_encrypted_len = EstimateTLVStructOverhead(nocCert.size() + icaCert.size() + tbsData3Signature.Length(), 3);
VerifyOrExit(msg_R3_Encrypted.Alloc(msg_r3_encrypted_len + kTAGSize), err = CHIP_ERROR_NO_MEMORY);
{
TLV::TLVWriter tlvWriter;
TLV::TLVType outerContainerType = TLV::kTLVType_NotSpecified;
tlvWriter.Init(msg_R3_Encrypted.Get(), msg_r3_encrypted_len);
SuccessOrExit(err = tlvWriter.StartContainer(TLV::AnonymousTag, TLV::kTLVType_Structure, outerContainerType));
SuccessOrExit(err = tlvWriter.Put(TLV::ContextTag(kTag_TBEData_SenderNOC), nocCert));
if (!icaCert.empty())
{
SuccessOrExit(err = tlvWriter.Put(TLV::ContextTag(kTag_TBEData_SenderICAC), icaCert));
}
SuccessOrExit(err = tlvWriter.PutBytes(TLV::ContextTag(kTag_TBEData_Signature), tbsData3Signature,
static_cast<uint32_t>(tbsData3Signature.Length())));
SuccessOrExit(err = tlvWriter.EndContainer(outerContainerType));
SuccessOrExit(err = tlvWriter.Finalize());
msg_r3_encrypted_len = static_cast<size_t>(tlvWriter.GetLengthWritten());
}
// Generate S3K key
{
MutableByteSpan saltSpan(msg_salt);
err = ConstructSaltSigma3(ByteSpan(mIPK), saltSpan);
SuccessOrExit(err);
HKDF_sha_crypto mHKDF;
err = mHKDF.HKDF_SHA256(mSharedSecret, mSharedSecret.Length(), saltSpan.data(), saltSpan.size(), kKDFSR3Info,
kKDFInfoLength, sr3k, kAEADKeySize);
SuccessOrExit(err);
}
// Generated Encrypted data blob
err = AES_CCM_encrypt(msg_R3_Encrypted.Get(), msg_r3_encrypted_len, nullptr, 0, sr3k, kAEADKeySize, kTBEData3_Nonce,
kTBEDataNonceLength, msg_R3_Encrypted.Get(), msg_R3_Encrypted.Get() + msg_r3_encrypted_len, kTAGSize);
SuccessOrExit(err);
// Generate Sigma3 Msg
data_len = EstimateTLVStructOverhead(kTAGSize + msg_r3_encrypted_len, 1);
msg_R3 = System::PacketBufferHandle::New(data_len);
VerifyOrExit(!msg_R3.IsNull(), err = CHIP_ERROR_NO_MEMORY);
{
System::PacketBufferTLVWriter tlvWriter;
TLV::TLVType outerContainerType = TLV::kTLVType_NotSpecified;
tlvWriter.Init(std::move(msg_R3));
err = tlvWriter.StartContainer(TLV::AnonymousTag, TLV::kTLVType_Structure, outerContainerType);
SuccessOrExit(err);
err =
tlvWriter.PutBytes(TLV::ContextTag(1), msg_R3_Encrypted.Get(), static_cast<uint32_t>(msg_r3_encrypted_len + kTAGSize));
SuccessOrExit(err);
err = tlvWriter.EndContainer(outerContainerType);
SuccessOrExit(err);
err = tlvWriter.Finalize(&msg_R3);
SuccessOrExit(err);
}
err = mCommissioningHash.AddData(ByteSpan{ msg_R3->Start(), msg_R3->DataLength() });
SuccessOrExit(err);
mState = kSentSigma3;
// Call delegate to send the Msg3 to peer
err = mExchangeCtxt->SendMessage(Protocols::SecureChannel::MsgType::CASE_Sigma3, std::move(msg_R3));
SuccessOrExit(err);
ChipLogDetail(SecureChannel, "Sent Sigma3 msg");
err = mCommissioningHash.Finish(messageDigestSpan);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
SendStatusReport(mExchangeCtxt, kProtocolCodeInvalidParam);
mState = kInitialized;
}
return err;
}
CHIP_ERROR CASESession::HandleSigma3(System::PacketBufferHandle && msg)
{
CHIP_ERROR err = CHIP_NO_ERROR;
MutableByteSpan messageDigestSpan(mMessageDigest);
System::PacketBufferTLVReader tlvReader;
TLV::TLVReader decryptedDataTlvReader;