-
Notifications
You must be signed in to change notification settings - Fork 61
/
Copy pathoperational-credentials-server.cpp
1200 lines (982 loc) · 51.9 KB
/
operational-credentials-server.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.
*/
/****************************************************************************
* @file
* @brief Implementation for the Operational Credentials Cluster
***************************************************************************/
#include <access/AccessControl.h>
#include <app-common/zap-generated/attributes/Accessors.h>
#include <app-common/zap-generated/cluster-objects.h>
#include <app-common/zap-generated/ids/Attributes.h>
#include <app/AttributeAccessInterface.h>
#include <app/AttributeAccessInterfaceRegistry.h>
#include <app/CommandHandler.h>
#include <app/ConcreteCommandPath.h>
#include <app/EventLogging.h>
#include <app/InteractionModelEngine.h>
#include <app/reporting/reporting.h>
#include <app/server/Dnssd.h>
#include <app/server/Server.h>
#include <app/util/attribute-storage.h>
#include <credentials/CHIPCert.h>
#include <credentials/CertificationDeclaration.h>
#include <credentials/DeviceAttestationConstructor.h>
#include <credentials/DeviceAttestationCredsProvider.h>
#include <credentials/FabricTable.h>
#include <credentials/GroupDataProvider.h>
#include <lib/core/CHIPSafeCasts.h>
#include <lib/core/PeerId.h>
#include <lib/support/CodeUtils.h>
#include <lib/support/ScopedBuffer.h>
#include <lib/support/logging/CHIPLogging.h>
#include <platform/CHIPDeviceLayer.h>
#include <string.h>
#include <tracing/macros.h>
using namespace chip;
using namespace ::chip::Transport;
using namespace chip::app;
using namespace chip::app::Clusters;
using namespace chip::app::Clusters::OperationalCredentials;
using namespace chip::Credentials;
using namespace chip::Crypto;
using namespace chip::Protocols::InteractionModel;
namespace {
void SendNOCResponse(app::CommandHandler * commandObj, const ConcreteCommandPath & path, NodeOperationalCertStatusEnum status,
uint8_t index, const CharSpan & debug_text);
NodeOperationalCertStatusEnum ConvertToNOCResponseStatus(CHIP_ERROR err);
constexpr auto kDACCertificate = CertificateChainTypeEnum::kDACCertificate;
constexpr auto kPAICertificate = CertificateChainTypeEnum::kPAICertificate;
CHIP_ERROR CreateAccessControlEntryForNewFabricAdministrator(const Access::SubjectDescriptor & subjectDescriptor,
FabricIndex fabricIndex, uint64_t subject)
{
NodeId subjectAsNodeID = static_cast<NodeId>(subject);
if (!IsOperationalNodeId(subjectAsNodeID) && !IsCASEAuthTag(subjectAsNodeID))
{
return CHIP_ERROR_INVALID_ADMIN_SUBJECT;
}
Access::AccessControl::Entry entry;
ReturnErrorOnFailure(Access::GetAccessControl().PrepareEntry(entry));
ReturnErrorOnFailure(entry.SetFabricIndex(fabricIndex));
ReturnErrorOnFailure(entry.SetPrivilege(Access::Privilege::kAdminister));
ReturnErrorOnFailure(entry.SetAuthMode(Access::AuthMode::kCase));
ReturnErrorOnFailure(entry.AddSubject(nullptr, subject));
CHIP_ERROR err = Access::GetAccessControl().CreateEntry(&subjectDescriptor, fabricIndex, nullptr, entry);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "OpCreds: Failed to add administrative node ACL entry: %" CHIP_ERROR_FORMAT, err.Format());
return err;
}
ChipLogProgress(Zcl, "OpCreds: ACL entry created for Fabric index 0x%x CASE Admin Subject 0x" ChipLogFormatX64,
static_cast<unsigned>(fabricIndex), ChipLogValueX64(subject));
return CHIP_NO_ERROR;
}
class OperationalCredentialsAttrAccess : public AttributeAccessInterface
{
public:
// Register for the OperationalCredentials cluster on all endpoints.
OperationalCredentialsAttrAccess() :
AttributeAccessInterface(Optional<EndpointId>::Missing(), Clusters::OperationalCredentials::Id)
{}
CHIP_ERROR Read(const ConcreteReadAttributePath & aPath, AttributeValueEncoder & aEncoder) override;
private:
CHIP_ERROR ReadNOCs(EndpointId endpoint, AttributeValueEncoder & aEncoder);
CHIP_ERROR ReadSupportedFabrics(EndpointId endpoint, AttributeValueEncoder & aEncoder);
CHIP_ERROR ReadCommissionedFabrics(EndpointId endpoint, AttributeValueEncoder & aEncoder);
CHIP_ERROR ReadFabricsList(EndpointId endpoint, AttributeValueEncoder & aEncoder);
CHIP_ERROR ReadRootCertificates(EndpointId endpoint, AttributeValueEncoder & aEncoder);
};
CHIP_ERROR OperationalCredentialsAttrAccess::ReadNOCs(EndpointId endpoint, AttributeValueEncoder & aEncoder)
{
auto accessingFabricIndex = aEncoder.AccessingFabricIndex();
return aEncoder.EncodeList([accessingFabricIndex](const auto & encoder) -> CHIP_ERROR {
const auto & fabricTable = Server::GetInstance().GetFabricTable();
for (const auto & fabricInfo : fabricTable)
{
Clusters::OperationalCredentials::Structs::NOCStruct::Type noc;
uint8_t nocBuf[kMaxCHIPCertLength];
uint8_t icacBuf[kMaxCHIPCertLength];
MutableByteSpan nocSpan{ nocBuf };
MutableByteSpan icacSpan{ icacBuf };
FabricIndex fabricIndex = fabricInfo.GetFabricIndex();
noc.fabricIndex = fabricIndex;
if (accessingFabricIndex == fabricIndex)
{
ReturnErrorOnFailure(fabricTable.FetchNOCCert(fabricIndex, nocSpan));
ReturnErrorOnFailure(fabricTable.FetchICACert(fabricIndex, icacSpan));
noc.noc = nocSpan;
if (!icacSpan.empty())
{
noc.icac.SetNonNull(icacSpan);
}
}
ReturnErrorOnFailure(encoder.Encode(noc));
}
return CHIP_NO_ERROR;
});
}
CHIP_ERROR OperationalCredentialsAttrAccess::ReadSupportedFabrics(EndpointId endpoint, AttributeValueEncoder & aEncoder)
{
uint8_t fabricCount = CHIP_CONFIG_MAX_FABRICS;
return aEncoder.Encode(fabricCount);
}
CHIP_ERROR OperationalCredentialsAttrAccess::ReadCommissionedFabrics(EndpointId endpoint, AttributeValueEncoder & aEncoder)
{
return aEncoder.Encode(Server::GetInstance().GetFabricTable().FabricCount());
}
CHIP_ERROR OperationalCredentialsAttrAccess::ReadFabricsList(EndpointId endpoint, AttributeValueEncoder & aEncoder)
{
return aEncoder.EncodeList([](const auto & encoder) -> CHIP_ERROR {
const auto & fabricTable = Server::GetInstance().GetFabricTable();
for (const auto & fabricInfo : fabricTable)
{
Clusters::OperationalCredentials::Structs::FabricDescriptorStruct::Type fabricDescriptor;
FabricIndex fabricIndex = fabricInfo.GetFabricIndex();
fabricDescriptor.fabricIndex = fabricIndex;
fabricDescriptor.nodeID = fabricInfo.GetPeerId().GetNodeId();
fabricDescriptor.vendorID = fabricInfo.GetVendorId();
fabricDescriptor.fabricID = fabricInfo.GetFabricId();
fabricDescriptor.label = fabricInfo.GetFabricLabel();
Crypto::P256PublicKey pubKey;
ReturnErrorOnFailure(fabricTable.FetchRootPubkey(fabricIndex, pubKey));
fabricDescriptor.rootPublicKey = ByteSpan{ pubKey.ConstBytes(), pubKey.Length() };
ReturnErrorOnFailure(encoder.Encode(fabricDescriptor));
}
return CHIP_NO_ERROR;
});
}
CHIP_ERROR OperationalCredentialsAttrAccess::ReadRootCertificates(EndpointId endpoint, AttributeValueEncoder & aEncoder)
{
// It is OK to have duplicates.
return aEncoder.EncodeList([](const auto & encoder) -> CHIP_ERROR {
const auto & fabricTable = Server::GetInstance().GetFabricTable();
for (const auto & fabricInfo : fabricTable)
{
uint8_t certBuf[kMaxCHIPCertLength];
MutableByteSpan cert{ certBuf };
ReturnErrorOnFailure(fabricTable.FetchRootCert(fabricInfo.GetFabricIndex(), cert));
ReturnErrorOnFailure(encoder.Encode(ByteSpan{ cert }));
}
{
uint8_t certBuf[kMaxCHIPCertLength];
MutableByteSpan cert{ certBuf };
CHIP_ERROR err = fabricTable.FetchPendingNonFabricAssociatedRootCert(cert);
if (err == CHIP_ERROR_NOT_FOUND)
{
// No pending root cert, do nothing
}
else if (err != CHIP_NO_ERROR)
{
return err;
}
else
{
ReturnErrorOnFailure(encoder.Encode(ByteSpan{ cert }));
}
}
return CHIP_NO_ERROR;
});
}
OperationalCredentialsAttrAccess gAttrAccess;
CHIP_ERROR OperationalCredentialsAttrAccess::Read(const ConcreteReadAttributePath & aPath, AttributeValueEncoder & aEncoder)
{
VerifyOrDie(aPath.mClusterId == Clusters::OperationalCredentials::Id);
switch (aPath.mAttributeId)
{
case Attributes::NOCs::Id: {
return ReadNOCs(aPath.mEndpointId, aEncoder);
}
case Attributes::SupportedFabrics::Id: {
return ReadSupportedFabrics(aPath.mEndpointId, aEncoder);
}
case Attributes::CommissionedFabrics::Id: {
return ReadCommissionedFabrics(aPath.mEndpointId, aEncoder);
}
case Attributes::Fabrics::Id: {
return ReadFabricsList(aPath.mEndpointId, aEncoder);
}
case Attributes::TrustedRootCertificates::Id: {
return ReadRootCertificates(aPath.mEndpointId, aEncoder);
}
case Attributes::CurrentFabricIndex::Id: {
return aEncoder.Encode(aEncoder.AccessingFabricIndex());
}
default:
break;
}
return CHIP_NO_ERROR;
}
const FabricInfo * RetrieveCurrentFabric(CommandHandler * aCommandHandler)
{
FabricIndex index = aCommandHandler->GetAccessingFabricIndex();
ChipLogDetail(Zcl, "OpCreds: Finding fabric with fabricIndex 0x%x", static_cast<unsigned>(index));
return Server::GetInstance().GetFabricTable().FindFabricWithIndex(index);
}
CHIP_ERROR DeleteFabricFromTable(FabricIndex fabricIndex)
{
ReturnErrorOnFailure(Server::GetInstance().GetFabricTable().Delete(fabricIndex));
return CHIP_NO_ERROR;
}
void CleanupSessionsForFabric(SessionManager & sessionMgr, FabricIndex fabricIndex)
{
sessionMgr.ExpireAllSessionsForFabric(fabricIndex);
}
void FailSafeCleanup(const chip::DeviceLayer::ChipDeviceEvent * event)
{
ChipLogError(Zcl, "OpCreds: Proceeding to FailSafeCleanup on fail-safe expiry!");
FabricIndex fabricIndex = event->FailSafeTimerExpired.fabricIndex;
// If an AddNOC or UpdateNOC command has been successfully invoked, terminate all CASE sessions associated with the Fabric
// whose Fabric Index is recorded in the Fail-Safe context (see ArmFailSafe Command) by clearing any associated Secure
// Session Context at the Server.
if (event->FailSafeTimerExpired.addNocCommandHasBeenInvoked || event->FailSafeTimerExpired.updateNocCommandHasBeenInvoked)
{
SessionManager & sessionMgr = Server::GetInstance().GetSecureSessionManager();
CleanupSessionsForFabric(sessionMgr, fabricIndex);
}
auto & fabricTable = Server::GetInstance().GetFabricTable();
fabricTable.RevertPendingFabricData();
// If an AddNOC command had been successfully invoked, achieve the equivalent effect of invoking the RemoveFabric command
// against the Fabric Index stored in the Fail-Safe Context for the Fabric Index that was the subject of the AddNOC
// command.
if (event->FailSafeTimerExpired.addNocCommandHasBeenInvoked)
{
CHIP_ERROR err;
err = DeleteFabricFromTable(fabricIndex);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "OpCreds: failed to delete fabric at index %u: %" CHIP_ERROR_FORMAT, fabricIndex, err.Format());
}
}
}
void OnPlatformEventHandler(const chip::DeviceLayer::ChipDeviceEvent * event, intptr_t arg)
{
if (event->Type == DeviceLayer::DeviceEventType::kFailSafeTimerExpired)
{
ChipLogError(Zcl, "OpCreds: Got FailSafeTimerExpired");
FailSafeCleanup(event);
}
}
} // anonymous namespace
class OpCredsFabricTableDelegate : public chip::FabricTable::Delegate
{
public:
// Gets called when a fabric is about to be deleted
void FabricWillBeRemoved(const FabricTable & fabricTable, FabricIndex fabricIndex) override
{
// The Leave event SHOULD be emitted by a Node prior to permanently leaving the Fabric.
for (auto endpoint : EnabledEndpointsWithServerCluster(BasicInformation::Id))
{
// If Basic cluster is implemented on this endpoint
BasicInformation::Events::Leave::Type event;
event.fabricIndex = fabricIndex;
EventNumber eventNumber;
if (CHIP_NO_ERROR != LogEvent(event, endpoint, eventNumber))
{
ChipLogError(Zcl, "OpCredsFabricTableDelegate: Failed to record Leave event");
}
}
// Try to send the queued events as soon as possible for this fabric. If the just emitted leave event won't
// be sent this time, it will likely not be delivered at all for the following reasons:
// - removing the fabric expires all associated ReadHandlers, so all subscriptions to
// the leave event will be cancelled.
// - removing the fabric removes all associated access control entries, so generating
// subsequent reports containing the leave event will fail the access control check.
InteractionModelEngine::GetInstance()->GetReportingEngine().ScheduleUrgentEventDeliverySync(MakeOptional(fabricIndex));
}
// Gets called when a fabric is deleted
void OnFabricRemoved(const FabricTable & fabricTable, FabricIndex fabricIndex) override
{
ChipLogProgress(Zcl, "OpCreds: Fabric index 0x%x was removed", static_cast<unsigned>(fabricIndex));
// We need to withdraw the advertisement for the now-removed fabric, so need
// to restart advertising altogether.
app::DnssdServer::Instance().StartServer();
EventManagement::GetInstance().FabricRemoved(fabricIndex);
NotifyFabricTableChanged();
}
// Gets called when a fabric is added/updated, but not necessarily committed to storage
void OnFabricUpdated(const FabricTable & fabricTable, FabricIndex fabricIndex) override { NotifyFabricTableChanged(); }
// Gets called when a fabric in FabricTable is persisted to storage
void OnFabricCommitted(const FabricTable & fabricTable, FabricIndex fabricIndex) override
{
const FabricInfo * fabric = fabricTable.FindFabricWithIndex(fabricIndex);
// Safety check, but should not happen by the code paths involved
VerifyOrReturn(fabric != nullptr);
ChipLogProgress(Zcl,
"OpCreds: Fabric index 0x%x was committed to storage. Compressed Fabric Id 0x" ChipLogFormatX64
", FabricId " ChipLogFormatX64 ", NodeId " ChipLogFormatX64 ", VendorId 0x%04X",
static_cast<unsigned>(fabric->GetFabricIndex()), ChipLogValueX64(fabric->GetCompressedFabricId()),
ChipLogValueX64(fabric->GetFabricId()), ChipLogValueX64(fabric->GetNodeId()), fabric->GetVendorId());
}
private:
void NotifyFabricTableChanged()
{
// Opcreds cluster is always on Endpoint 0
MatterReportingAttributeChangeCallback(0, OperationalCredentials::Id,
OperationalCredentials::Attributes::CommissionedFabrics::Id);
MatterReportingAttributeChangeCallback(0, OperationalCredentials::Id, OperationalCredentials::Attributes::Fabrics::Id);
}
};
OpCredsFabricTableDelegate gFabricDelegate;
void MatterOperationalCredentialsPluginServerInitCallback()
{
AttributeAccessInterfaceRegistry::Instance().Register(&gAttrAccess);
Server::GetInstance().GetFabricTable().AddFabricDelegate(&gFabricDelegate);
DeviceLayer::PlatformMgrImpl().AddEventHandler(OnPlatformEventHandler);
}
bool emberAfOperationalCredentialsClusterRemoveFabricCallback(app::CommandHandler * commandObj,
const app::ConcreteCommandPath & commandPath,
const Commands::RemoveFabric::DecodableType & commandData)
{
MATTER_TRACE_SCOPE("RemoveFabric", "OperationalCredentials");
auto & fabricBeingRemoved = commandData.fabricIndex;
ChipLogProgress(Zcl, "OpCreds: Received a RemoveFabric Command for FabricIndex 0x%x",
static_cast<unsigned>(fabricBeingRemoved));
if (!IsValidFabricIndex(fabricBeingRemoved))
{
ChipLogError(Zcl, "OpCreds: Failed RemoveFabric due to invalid FabricIndex");
commandObj->AddStatus(commandPath, Status::InvalidCommand);
return true;
}
commandObj->FlushAcksRightAwayOnSlowCommand();
CHIP_ERROR err = DeleteFabricFromTable(fabricBeingRemoved);
SuccessOrExit(err);
// Notification was already done by FabricTable delegate
exit:
// Not using ConvertToNOCResponseStatus here because it's pretty
// AddNOC/UpdateNOC specific.
if (err == CHIP_ERROR_NOT_FOUND)
{
ChipLogError(Zcl, "OpCreds: Failed RemoveFabric due to FabricIndex not found locally");
SendNOCResponse(commandObj, commandPath, NodeOperationalCertStatusEnum::kInvalidFabricIndex, fabricBeingRemoved,
CharSpan());
}
else if (err != CHIP_NO_ERROR)
{
// We have no idea what happened; just report failure.
ChipLogError(Zcl, "OpCreds: Failed RemoveFabric due to internal error (err = %" CHIP_ERROR_FORMAT ")", err.Format());
StatusIB status(err);
commandObj->AddStatus(commandPath, status.mStatus);
}
else
{
ChipLogProgress(Zcl, "OpCreds: RemoveFabric successful");
SendNOCResponse(commandObj, commandPath, NodeOperationalCertStatusEnum::kOk, fabricBeingRemoved, CharSpan());
chip::Messaging::ExchangeContext * ec = commandObj->GetExchangeContext();
FabricIndex currentFabricIndex = commandObj->GetAccessingFabricIndex();
if (currentFabricIndex == fabricBeingRemoved)
{
ec->AbortAllOtherCommunicationOnFabric();
}
else
{
SessionManager * sessionManager = ec->GetExchangeMgr()->GetSessionManager();
CleanupSessionsForFabric(*sessionManager, fabricBeingRemoved);
}
}
return true;
}
bool emberAfOperationalCredentialsClusterUpdateFabricLabelCallback(app::CommandHandler * commandObj,
const app::ConcreteCommandPath & commandPath,
const Commands::UpdateFabricLabel::DecodableType & commandData)
{
MATTER_TRACE_SCOPE("UpdateFabricLabel", "OperationalCredentials");
auto & label = commandData.label;
auto ourFabricIndex = commandObj->GetAccessingFabricIndex();
auto finalStatus = Status::Failure;
auto & fabricTable = Server::GetInstance().GetFabricTable();
ChipLogProgress(Zcl, "OpCreds: Received an UpdateFabricLabel command");
if (label.size() > 32)
{
ChipLogError(Zcl, "OpCreds: Failed UpdateFabricLabel due to invalid label size %u", static_cast<unsigned>(label.size()));
commandObj->AddStatus(commandPath, Status::InvalidCommand);
return true;
}
for (const auto & fabricInfo : fabricTable)
{
if (fabricInfo.GetFabricLabel().data_equal(label) && fabricInfo.GetFabricIndex() != ourFabricIndex)
{
ChipLogError(Zcl, "Fabric label already in use");
SendNOCResponse(commandObj, commandPath, NodeOperationalCertStatusEnum::kLabelConflict, ourFabricIndex, CharSpan());
return true;
}
}
// Set Label on fabric. Any error on this is basically an internal error...
// NOTE: if an UpdateNOC had caused a pending fabric, that pending fabric is
// the one updated thereafter. Otherwise, the data is committed to storage
// as soon as the update is done.
CHIP_ERROR err = fabricTable.SetFabricLabel(ourFabricIndex, label);
VerifyOrExit(err == CHIP_NO_ERROR, finalStatus = Status::Failure);
finalStatus = Status::Success;
// Succeeded at updating the label, mark Fabrics table changed.
MatterReportingAttributeChangeCallback(commandPath.mEndpointId, OperationalCredentials::Id,
OperationalCredentials::Attributes::Fabrics::Id);
exit:
if (finalStatus == Status::Success)
{
SendNOCResponse(commandObj, commandPath, NodeOperationalCertStatusEnum::kOk, ourFabricIndex, CharSpan());
}
else
{
commandObj->AddStatus(commandPath, finalStatus);
}
return true;
}
namespace {
void SendNOCResponse(app::CommandHandler * commandObj, const ConcreteCommandPath & path, NodeOperationalCertStatusEnum status,
uint8_t index, const CharSpan & debug_text)
{
Commands::NOCResponse::Type payload;
payload.statusCode = status;
if (status == NodeOperationalCertStatusEnum::kOk)
{
payload.fabricIndex.Emplace(index);
}
if (!debug_text.empty())
{
// Max length of DebugText is 128 in the spec.
const CharSpan & to_send = debug_text.size() > 128 ? debug_text.SubSpan(0, 128) : debug_text;
payload.debugText.Emplace(to_send);
}
commandObj->AddResponse(path, payload);
}
NodeOperationalCertStatusEnum ConvertToNOCResponseStatus(CHIP_ERROR err)
{
if (err == CHIP_NO_ERROR)
{
return NodeOperationalCertStatusEnum::kOk;
}
if (err == CHIP_ERROR_INVALID_PUBLIC_KEY)
{
return NodeOperationalCertStatusEnum::kInvalidPublicKey;
}
if (err == CHIP_ERROR_WRONG_NODE_ID)
{
return NodeOperationalCertStatusEnum::kInvalidNodeOpId;
}
if (err == CHIP_ERROR_UNSUPPORTED_CERT_FORMAT)
{
return NodeOperationalCertStatusEnum::kInvalidNOC;
}
if (err == CHIP_ERROR_WRONG_CERT_DN)
{
return NodeOperationalCertStatusEnum::kInvalidNOC;
}
if (err == CHIP_ERROR_INCORRECT_STATE)
{
return NodeOperationalCertStatusEnum::kMissingCsr;
}
if (err == CHIP_ERROR_NO_MEMORY)
{
return NodeOperationalCertStatusEnum::kTableFull;
}
if (err == CHIP_ERROR_FABRIC_EXISTS)
{
return NodeOperationalCertStatusEnum::kFabricConflict;
}
if (err == CHIP_ERROR_INVALID_FABRIC_INDEX)
{
return NodeOperationalCertStatusEnum::kInvalidFabricIndex;
}
if (err == CHIP_ERROR_INVALID_ADMIN_SUBJECT)
{
return NodeOperationalCertStatusEnum::kInvalidAdminSubject;
}
return NodeOperationalCertStatusEnum::kInvalidNOC;
}
} // namespace
bool emberAfOperationalCredentialsClusterAddNOCCallback(app::CommandHandler * commandObj,
const app::ConcreteCommandPath & commandPath,
const Commands::AddNOC::DecodableType & commandData)
{
MATTER_TRACE_SCOPE("AddNOC", "OperationalCredentials");
auto & NOCValue = commandData.NOCValue;
auto & ICACValue = commandData.ICACValue;
auto & adminVendorId = commandData.adminVendorId;
auto & ipkValue = commandData.IPKValue;
auto * groupDataProvider = Credentials::GetGroupDataProvider();
auto nocResponse = NodeOperationalCertStatusEnum::kOk;
auto nonDefaultStatus = Status::Success;
bool needRevert = false;
CHIP_ERROR err = CHIP_NO_ERROR;
FabricIndex newFabricIndex = kUndefinedFabricIndex;
Credentials::GroupDataProvider::KeySet keyset;
const FabricInfo * newFabricInfo = nullptr;
auto & fabricTable = Server::GetInstance().GetFabricTable();
auto * secureSession = commandObj->GetExchangeContext()->GetSessionHandle()->AsSecureSession();
auto & failSafeContext = Server::GetInstance().GetFailSafeContext();
uint8_t compressed_fabric_id_buffer[sizeof(uint64_t)];
MutableByteSpan compressed_fabric_id(compressed_fabric_id_buffer);
bool csrWasForUpdateNoc = false; //< Output param of HasPendingOperationalKey
bool hasPendingKey = fabricTable.HasPendingOperationalKey(csrWasForUpdateNoc);
ChipLogProgress(Zcl, "OpCreds: Received an AddNOC command");
VerifyOrExit(NOCValue.size() <= Credentials::kMaxCHIPCertLength, nonDefaultStatus = Status::InvalidCommand);
VerifyOrExit(!ICACValue.HasValue() || ICACValue.Value().size() <= Credentials::kMaxCHIPCertLength,
nonDefaultStatus = Status::InvalidCommand);
VerifyOrExit(ipkValue.size() == Crypto::CHIP_CRYPTO_SYMMETRIC_KEY_LENGTH_BYTES, nonDefaultStatus = Status::InvalidCommand);
VerifyOrExit(IsVendorIdValidOperationally(adminVendorId), nonDefaultStatus = Status::InvalidCommand);
VerifyOrExit(failSafeContext.IsFailSafeArmed(commandObj->GetAccessingFabricIndex()),
nonDefaultStatus = Status::FailsafeRequired);
VerifyOrExit(!failSafeContext.NocCommandHasBeenInvoked(), nonDefaultStatus = Status::ConstraintError);
// Must have had a previous CSR request, not tagged for UpdateNOC
VerifyOrExit(hasPendingKey, nocResponse = NodeOperationalCertStatusEnum::kMissingCsr);
VerifyOrExit(!csrWasForUpdateNoc, nonDefaultStatus = Status::ConstraintError);
// Internal error that would prevent IPK from being added
VerifyOrExit(groupDataProvider != nullptr, nonDefaultStatus = Status::Failure);
// Flush acks before really slow work
commandObj->FlushAcksRightAwayOnSlowCommand();
// We can't possibly have a matching root based on the fact that we don't have
// a shared root store. Therefore we would later fail path validation due to
// missing root. Let's early-bail with InvalidNOC.
VerifyOrExit(failSafeContext.AddTrustedRootCertHasBeenInvoked(), nocResponse = NodeOperationalCertStatusEnum::kInvalidNOC);
// Check this explicitly before adding the fabric so we don't need to back out changes if this is an error.
VerifyOrExit(IsOperationalNodeId(commandData.caseAdminSubject) || IsCASEAuthTag(commandData.caseAdminSubject),
nocResponse = NodeOperationalCertStatusEnum::kInvalidAdminSubject);
err = fabricTable.AddNewPendingFabricWithOperationalKeystore(NOCValue, ICACValue.ValueOr(ByteSpan{}), adminVendorId,
&newFabricIndex);
VerifyOrExit(err == CHIP_NO_ERROR, nocResponse = ConvertToNOCResponseStatus(err));
// Inform FailSafeContext about starting adding NOC for specified fabric
VerifyOrExit(failSafeContext.SetAddNocCommandStarted(newFabricIndex), nonDefaultStatus = Status::Failure);
// From here if we error-out, we should revert the fabric table pending updates
needRevert = true;
newFabricInfo = fabricTable.FindFabricWithIndex(newFabricIndex);
VerifyOrExit(newFabricInfo != nullptr, nonDefaultStatus = Status::Failure);
// Set the Identity Protection Key (IPK)
// The IPK SHALL be the operational group key under GroupKeySetID of 0
keyset.keyset_id = Credentials::GroupDataProvider::kIdentityProtectionKeySetId;
keyset.policy = GroupKeyManagement::GroupKeySecurityPolicyEnum::kTrustFirst;
keyset.num_keys_used = 1;
keyset.epoch_keys[0].start_time = 0;
memcpy(keyset.epoch_keys[0].key, ipkValue.data(), Crypto::CHIP_CRYPTO_SYMMETRIC_KEY_LENGTH_BYTES);
err = newFabricInfo->GetCompressedFabricIdBytes(compressed_fabric_id);
VerifyOrExit(err == CHIP_NO_ERROR, nonDefaultStatus = Status::Failure);
err = groupDataProvider->SetKeySet(newFabricIndex, compressed_fabric_id, keyset);
VerifyOrExit(err == CHIP_NO_ERROR, nocResponse = ConvertToNOCResponseStatus(err));
/**
* . If the current secure session was established with PASE,
* the receiver SHALL:
* .. Augment the secure session context with the `FabricIndex` generated above
* such that subsequent interactions have the proper accessing fabric.
*
* . If the current secure session was established with CASE, subsequent configuration
* of the newly installed Fabric requires the opening of a new CASE session from the
* Administrator from the Fabric just installed. This Administrator is the one listed
* in the `caseAdminSubject` argument.
*
*/
if (secureSession->GetSecureSessionType() == SecureSession::Type::kPASE)
{
err = secureSession->AdoptFabricIndex(newFabricIndex);
VerifyOrExit(err == CHIP_NO_ERROR, nonDefaultStatus = Status::Failure);
}
// Creating the initial ACL must occur after the PASE session has adopted the fabric index
// (see above) so that the concomitant event, which is fabric scoped, is properly handled.
err = CreateAccessControlEntryForNewFabricAdministrator(commandObj->GetSubjectDescriptor(), newFabricIndex,
commandData.caseAdminSubject);
VerifyOrExit(err != CHIP_ERROR_INTERNAL, nonDefaultStatus = Status::Failure);
VerifyOrExit(err == CHIP_NO_ERROR, nocResponse = ConvertToNOCResponseStatus(err));
// The Fabric Index associated with the armed fail-safe context SHALL be updated to match the Fabric
// Index just allocated.
failSafeContext.SetAddNocCommandInvoked(newFabricIndex);
// Done all intermediate steps, we are now successful
needRevert = false;
// We might have a new operational identity, so we should start advertising it right away.
err = app::DnssdServer::Instance().AdvertiseOperational();
if (err != CHIP_NO_ERROR)
{
ChipLogError(AppServer, "Operational advertising failed: %" CHIP_ERROR_FORMAT, err.Format());
}
// Notify the attributes containing fabric metadata can be read with new data
MatterReportingAttributeChangeCallback(commandPath.mEndpointId, OperationalCredentials::Id,
OperationalCredentials::Attributes::Fabrics::Id);
// Notify we have one more fabric
MatterReportingAttributeChangeCallback(commandPath.mEndpointId, OperationalCredentials::Id,
OperationalCredentials::Attributes::CommissionedFabrics::Id);
exit:
if (needRevert)
{
// Here, on revert, we DO NOT call FabricTable::Delete as this would also remove the existing
// trusted root previously added. It possibly got reverted in case of the worst kinds of errors,
// but a better impl of the innards of FabricTable::CommitPendingFabricData would make it work.
fabricTable.RevertPendingOpCertsExceptRoot();
// Revert IPK and ACL entries added, ignoring errors, since some steps may have been skipped
// and error handling does not assist.
if (groupDataProvider != nullptr)
{
(void) groupDataProvider->RemoveFabric(newFabricIndex);
}
(void) Access::GetAccessControl().DeleteAllEntriesForFabric(newFabricIndex);
MatterReportingAttributeChangeCallback(commandPath.mEndpointId, OperationalCredentials::Id,
OperationalCredentials::Attributes::CommissionedFabrics::Id);
MatterReportingAttributeChangeCallback(commandPath.mEndpointId, OperationalCredentials::Id,
OperationalCredentials::Attributes::Fabrics::Id);
}
// We have an NOC response
if (nonDefaultStatus == Status::Success)
{
SendNOCResponse(commandObj, commandPath, nocResponse, newFabricIndex, CharSpan());
// Failed to add NOC
if (nocResponse != NodeOperationalCertStatusEnum::kOk)
{
ChipLogError(Zcl, "OpCreds: Failed AddNOC request (err=%" CHIP_ERROR_FORMAT ") with OperationalCert error %d",
err.Format(), to_underlying(nocResponse));
}
// Success
else
{
ChipLogProgress(Zcl, "OpCreds: successfully created fabric index 0x%x via AddNOC",
static_cast<unsigned>(newFabricIndex));
}
}
// No NOC response - Failed constraints
else
{
commandObj->AddStatus(commandPath, nonDefaultStatus);
ChipLogError(Zcl, "OpCreds: Failed AddNOC request with IM error 0x%02x", to_underlying(nonDefaultStatus));
}
return true;
}
bool emberAfOperationalCredentialsClusterUpdateNOCCallback(app::CommandHandler * commandObj,
const app::ConcreteCommandPath & commandPath,
const Commands::UpdateNOC::DecodableType & commandData)
{
MATTER_TRACE_SCOPE("UpdateNOC", "OperationalCredentials");
auto & NOCValue = commandData.NOCValue;
auto & ICACValue = commandData.ICACValue;
auto nocResponse = NodeOperationalCertStatusEnum::kOk;
auto nonDefaultStatus = Status::Success;
CHIP_ERROR err = CHIP_NO_ERROR;
FabricIndex fabricIndex = 0;
ChipLogProgress(Zcl, "OpCreds: Received an UpdateNOC command");
auto & fabricTable = Server::GetInstance().GetFabricTable();
auto & failSafeContext = Server::GetInstance().GetFailSafeContext();
const FabricInfo * fabricInfo = RetrieveCurrentFabric(commandObj);
bool csrWasForUpdateNoc = false; //< Output param of HasPendingOperationalKey
bool hasPendingKey = fabricTable.HasPendingOperationalKey(csrWasForUpdateNoc);
VerifyOrExit(NOCValue.size() <= Credentials::kMaxCHIPCertLength, nonDefaultStatus = Status::InvalidCommand);
VerifyOrExit(!ICACValue.HasValue() || ICACValue.Value().size() <= Credentials::kMaxCHIPCertLength,
nonDefaultStatus = Status::InvalidCommand);
VerifyOrExit(failSafeContext.IsFailSafeArmed(commandObj->GetAccessingFabricIndex()),
nonDefaultStatus = Status::FailsafeRequired);
VerifyOrExit(!failSafeContext.NocCommandHasBeenInvoked(), nonDefaultStatus = Status::ConstraintError);
// Must have had a previous CSR request, tagged for UpdateNOC
VerifyOrExit(hasPendingKey, nocResponse = NodeOperationalCertStatusEnum::kMissingCsr);
VerifyOrExit(csrWasForUpdateNoc, nonDefaultStatus = Status::ConstraintError);
// If current fabric is not available, command was invoked over PASE which is not legal
VerifyOrExit(fabricInfo != nullptr, nocResponse = ConvertToNOCResponseStatus(CHIP_ERROR_INSUFFICIENT_PRIVILEGE));
fabricIndex = fabricInfo->GetFabricIndex();
// Flush acks before really slow work
commandObj->FlushAcksRightAwayOnSlowCommand();
err = fabricTable.UpdatePendingFabricWithOperationalKeystore(fabricIndex, NOCValue, ICACValue.ValueOr(ByteSpan{}));
VerifyOrExit(err == CHIP_NO_ERROR, nocResponse = ConvertToNOCResponseStatus(err));
// Flag on the fail-safe context that the UpdateNOC command was invoked.
failSafeContext.SetUpdateNocCommandInvoked();
// We might have a new operational identity, so we should start advertising
// it right away. Also, we need to withdraw our old operational identity.
// So we need to StartServer() here.
app::DnssdServer::Instance().StartServer();
// Attribute notification was already done by fabric table
exit:
// We have an NOC response
if (nonDefaultStatus == Status::Success)
{
SendNOCResponse(commandObj, commandPath, nocResponse, fabricIndex, CharSpan());
// Failed to update NOC
if (nocResponse != NodeOperationalCertStatusEnum::kOk)
{
ChipLogError(Zcl, "OpCreds: Failed UpdateNOC request (err=%" CHIP_ERROR_FORMAT ") with OperationalCert error %d",
err.Format(), to_underlying(nocResponse));
}
// Success
else
{
ChipLogProgress(Zcl, "OpCreds: UpdateNOC successful.");
// On success, revoke all CASE sessions on the fabric hosting the exchange.
// From spec:
//
// All internal data reflecting the prior operational identifier of the Node within the Fabric
// SHALL be revoked and removed, to an outcome equivalent to the disappearance of the prior Node,
// except for the ongoing CASE session context, which SHALL temporarily remain valid until the
// `NOCResponse` has been successfully delivered or until the next transport-layer error, so
// that the response can be received by the Administrator invoking the command.
commandObj->GetExchangeContext()->AbortAllOtherCommunicationOnFabric();
}
}
// No NOC response - Failed constraints
else
{
commandObj->AddStatus(commandPath, nonDefaultStatus);
ChipLogError(Zcl, "OpCreds: Failed UpdateNOC request with IM error 0x%02x", to_underlying(nonDefaultStatus));
}
return true;
}
bool emberAfOperationalCredentialsClusterCertificateChainRequestCallback(
app::CommandHandler * commandObj, const app::ConcreteCommandPath & commandPath,
const Commands::CertificateChainRequest::DecodableType & commandData)
{
MATTER_TRACE_SCOPE("CertificateChainRequest", "OperationalCredentials");
auto & certificateType = commandData.certificateType;
CHIP_ERROR err = CHIP_NO_ERROR;
uint8_t derBuf[Credentials::kMaxDERCertLength];
MutableByteSpan derBufSpan(derBuf);
Commands::CertificateChainResponse::Type response;
Credentials::DeviceAttestationCredentialsProvider * dacProvider = Credentials::GetDeviceAttestationCredentialsProvider();
VerifyOrExit(commandObj != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
if (certificateType == kDACCertificate)
{
ChipLogProgress(Zcl, "OpCreds: Certificate Chain request received for DAC");
SuccessOrExit(err = dacProvider->GetDeviceAttestationCert(derBufSpan));
}
else if (certificateType == kPAICertificate)
{
ChipLogProgress(Zcl, "OpCreds: Certificate Chain request received for PAI");
SuccessOrExit(err = dacProvider->GetProductAttestationIntermediateCert(derBufSpan));
}
else
{
ChipLogError(Zcl, "OpCreds: Certificate Chain request received for unknown type: %d", static_cast<int>(certificateType));
commandObj->AddStatus(commandPath, Status::InvalidCommand);
return true;
}
response.certificate = derBufSpan;
commandObj->AddResponse(commandPath, response);
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(Zcl, "OpCreds: Failed CertificateChainRequest: %" CHIP_ERROR_FORMAT, err.Format());
commandObj->AddStatus(commandPath, Status::Failure);
}
return true;
}
bool emberAfOperationalCredentialsClusterAttestationRequestCallback(app::CommandHandler * commandObj,
const app::ConcreteCommandPath & commandPath,
const Commands::AttestationRequest::DecodableType & commandData)
{
MATTER_TRACE_SCOPE("AttestationRequest", "OperationalCredentials");
auto & attestationNonce = commandData.attestationNonce;
auto finalStatus = Status::Failure;
CHIP_ERROR err = CHIP_ERROR_INVALID_ARGUMENT;
ByteSpan tbsSpan;
Platform::ScopedMemoryBuffer<uint8_t> attestationElements;
size_t attestationElementsLen = 0;
MutableByteSpan attestationElementsSpan;
uint8_t certDeclBuf[Credentials::kMaxCMSSignedCDMessage]; // Sized to hold the example certificate declaration with 100 PIDs.
// See DeviceAttestationCredsExample
MutableByteSpan certDeclSpan(certDeclBuf);
// TODO: Create an alternative way to retrieve the Attestation Challenge without this huge amount of calls.
// Retrieve attestation challenge
ByteSpan attestationChallenge =
commandObj->GetExchangeContext()->GetSessionHandle()->AsSecureSession()->GetCryptoContext().GetAttestationChallenge();
// TODO: in future versions, retrieve vendor information to populate the fields below.
uint32_t timestamp = 0;
Credentials::DeviceAttestationVendorReservedConstructor emptyVendorReserved(nullptr, 0);
// TODO: in future versions, also retrieve and use firmware Information
const ByteSpan kEmptyFirmwareInfo;
ChipLogProgress(Zcl, "OpCreds: Received an AttestationRequest command");
// Flush acks before really slow work
commandObj->FlushAcksRightAwayOnSlowCommand();
Credentials::DeviceAttestationCredentialsProvider * dacProvider = Credentials::GetDeviceAttestationCredentialsProvider();
VerifyOrExit(attestationNonce.size() == Credentials::kExpectedAttestationNonceSize, finalStatus = Status::InvalidCommand);
if (dacProvider == nullptr)
{
err = CHIP_ERROR_INTERNAL;
VerifyOrExit(dacProvider != nullptr, finalStatus = Status::Failure);
}
err = dacProvider->GetCertificationDeclaration(certDeclSpan);
VerifyOrExit(err == CHIP_NO_ERROR, finalStatus = Status::Failure);
attestationElementsLen = TLV::EstimateStructOverhead(certDeclSpan.size(), attestationNonce.size(), sizeof(uint64_t) * 8);
if (!attestationElements.Alloc(attestationElementsLen + attestationChallenge.size()))
{
err = CHIP_ERROR_NO_MEMORY;
VerifyOrExit(err == CHIP_NO_ERROR, finalStatus = Status::ResourceExhausted);
}
attestationElementsSpan = MutableByteSpan{ attestationElements.Get(), attestationElementsLen };
err = Credentials::ConstructAttestationElements(certDeclSpan, attestationNonce, timestamp, kEmptyFirmwareInfo,
emptyVendorReserved, attestationElementsSpan);
VerifyOrExit(err == CHIP_NO_ERROR, finalStatus = Status::Failure);
// Append attestation challenge in the back of the reserved space for the signature
memcpy(attestationElements.Get() + attestationElementsSpan.size(), attestationChallenge.data(), attestationChallenge.size());
tbsSpan = ByteSpan{ attestationElements.Get(), attestationElementsSpan.size() + attestationChallenge.size() };
{
Crypto::P256ECDSASignature signature;
MutableByteSpan signatureSpan{ signature.Bytes(), signature.Capacity() };
// Generate attestation signature
err = dacProvider->SignWithDeviceAttestationKey(tbsSpan, signatureSpan);
ClearSecretData(attestationElements.Get() + attestationElementsSpan.size(), attestationChallenge.size());
VerifyOrExit(err == CHIP_NO_ERROR, finalStatus = Status::Failure);
VerifyOrExit(signatureSpan.size() == Crypto::P256ECDSASignature::Capacity(), finalStatus = Status::Failure);
Commands::AttestationResponse::Type response;
response.attestationElements = attestationElementsSpan;
response.attestationSignature = signatureSpan;
ChipLogProgress(Zcl, "OpCreds: AttestationRequest successful.");
finalStatus = Status::Success;
commandObj->AddResponse(commandPath, response);
}
exit:
if (finalStatus != Status::Success)
{