forked from project-chip/connectedhomeip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFabricTable.cpp
2180 lines (1825 loc) · 83.2 KB
/
FabricTable.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-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://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.
*/
/**
* @brief Defines a table of fabrics that have provisioned the device.
*/
#include "FabricTable.h"
#include <lib/core/CHIPEncoding.h>
#include <lib/support/BufferWriter.h>
#include <lib/support/CHIPMem.h>
#include <lib/support/CHIPMemString.h>
#include <lib/support/DefaultStorageKeyAllocator.h>
#include <lib/support/SafeInt.h>
#include <lib/support/ScopedBuffer.h>
#include <platform/LockTracker.h>
#include <tracing/macros.h>
namespace chip {
using namespace Credentials;
using namespace Crypto;
using CertChainElement = chip::Credentials::OperationalCertificateStore::CertChainElement;
namespace {
static_assert(kMinValidFabricIndex <= CHIP_CONFIG_MAX_FABRICS, "Must support some fabrics.");
static_assert(CHIP_CONFIG_MAX_FABRICS <= kMaxValidFabricIndex, "Max fabric count out of range.");
// Tags for our metadata storage.
constexpr TLV::Tag kVendorIdTag = TLV::ContextTag(0);
constexpr TLV::Tag kFabricLabelTag = TLV::ContextTag(1);
// Tags for our index list storage.
constexpr TLV::Tag kNextAvailableFabricIndexTag = TLV::ContextTag(0);
constexpr TLV::Tag kFabricIndicesTag = TLV::ContextTag(1);
// Tags for commit marker storage
constexpr TLV::Tag kMarkerFabricIndexTag = TLV::ContextTag(0);
constexpr TLV::Tag kMarkerIsAdditionTag = TLV::ContextTag(1);
constexpr size_t CommitMarkerContextTLVMaxSize()
{
// Add 2x uncommitted uint64_t to leave space for backwards/forwards
// versioning for this critical feature that runs at boot.
return TLV::EstimateStructOverhead(sizeof(FabricIndex), sizeof(bool), sizeof(uint64_t), sizeof(uint64_t));
}
constexpr size_t IndexInfoTLVMaxSize()
{
// We have a single next-available index and an array of anonymous-tagged
// fabric indices.
//
// The max size of the list is (1 byte control + bytes for actual value)
// times max number of list items, plus one byte for the list terminator.
return TLV::EstimateStructOverhead(sizeof(FabricIndex), CHIP_CONFIG_MAX_FABRICS * (1 + sizeof(FabricIndex)) + 1);
}
CHIP_ERROR AddNewFabricForTestInternal(FabricTable & fabricTable, bool leavePending, const ByteSpan & rootCert,
const ByteSpan & icacCert, const ByteSpan & nocCert, const ByteSpan & opKeySpan,
FabricIndex * outFabricIndex)
{
VerifyOrReturnError(outFabricIndex != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
CHIP_ERROR err = CHIP_ERROR_INTERNAL;
Crypto::P256Keypair injectedOpKey;
Crypto::P256SerializedKeypair injectedOpKeysSerialized;
Crypto::P256Keypair * opKey = nullptr;
if (!opKeySpan.empty())
{
VerifyOrReturnError(opKeySpan.size() == injectedOpKeysSerialized.Capacity(), CHIP_ERROR_INVALID_ARGUMENT);
memcpy(injectedOpKeysSerialized.Bytes(), opKeySpan.data(), opKeySpan.size());
SuccessOrExit(err = injectedOpKeysSerialized.SetLength(opKeySpan.size()));
SuccessOrExit(err = injectedOpKey.Deserialize(injectedOpKeysSerialized));
opKey = &injectedOpKey;
}
SuccessOrExit(err = fabricTable.AddNewPendingTrustedRootCert(rootCert));
SuccessOrExit(err =
fabricTable.AddNewPendingFabricWithProvidedOpKey(nocCert, icacCert, VendorId::TestVendor1, opKey,
/*isExistingOpKeyExternallyOwned =*/false, outFabricIndex));
if (!leavePending)
{
SuccessOrExit(err = fabricTable.CommitPendingFabricData());
}
exit:
if (err != CHIP_NO_ERROR)
{
fabricTable.RevertPendingFabricData();
}
return err;
}
} // anonymous namespace
CHIP_ERROR FabricInfo::Init(const FabricInfo::InitParams & initParams)
{
ReturnErrorOnFailure(initParams.AreValid());
Reset();
mNodeId = initParams.nodeId;
mFabricId = initParams.fabricId;
mFabricIndex = initParams.fabricIndex;
mCompressedFabricId = initParams.compressedFabricId;
mRootPublicKey = initParams.rootPublicKey;
mVendorId = static_cast<VendorId>(initParams.vendorId);
mShouldAdvertiseIdentity = initParams.advertiseIdentity;
// Deal with externally injected keys
if (initParams.operationalKeypair != nullptr)
{
if (initParams.hasExternallyOwnedKeypair)
{
ReturnErrorOnFailure(SetExternallyOwnedOperationalKeypair(initParams.operationalKeypair));
}
else
{
ReturnErrorOnFailure(SetOperationalKeypair(initParams.operationalKeypair));
}
}
return CHIP_NO_ERROR;
}
void FabricInfo::operator=(FabricInfo && other)
{
Reset();
mNodeId = other.mNodeId;
mFabricId = other.mFabricId;
mFabricIndex = other.mFabricIndex;
mCompressedFabricId = other.mCompressedFabricId;
mRootPublicKey = other.mRootPublicKey;
mVendorId = other.mVendorId;
mShouldAdvertiseIdentity = other.mShouldAdvertiseIdentity;
SetFabricLabel(other.GetFabricLabel());
// Transfer ownership of operational keypair (if it was nullptr, it stays that way).
mOperationalKey = other.mOperationalKey;
mHasExternallyOwnedOperationalKey = other.mHasExternallyOwnedOperationalKey;
other.mOperationalKey = nullptr;
other.mHasExternallyOwnedOperationalKey = false;
other.Reset();
}
CHIP_ERROR FabricInfo::CommitToStorage(PersistentStorageDelegate * storage) const
{
{
uint8_t buf[MetadataTLVMaxSize()];
TLV::TLVWriter writer;
writer.Init(buf);
TLV::TLVType outerType;
ReturnErrorOnFailure(writer.StartContainer(TLV::AnonymousTag(), TLV::kTLVType_Structure, outerType));
ReturnErrorOnFailure(writer.Put(kVendorIdTag, mVendorId));
ReturnErrorOnFailure(writer.PutString(kFabricLabelTag, CharSpan::fromCharString(mFabricLabel)));
ReturnErrorOnFailure(writer.EndContainer(outerType));
const auto metadataLength = writer.GetLengthWritten();
VerifyOrReturnError(CanCastTo<uint16_t>(metadataLength), CHIP_ERROR_BUFFER_TOO_SMALL);
ReturnErrorOnFailure(storage->SyncSetKeyValue(DefaultStorageKeyAllocator::FabricMetadata(mFabricIndex).KeyName(), buf,
static_cast<uint16_t>(metadataLength)));
}
// NOTE: Operational Key is never saved to storage here. See OperationalKeystore interface for how it is accessed
return CHIP_NO_ERROR;
}
CHIP_ERROR FabricInfo::LoadFromStorage(PersistentStorageDelegate * storage, FabricIndex newFabricIndex, const ByteSpan & rcac,
const ByteSpan & noc)
{
mFabricIndex = newFabricIndex;
// Regenerate operational metadata from NOC/RCAC
{
ReturnErrorOnFailure(ExtractNodeIdFabricIdFromOpCert(noc, &mNodeId, &mFabricId));
P256PublicKeySpan rootPubKeySpan;
ReturnErrorOnFailure(ExtractPublicKeyFromChipCert(rcac, rootPubKeySpan));
mRootPublicKey = rootPubKeySpan;
uint8_t compressedFabricIdBuf[sizeof(uint64_t)];
MutableByteSpan compressedFabricIdSpan(compressedFabricIdBuf);
ReturnErrorOnFailure(GenerateCompressedFabricId(mRootPublicKey, mFabricId, compressedFabricIdSpan));
// Decode compressed fabric ID accounting for endianness, as GenerateCompressedFabricId()
// returns a binary buffer and is agnostic of usage of the output as an integer type.
mCompressedFabricId = Encoding::BigEndian::Get64(compressedFabricIdBuf);
}
// Load other storable metadata (label, vendorId, etc)
{
uint8_t buf[MetadataTLVMaxSize()];
uint16_t size = sizeof(buf);
ReturnErrorOnFailure(
storage->SyncGetKeyValue(DefaultStorageKeyAllocator::FabricMetadata(mFabricIndex).KeyName(), buf, size));
TLV::ContiguousBufferTLVReader reader;
reader.Init(buf, size);
ReturnErrorOnFailure(reader.Next(TLV::kTLVType_Structure, TLV::AnonymousTag()));
TLV::TLVType containerType;
ReturnErrorOnFailure(reader.EnterContainer(containerType));
ReturnErrorOnFailure(reader.Next(kVendorIdTag));
ReturnErrorOnFailure(reader.Get(mVendorId));
ReturnErrorOnFailure(reader.Next(kFabricLabelTag));
CharSpan label;
ReturnErrorOnFailure(reader.Get(label));
VerifyOrReturnError(label.size() <= kFabricLabelMaxLengthInBytes, CHIP_ERROR_BUFFER_TOO_SMALL);
Platform::CopyString(mFabricLabel, label);
ReturnErrorOnFailure(reader.ExitContainer(containerType));
ReturnErrorOnFailure(reader.VerifyEndOfContainer());
}
// NOTE: Operational Key is never loaded here. See OperationalKeystore interface for how it is accessed
return CHIP_NO_ERROR;
}
CHIP_ERROR FabricInfo::SetFabricLabel(const CharSpan & fabricLabel)
{
Platform::CopyString(mFabricLabel, fabricLabel);
return CHIP_NO_ERROR;
}
CHIP_ERROR FabricTable::DeleteMetadataFromStorage(FabricIndex fabricIndex)
{
VerifyOrReturnError(IsValidFabricIndex(fabricIndex), CHIP_ERROR_INVALID_FABRIC_INDEX);
VerifyOrReturnError(mStorage != nullptr, CHIP_ERROR_INCORRECT_STATE);
CHIP_ERROR deleteErr = mStorage->SyncDeleteKeyValue(DefaultStorageKeyAllocator::FabricMetadata(fabricIndex).KeyName());
if (deleteErr != CHIP_NO_ERROR)
{
if (deleteErr == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND)
{
ChipLogError(FabricProvisioning, "Warning: metadata not found during delete of fabric 0x%x",
static_cast<unsigned>(fabricIndex));
}
else
{
ChipLogError(FabricProvisioning, "Error deleting metadata for fabric fabric 0x%x: %" CHIP_ERROR_FORMAT,
static_cast<unsigned>(fabricIndex), deleteErr.Format());
}
}
return deleteErr;
}
CHIP_ERROR FabricInfo::SetOperationalKeypair(const P256Keypair * keyPair)
{
VerifyOrReturnError(keyPair != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
P256SerializedKeypair serialized;
ReturnErrorOnFailure(keyPair->Serialize(serialized));
if (mHasExternallyOwnedOperationalKey)
{
// Drop it, so we will allocate an internally owned one.
mOperationalKey = nullptr;
mHasExternallyOwnedOperationalKey = false;
}
if (mOperationalKey == nullptr)
{
mOperationalKey = chip::Platform::New<P256Keypair>();
}
VerifyOrReturnError(mOperationalKey != nullptr, CHIP_ERROR_NO_MEMORY);
return mOperationalKey->Deserialize(serialized);
}
CHIP_ERROR FabricInfo::SetExternallyOwnedOperationalKeypair(P256Keypair * keyPair)
{
VerifyOrReturnError(keyPair != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
if (!mHasExternallyOwnedOperationalKey && mOperationalKey != nullptr)
{
chip::Platform::Delete(mOperationalKey);
mOperationalKey = nullptr;
}
mHasExternallyOwnedOperationalKey = true;
mOperationalKey = keyPair;
return CHIP_NO_ERROR;
}
CHIP_ERROR FabricTable::ValidateIncomingNOCChain(const ByteSpan & noc, const ByteSpan & icac, const ByteSpan & rcac,
FabricId existingFabricId, Credentials::CertificateValidityPolicy * policy,
CompressedFabricId & outCompressedFabricId, FabricId & outFabricId,
NodeId & outNodeId, Crypto::P256PublicKey & outNocPubkey,
Crypto::P256PublicKey & outRootPubkey)
{
MATTER_TRACE_SCOPE("ValidateIncomingNOCChain", "Fabric");
Credentials::ValidationContext validContext;
// Note that we do NOT set a time in the validation context. This will
// cause the certificate chain NotBefore / NotAfter time validation logic
// to report CertificateValidityResult::kTimeUnknown.
//
// The default CHIPCert policy passes NotBefore / NotAfter validation for
// this case where time is unknown. If an override policy is passed, it
// will be up to the passed policy to decide how to handle this.
//
// In the FabricTable::AddNewFabric and FabricTable::UpdateFabric calls,
// the passed policy always passes for all questions of time validity. The
// rationale is that installed certificates should be valid at the time of
// installation by definition. If they are not and the commissionee and
// commissioner disagree enough on current time, CASE will fail and our
// fail-safe timer will expire.
//
// This then is ultimately how we validate that NotBefore / NotAfter in
// newly installed certificates is workable.
validContext.Reset();
validContext.mRequiredKeyUsages.Set(KeyUsageFlags::kDigitalSignature);
validContext.mRequiredKeyPurposes.Set(KeyPurposeFlags::kServerAuth);
validContext.mValidityPolicy = policy;
ChipLogProgress(FabricProvisioning, "Validating NOC chain");
CHIP_ERROR err = FabricTable::VerifyCredentials(noc, icac, rcac, validContext, outCompressedFabricId, outFabricId, outNodeId,
outNocPubkey, &outRootPubkey);
if (err != CHIP_NO_ERROR && err != CHIP_ERROR_WRONG_NODE_ID)
{
err = CHIP_ERROR_UNSUPPORTED_CERT_FORMAT;
}
if (err != CHIP_NO_ERROR)
{
ChipLogError(FabricProvisioning, "Failed NOC chain validation: %" CHIP_ERROR_FORMAT, err.Format());
}
ReturnErrorOnFailure(err);
// Validate fabric ID match for cases like UpdateNOC.
if (existingFabricId != kUndefinedFabricId)
{
VerifyOrReturnError(existingFabricId == outFabricId, CHIP_ERROR_UNSUPPORTED_CERT_FORMAT);
}
ChipLogProgress(FabricProvisioning, "NOC chain validation successful");
return CHIP_NO_ERROR;
}
CHIP_ERROR FabricInfo::SignWithOpKeypair(ByteSpan message, P256ECDSASignature & outSignature) const
{
MATTER_TRACE_SCOPE("SignWithOpKeypair", "Fabric");
VerifyOrReturnError(mOperationalKey != nullptr, CHIP_ERROR_KEY_NOT_FOUND);
return mOperationalKey->ECDSA_sign_msg(message.data(), message.size(), outSignature);
}
CHIP_ERROR FabricInfo::FetchRootPubkey(Crypto::P256PublicKey & outPublicKey) const
{
MATTER_TRACE_SCOPE("FetchRootPubKey", "Fabric");
VerifyOrReturnError(IsInitialized(), CHIP_ERROR_KEY_NOT_FOUND);
outPublicKey = mRootPublicKey;
return CHIP_NO_ERROR;
}
CHIP_ERROR FabricTable::VerifyCredentials(FabricIndex fabricIndex, const ByteSpan & noc, const ByteSpan & icac,
ValidationContext & context, CompressedFabricId & outCompressedFabricId,
FabricId & outFabricId, NodeId & outNodeId, Crypto::P256PublicKey & outNocPubkey,
Crypto::P256PublicKey * outRootPublicKey) const
{
MATTER_TRACE_SCOPE("VerifyCredentials", "Fabric");
assertChipStackLockedByCurrentThread();
uint8_t rootCertBuf[kMaxCHIPCertLength];
MutableByteSpan rootCertSpan{ rootCertBuf };
ReturnErrorOnFailure(FetchRootCert(fabricIndex, rootCertSpan));
return VerifyCredentials(noc, icac, rootCertSpan, context, outCompressedFabricId, outFabricId, outNodeId, outNocPubkey,
outRootPublicKey);
}
CHIP_ERROR FabricTable::VerifyCredentials(const ByteSpan & noc, const ByteSpan & icac, const ByteSpan & rcac,
ValidationContext & context, CompressedFabricId & outCompressedFabricId,
FabricId & outFabricId, NodeId & outNodeId, Crypto::P256PublicKey & outNocPubkey,
Crypto::P256PublicKey * outRootPublicKey)
{
// TODO - Optimize credentials verification logic
// The certificate chain construction and verification is a compute and memory intensive operation.
// It can be optimized by not loading certificate (i.e. rcac) that's local and implicitly trusted.
// The FindValidCert() algorithm will need updates to achieve this refactor.
constexpr uint8_t kMaxNumCertsInOpCreds = 3;
ChipCertificateSet certificates;
ReturnErrorOnFailure(certificates.Init(kMaxNumCertsInOpCreds));
ReturnErrorOnFailure(certificates.LoadCert(rcac, BitFlags<CertDecodeFlags>(CertDecodeFlags::kIsTrustAnchor)));
if (!icac.empty())
{
ReturnErrorOnFailure(certificates.LoadCert(icac, BitFlags<CertDecodeFlags>(CertDecodeFlags::kGenerateTBSHash)));
}
ReturnErrorOnFailure(certificates.LoadCert(noc, BitFlags<CertDecodeFlags>(CertDecodeFlags::kGenerateTBSHash)));
const ChipDN & nocSubjectDN = certificates.GetLastCert()[0].mSubjectDN;
const CertificateKeyId & nocSubjectKeyId = certificates.GetLastCert()[0].mSubjectKeyId;
const ChipCertificateData * resultCert = nullptr;
// FindValidCert() checks the certificate set constructed by loading noc, icac and rcac.
// It confirms that the certs link correctly (noc -> icac -> rcac), and have been correctly signed.
ReturnErrorOnFailure(certificates.FindValidCert(nocSubjectDN, nocSubjectKeyId, context, &resultCert));
ReturnErrorOnFailure(ExtractNodeIdFabricIdFromOpCert(certificates.GetLastCert()[0], &outNodeId, &outFabricId));
CHIP_ERROR err;
FabricId icacFabricId = kUndefinedFabricId;
if (!icac.empty())
{
err = ExtractFabricIdFromCert(certificates.GetCertSet()[1], &icacFabricId);
if (err == CHIP_NO_ERROR)
{
ReturnErrorCodeIf(icacFabricId != outFabricId, CHIP_ERROR_FABRIC_MISMATCH_ON_ICA);
}
// FabricId is optional field in ICAC and "not found" code is not treated as error.
else if (err != CHIP_ERROR_NOT_FOUND)
{
return err;
}
}
FabricId rcacFabricId = kUndefinedFabricId;
err = ExtractFabricIdFromCert(certificates.GetCertSet()[0], &rcacFabricId);
if (err == CHIP_NO_ERROR)
{
ReturnErrorCodeIf(rcacFabricId != outFabricId, CHIP_ERROR_WRONG_CERT_DN);
}
// FabricId is optional field in RCAC and "not found" code is not treated as error.
else if (err != CHIP_ERROR_NOT_FOUND)
{
return err;
}
// Extract compressed fabric ID and root public key
{
uint8_t compressedFabricIdBuf[sizeof(uint64_t)];
MutableByteSpan compressedFabricIdSpan(compressedFabricIdBuf);
P256PublicKey rootPubkey(certificates.GetCertSet()[0].mPublicKey);
ReturnErrorOnFailure(GenerateCompressedFabricId(rootPubkey, outFabricId, compressedFabricIdSpan));
// Decode compressed fabric ID accounting for endianness, as GenerateCompressedFabricId()
// returns a binary buffer and is agnostic of usage of the output as an integer type.
outCompressedFabricId = Encoding::BigEndian::Get64(compressedFabricIdBuf);
if (outRootPublicKey != nullptr)
{
*outRootPublicKey = rootPubkey;
}
}
outNocPubkey = certificates.GetLastCert()->mPublicKey;
return CHIP_NO_ERROR;
}
const FabricInfo * FabricTable::FindFabric(const Crypto::P256PublicKey & rootPubKey, FabricId fabricId) const
{
return FindFabricCommon(rootPubKey, fabricId);
}
const FabricInfo * FabricTable::FindIdentity(const Crypto::P256PublicKey & rootPubKey, FabricId fabricId, NodeId nodeId) const
{
return FindFabricCommon(rootPubKey, fabricId, nodeId);
}
const FabricInfo * FabricTable::FindFabricCommon(const Crypto::P256PublicKey & rootPubKey, FabricId fabricId, NodeId nodeId) const
{
P256PublicKey candidatePubKey;
// Try to match pending fabric first if available
if (HasPendingFabricUpdate())
{
bool pubKeyAvailable = (mPendingFabric.FetchRootPubkey(candidatePubKey) == CHIP_NO_ERROR);
auto matchingNodeId = (nodeId == kUndefinedNodeId) ? mPendingFabric.GetNodeId() : nodeId;
if (pubKeyAvailable && rootPubKey.Matches(candidatePubKey) && fabricId == mPendingFabric.GetFabricId() &&
matchingNodeId == mPendingFabric.GetNodeId())
{
return &mPendingFabric;
}
}
for (auto & fabric : mStates)
{
auto matchingNodeId = (nodeId == kUndefinedNodeId) ? fabric.GetNodeId() : nodeId;
if (!fabric.IsInitialized())
{
continue;
}
if (fabric.FetchRootPubkey(candidatePubKey) != CHIP_NO_ERROR)
{
continue;
}
if (rootPubKey.Matches(candidatePubKey) && fabricId == fabric.GetFabricId() && matchingNodeId == fabric.GetNodeId())
{
return &fabric;
}
}
return nullptr;
}
FabricInfo * FabricTable::GetMutableFabricByIndex(FabricIndex fabricIndex)
{
// Try to match pending fabric first if available
if (HasPendingFabricUpdate() && (mPendingFabric.GetFabricIndex() == fabricIndex))
{
return &mPendingFabric;
}
for (auto & fabric : mStates)
{
if (!fabric.IsInitialized())
{
continue;
}
if (fabric.GetFabricIndex() == fabricIndex)
{
return &fabric;
}
}
return nullptr;
}
const FabricInfo * FabricTable::FindFabricWithIndex(FabricIndex fabricIndex) const
{
if (fabricIndex == kUndefinedFabricIndex)
{
return nullptr;
}
// Try to match pending fabric first if available
if (HasPendingFabricUpdate() && (mPendingFabric.GetFabricIndex() == fabricIndex))
{
return &mPendingFabric;
}
for (const auto & fabric : mStates)
{
if (!fabric.IsInitialized())
{
continue;
}
if (fabric.GetFabricIndex() == fabricIndex)
{
return &fabric;
}
}
return nullptr;
}
const FabricInfo * FabricTable::FindFabricWithCompressedId(CompressedFabricId compressedFabricId) const
{
// Try to match pending fabric first if available
if (HasPendingFabricUpdate() && (mPendingFabric.GetCompressedFabricId() == compressedFabricId))
{
return &mPendingFabric;
}
for (auto & fabric : mStates)
{
if (!fabric.IsInitialized())
{
continue;
}
if (compressedFabricId == fabric.GetPeerId().GetCompressedFabricId())
{
return &fabric;
}
}
return nullptr;
}
CHIP_ERROR FabricTable::FetchRootCert(FabricIndex fabricIndex, MutableByteSpan & outCert) const
{
MATTER_TRACE_SCOPE("FetchRootCert", "Fabric");
VerifyOrReturnError(mOpCertStore != nullptr, CHIP_ERROR_INCORRECT_STATE);
return mOpCertStore->GetCertificate(fabricIndex, CertChainElement::kRcac, outCert);
}
CHIP_ERROR FabricTable::FetchPendingNonFabricAssociatedRootCert(MutableByteSpan & outCert) const
{
MATTER_TRACE_SCOPE("FetchPendingNonFabricAssociatedRootCert", "Fabric");
VerifyOrReturnError(mOpCertStore != nullptr, CHIP_ERROR_INCORRECT_STATE);
if (!mStateFlags.Has(StateFlags::kIsTrustedRootPending))
{
return CHIP_ERROR_NOT_FOUND;
}
if (mStateFlags.Has(StateFlags::kIsAddPending))
{
// The root certificate is already associated with a pending fabric, so
// does not exist for purposes of this API.
return CHIP_ERROR_NOT_FOUND;
}
return FetchRootCert(mFabricIndexWithPendingState, outCert);
}
CHIP_ERROR FabricTable::FetchICACert(FabricIndex fabricIndex, MutableByteSpan & outCert) const
{
MATTER_TRACE_SCOPE("FetchICACert", "Fabric");
VerifyOrReturnError(mOpCertStore != nullptr, CHIP_ERROR_INCORRECT_STATE);
CHIP_ERROR err = mOpCertStore->GetCertificate(fabricIndex, CertChainElement::kIcac, outCert);
if (err == CHIP_ERROR_NOT_FOUND)
{
if (mOpCertStore->HasCertificateForFabric(fabricIndex, CertChainElement::kNoc))
{
// Didn't find ICAC, but have NOC: return empty for ICAC since not present in chain, but chain exists
outCert.reduce_size(0);
return CHIP_NO_ERROR;
}
}
// For all other cases, delegate to operational cert store for results
return err;
}
CHIP_ERROR FabricTable::FetchNOCCert(FabricIndex fabricIndex, MutableByteSpan & outCert) const
{
MATTER_TRACE_SCOPE("FetchNOCCert", "Fabric");
VerifyOrReturnError(mOpCertStore != nullptr, CHIP_ERROR_INCORRECT_STATE);
return mOpCertStore->GetCertificate(fabricIndex, CertChainElement::kNoc, outCert);
}
CHIP_ERROR FabricTable::FetchRootPubkey(FabricIndex fabricIndex, Crypto::P256PublicKey & outPublicKey) const
{
MATTER_TRACE_SCOPE("FetchRootPubkey", "Fabric");
const FabricInfo * fabricInfo = FindFabricWithIndex(fabricIndex);
ReturnErrorCodeIf(fabricInfo == nullptr, CHIP_ERROR_INVALID_FABRIC_INDEX);
return fabricInfo->FetchRootPubkey(outPublicKey);
}
CHIP_ERROR FabricTable::FetchCATs(const FabricIndex fabricIndex, CATValues & cats) const
{
uint8_t nocBuf[Credentials::kMaxCHIPCertLength];
MutableByteSpan nocSpan{ nocBuf };
ReturnErrorOnFailure(FetchNOCCert(fabricIndex, nocSpan));
ReturnErrorOnFailure(ExtractCATsFromOpCert(nocSpan, cats));
return CHIP_NO_ERROR;
}
CHIP_ERROR FabricTable::StoreFabricMetadata(const FabricInfo * fabricInfo) const
{
VerifyOrReturnError(mStorage != nullptr, CHIP_ERROR_INCORRECT_STATE);
VerifyOrDie(fabricInfo != nullptr);
FabricIndex fabricIndex = fabricInfo->GetFabricIndex();
VerifyOrReturnError(IsValidFabricIndex(fabricIndex), CHIP_ERROR_INTERNAL);
// TODO: Refactor not to internally rely directly on storage
ReturnErrorOnFailure(fabricInfo->CommitToStorage(mStorage));
ChipLogProgress(FabricProvisioning, "Metadata for Fabric 0x%x persisted to storage.", static_cast<unsigned>(fabricIndex));
return CHIP_NO_ERROR;
}
CHIP_ERROR FabricTable::LoadFromStorage(FabricInfo * fabric, FabricIndex newFabricIndex)
{
VerifyOrReturnError(mStorage != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrReturnError(!fabric->IsInitialized(), CHIP_ERROR_INCORRECT_STATE);
uint8_t nocBuf[kMaxCHIPCertLength];
MutableByteSpan nocSpan{ nocBuf };
uint8_t rcacBuf[kMaxCHIPCertLength];
MutableByteSpan rcacSpan{ rcacBuf };
CHIP_ERROR err = FetchNOCCert(newFabricIndex, nocSpan);
if (err == CHIP_NO_ERROR)
{
err = FetchRootCert(newFabricIndex, rcacSpan);
}
// TODO(#19935): Sweep-away fabrics without RCAC/NOC by deleting everything and marking fabric gone.
if (err == CHIP_NO_ERROR)
{
err = fabric->LoadFromStorage(mStorage, newFabricIndex, rcacSpan, nocSpan);
}
if (err != CHIP_NO_ERROR)
{
ChipLogError(FabricProvisioning, "Failed to load Fabric (0x%x): %" CHIP_ERROR_FORMAT, static_cast<unsigned>(newFabricIndex),
err.Format());
fabric->Reset();
return err;
}
ChipLogProgress(FabricProvisioning,
"Fabric index 0x%x was retrieved from storage. Compressed FabricId 0x" ChipLogFormatX64
", FabricId 0x" ChipLogFormatX64 ", NodeId 0x" ChipLogFormatX64 ", VendorId 0x%04X",
static_cast<unsigned>(fabric->GetFabricIndex()), ChipLogValueX64(fabric->GetCompressedFabricId()),
ChipLogValueX64(fabric->GetFabricId()), ChipLogValueX64(fabric->GetNodeId()),
to_underlying(fabric->GetVendorId()));
return CHIP_NO_ERROR;
}
CHIP_ERROR FabricTable::AddNewFabricForTest(const ByteSpan & rootCert, const ByteSpan & icacCert, const ByteSpan & nocCert,
const ByteSpan & opKeySpan, FabricIndex * outFabricIndex)
{
return AddNewFabricForTestInternal(*this, /*leavePending=*/false, rootCert, icacCert, nocCert, opKeySpan, outFabricIndex);
}
CHIP_ERROR FabricTable::AddNewUncommittedFabricForTest(const ByteSpan & rootCert, const ByteSpan & icacCert,
const ByteSpan & nocCert, const ByteSpan & opKeySpan,
FabricIndex * outFabricIndex)
{
return AddNewFabricForTestInternal(*this, /*leavePending=*/true, rootCert, icacCert, nocCert, opKeySpan, outFabricIndex);
}
/*
* A validation policy we can pass into VerifyCredentials to extract the
* latest NotBefore time in the certificate chain without having to load the
* certificates into memory again, and one which will pass validation for all
* questions of NotBefore / NotAfter validity.
*
* The rationale is that installed certificates should be valid at the time of
* installation by definition. If they are not and the commissionee and
* commissioner disagree enough on current time, CASE will fail and our
* fail-safe timer will expire.
*
* This then is ultimately how we validate that NotBefore / NotAfter in
* newly installed certificates is workable.
*/
class NotBeforeCollector : public Credentials::CertificateValidityPolicy
{
public:
NotBeforeCollector() : mLatestNotBefore(0) {}
CHIP_ERROR ApplyCertificateValidityPolicy(const ChipCertificateData * cert, uint8_t depth,
CertificateValidityResult result) override
{
if (cert->mNotBeforeTime > mLatestNotBefore.count())
{
mLatestNotBefore = System::Clock::Seconds32(cert->mNotBeforeTime);
}
return CHIP_NO_ERROR;
}
System::Clock::Seconds32 mLatestNotBefore;
};
CHIP_ERROR FabricTable::NotifyFabricUpdated(FabricIndex fabricIndex)
{
MATTER_TRACE_SCOPE("NotifyFabricUpdated", "Fabric");
FabricTable::Delegate * delegate = mDelegateListRoot;
while (delegate)
{
// It is possible that delegate will remove itself from the list in the callback
// so we grab the next delegate in the list now.
FabricTable::Delegate * nextDelegate = delegate->next;
delegate->OnFabricUpdated(*this, fabricIndex);
delegate = nextDelegate;
}
return CHIP_NO_ERROR;
}
CHIP_ERROR FabricTable::NotifyFabricCommitted(FabricIndex fabricIndex)
{
MATTER_TRACE_SCOPE("NotifyFabricCommitted", "Fabric");
FabricTable::Delegate * delegate = mDelegateListRoot;
while (delegate)
{
// It is possible that delegate will remove itself from the list in the callback
// so we grab the next delegate in the list now.
FabricTable::Delegate * nextDelegate = delegate->next;
delegate->OnFabricCommitted(*this, fabricIndex);
delegate = nextDelegate;
}
return CHIP_NO_ERROR;
}
CHIP_ERROR
FabricTable::AddOrUpdateInner(FabricIndex fabricIndex, bool isAddition, Crypto::P256Keypair * existingOpKey,
bool isExistingOpKeyExternallyOwned, uint16_t vendorId, AdvertiseIdentity advertiseIdentity)
{
// All parameters pre-validated before we get here
FabricInfo::InitParams newFabricInfo;
FabricInfo * fabricEntry = nullptr;
FabricId fabricIdToValidate = kUndefinedFabricId;
CharSpan fabricLabel;
if (isAddition)
{
// Initialization for Adding a fabric
// Find an available slot.
for (auto & fabric : mStates)
{
if (fabric.IsInitialized())
{
continue;
}
fabricEntry = &fabric;
break;
}
VerifyOrReturnError(fabricEntry != nullptr, CHIP_ERROR_NO_MEMORY);
newFabricInfo.vendorId = static_cast<VendorId>(vendorId);
newFabricInfo.fabricIndex = fabricIndex;
}
else
{
// Initialization for Updating fabric: setting up a shadow fabricInfo
const FabricInfo * existingFabric = FindFabricWithIndex(fabricIndex);
VerifyOrReturnError(existingFabric != nullptr, CHIP_ERROR_INTERNAL);
mPendingFabric.Reset();
fabricEntry = &mPendingFabric;
newFabricInfo.vendorId = existingFabric->GetVendorId();
newFabricInfo.fabricIndex = fabricIndex;
fabricIdToValidate = existingFabric->GetFabricId();
fabricLabel = existingFabric->GetFabricLabel();
}
// Make sure to not modify any of our state until ValidateIncomingNOCChain passes.
NotBeforeCollector notBeforeCollector;
P256PublicKey nocPubKey;
// Validate the cert chain prior to adding
{
Platform::ScopedMemoryBuffer<uint8_t> nocBuf;
Platform::ScopedMemoryBuffer<uint8_t> icacBuf;
Platform::ScopedMemoryBuffer<uint8_t> rcacBuf;
ReturnErrorCodeIf(!nocBuf.Alloc(kMaxCHIPCertLength), CHIP_ERROR_NO_MEMORY);
ReturnErrorCodeIf(!icacBuf.Alloc(kMaxCHIPCertLength), CHIP_ERROR_NO_MEMORY);
ReturnErrorCodeIf(!rcacBuf.Alloc(kMaxCHIPCertLength), CHIP_ERROR_NO_MEMORY);
MutableByteSpan nocSpan{ nocBuf.Get(), kMaxCHIPCertLength };
MutableByteSpan icacSpan{ icacBuf.Get(), kMaxCHIPCertLength };
MutableByteSpan rcacSpan{ rcacBuf.Get(), kMaxCHIPCertLength };
ReturnErrorOnFailure(FetchNOCCert(fabricIndex, nocSpan));
ReturnErrorOnFailure(FetchICACert(fabricIndex, icacSpan));
ReturnErrorOnFailure(FetchRootCert(fabricIndex, rcacSpan));
ReturnErrorOnFailure(ValidateIncomingNOCChain(nocSpan, icacSpan, rcacSpan, fabricIdToValidate, ¬BeforeCollector,
newFabricInfo.compressedFabricId, newFabricInfo.fabricId,
newFabricInfo.nodeId, nocPubKey, newFabricInfo.rootPublicKey));
}
if (existingOpKey != nullptr)
{
// Verify that public key in NOC matches public key of the provided keypair.
// When operational key is not injected (e.g. when mOperationalKeystore != nullptr)
// the check is done by the keystore in `ActivateOpKeypairForFabric`.
VerifyOrReturnError(existingOpKey->Pubkey().Matches(nocPubKey), CHIP_ERROR_INVALID_PUBLIC_KEY);
newFabricInfo.operationalKeypair = existingOpKey;
newFabricInfo.hasExternallyOwnedKeypair = isExistingOpKeyExternallyOwned;
}
else if (mOperationalKeystore != nullptr)
{
// If a keystore exists, we activate the operational key now, which also validates if it was previously installed
if (mOperationalKeystore->HasPendingOpKeypair())
{
ReturnErrorOnFailure(mOperationalKeystore->ActivateOpKeypairForFabric(fabricIndex, nocPubKey));
}
else
{
VerifyOrReturnError(mOperationalKeystore->HasOpKeypairForFabric(fabricIndex), CHIP_ERROR_KEY_NOT_FOUND);
}
}
else
{
return CHIP_ERROR_INCORRECT_STATE;
}
newFabricInfo.advertiseIdentity = (advertiseIdentity == AdvertiseIdentity::Yes);
// Update local copy of fabric data. For add it's a new entry, for update, it's `mPendingFabric` shadow entry.
ReturnErrorOnFailure(fabricEntry->Init(newFabricInfo));
// Set the label, matching add/update semantics of empty/existing.
fabricEntry->SetFabricLabel(fabricLabel);
if (isAddition)
{
ChipLogProgress(FabricProvisioning, "Added new fabric at index: 0x%x",
static_cast<unsigned>(fabricEntry->GetFabricIndex()));
ChipLogProgress(FabricProvisioning, "Assigned compressed fabric ID: 0x" ChipLogFormatX64 ", node ID: 0x" ChipLogFormatX64,
ChipLogValueX64(fabricEntry->GetCompressedFabricId()), ChipLogValueX64(fabricEntry->GetNodeId()));
}
else
{
ChipLogProgress(FabricProvisioning, "Updated fabric at index: 0x%x, Node ID: 0x" ChipLogFormatX64,
static_cast<unsigned>(fabricEntry->GetFabricIndex()), ChipLogValueX64(fabricEntry->GetNodeId()));
}
// Failure to update pending Last Known Good Time is non-fatal. If Last
// Known Good Time is incorrect and this causes the commissioner's
// certificates to appear invalid, the certificate validity policy will
// determine what to do. And if the validity policy considers this fatal
// this will prevent CASE and cause the pending fabric and Last Known Good
// Time to be reverted.
CHIP_ERROR lkgtErr = mLastKnownGoodTime.UpdatePendingLastKnownGoodChipEpochTime(notBeforeCollector.mLatestNotBefore);
if (lkgtErr != CHIP_NO_ERROR)
{
// Log but this is not sticky...
ChipLogError(FabricProvisioning, "Failed to update pending Last Known Good Time: %" CHIP_ERROR_FORMAT, lkgtErr.Format());
}
// Must be the last thing before we return, as this is undone later on error handling within Delete.
if (isAddition)
{
mFabricCount++;
}
return CHIP_NO_ERROR;
}
CHIP_ERROR FabricTable::Delete(FabricIndex fabricIndex)
{
MATTER_TRACE_SCOPE("Delete", "Fabric");
VerifyOrReturnError(mStorage != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrReturnError(IsValidFabricIndex(fabricIndex), CHIP_ERROR_INVALID_ARGUMENT);
{
FabricTable::Delegate * delegate = mDelegateListRoot;
while (delegate)
{
// It is possible that delegate will remove itself from the list in FabricWillBeRemoved,
// so we grab the next delegate in the list now.
FabricTable::Delegate * nextDelegate = delegate->next;
delegate->FabricWillBeRemoved(*this, fabricIndex);
delegate = nextDelegate;
}
}
FabricInfo * fabricInfo = GetMutableFabricByIndex(fabricIndex);
if (fabricInfo == &mPendingFabric)
{
// Asked to Delete while pending an update: reset the pending state and
// get back to the underlying fabric data for existing fabric.
RevertPendingFabricData();
fabricInfo = GetMutableFabricByIndex(fabricIndex);
}
bool fabricIsInitialized = fabricInfo != nullptr && fabricInfo->IsInitialized();
CHIP_ERROR metadataErr = DeleteMetadataFromStorage(fabricIndex); // Delete from storage regardless
CHIP_ERROR opKeyErr = CHIP_NO_ERROR;
if (mOperationalKeystore != nullptr)
{
opKeyErr = mOperationalKeystore->RemoveOpKeypairForFabric(fabricIndex);
// Not having found data is not an error, we may just have gotten here
// on a fail-safe expiry after `RevertPendingFabricData`.
if (opKeyErr == CHIP_ERROR_INVALID_FABRIC_INDEX)
{
opKeyErr = CHIP_NO_ERROR;
}
}
CHIP_ERROR opCertsErr = CHIP_NO_ERROR;
if (mOpCertStore != nullptr)
{
opCertsErr = mOpCertStore->RemoveOpCertsForFabric(fabricIndex);
// Not having found data is not an error, we may just have gotten here
// on a fail-safe expiry after `RevertPendingFabricData`.
if (opCertsErr == CHIP_ERROR_INVALID_FABRIC_INDEX)
{