forked from project-chip/connectedhomeip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgroup-key-mgmt-server.cpp
728 lines (623 loc) · 28.1 KB
/
group-key-mgmt-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
/**
*
* Copyright (c) 2020-2022 Project CHIP Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://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.
*/
#include <app-common/zap-generated/attributes/Accessors.h>
#include <app-common/zap-generated/cluster-objects.h>
#include <app/AttributeAccessInterface.h>
#include <app/AttributeAccessInterfaceRegistry.h>
#include <app/CommandHandler.h>
#include <app/MessageDef/StatusIB.h>
#include <app/server/Server.h>
#include <app/util/attribute-storage.h>
#include <credentials/GroupDataProvider.h>
#include <lib/support/CodeUtils.h>
using namespace chip;
using namespace chip::app;
using namespace chip::Credentials;
using namespace chip::app::Clusters;
using namespace chip::app::Clusters::GroupKeyManagement;
using chip::Protocols::InteractionModel::Status;
//
// Attributes
//
namespace {
struct GroupTableCodec
{
static constexpr TLV::Tag TagFabric()
{
return TLV::ContextTag(GroupKeyManagement::Structs::GroupInfoMapStruct::Fields::kFabricIndex);
}
static constexpr TLV::Tag TagGroup()
{
return TLV::ContextTag(GroupKeyManagement::Structs::GroupInfoMapStruct::Fields::kGroupId);
}
static constexpr TLV::Tag TagEndpoints()
{
return TLV::ContextTag(GroupKeyManagement::Structs::GroupInfoMapStruct::Fields::kEndpoints);
}
static constexpr TLV::Tag TagGroupName()
{
return TLV::ContextTag(GroupKeyManagement::Structs::GroupInfoMapStruct::Fields::kGroupName);
}
GroupDataProvider * mProvider = nullptr;
chip::FabricIndex mFabric;
GroupDataProvider::GroupInfo mInfo;
GroupTableCodec(GroupDataProvider * provider, chip::FabricIndex fabric_index, GroupDataProvider::GroupInfo & info) :
mProvider(provider), mFabric(fabric_index), mInfo(info)
{}
static constexpr bool kIsFabricScoped = true;
auto GetFabricIndex() const { return mFabric; }
CHIP_ERROR EncodeForRead(TLV::TLVWriter & writer, TLV::Tag tag, FabricIndex accessingFabricIndex) const
{
TLV::TLVType outer;
ReturnErrorOnFailure(writer.StartContainer(tag, TLV::kTLVType_Structure, outer));
// FabricIndex
ReturnErrorOnFailure(DataModel::Encode(writer, TagFabric(), mFabric));
// GroupId
ReturnErrorOnFailure(DataModel::Encode(writer, TagGroup(), mInfo.group_id));
// Endpoints
TLV::TLVType inner;
ReturnErrorOnFailure(writer.StartContainer(TagEndpoints(), TLV::kTLVType_Array, inner));
GroupDataProvider::GroupEndpoint mapping;
auto iter = mProvider->IterateEndpoints(mFabric, std::make_optional(mInfo.group_id));
if (nullptr != iter)
{
while (iter->Next(mapping))
{
ReturnErrorOnFailure(writer.Put(TLV::AnonymousTag(), static_cast<uint16_t>(mapping.endpoint_id)));
}
iter->Release();
}
ReturnErrorOnFailure(writer.EndContainer(inner));
// GroupName
uint32_t name_size = static_cast<uint32_t>(strnlen(mInfo.name, GroupDataProvider::GroupInfo::kGroupNameMax));
ReturnErrorOnFailure(writer.PutString(TagGroupName(), mInfo.name, name_size));
ReturnErrorOnFailure(writer.EndContainer(outer));
return CHIP_NO_ERROR;
}
};
class GroupKeyManagementAttributeAccess : public AttributeAccessInterface
{
public:
// Register for the GroupKeyManagement cluster on all endpoints.
GroupKeyManagementAttributeAccess() : AttributeAccessInterface(Optional<EndpointId>(0), GroupKeyManagement::Id) {}
// TODO: Once there is MCSP support, this may need to change.
static constexpr bool IsMCSPSupported() { return false; }
static constexpr uint16_t kImplementedClusterRevision = 2;
CHIP_ERROR Read(const ConcreteReadAttributePath & aPath, AttributeValueEncoder & aEncoder) override
{
VerifyOrDie(aPath.mClusterId == GroupKeyManagement::Id);
switch (aPath.mAttributeId)
{
case GroupKeyManagement::Attributes::ClusterRevision::Id:
return aEncoder.Encode(kImplementedClusterRevision);
case Attributes::FeatureMap::Id: {
uint32_t features = 0;
if (IsMCSPSupported())
{
// TODO: Once there is MCSP support, this will need to add the
// right feature bit.
}
return aEncoder.Encode(features);
}
case GroupKeyManagement::Attributes::GroupKeyMap::Id:
return ReadGroupKeyMap(aPath.mEndpointId, aEncoder);
case GroupKeyManagement::Attributes::GroupTable::Id:
return ReadGroupTable(aPath.mEndpointId, aEncoder);
case GroupKeyManagement::Attributes::MaxGroupsPerFabric::Id:
return ReadMaxGroupsPerFabric(aPath.mEndpointId, aEncoder);
case GroupKeyManagement::Attributes::MaxGroupKeysPerFabric::Id:
return ReadMaxGroupKeysPerFabric(aPath.mEndpointId, aEncoder);
default:
break;
}
return CHIP_ERROR_READ_FAILED;
}
CHIP_ERROR Write(const ConcreteDataAttributePath & aPath, AttributeValueDecoder & aDecoder) override
{
if (GroupKeyManagement::Attributes::GroupKeyMap::Id == aPath.mAttributeId)
{
return WriteGroupKeyMap(aPath, aDecoder);
}
return CHIP_ERROR_WRITE_FAILED;
}
private:
static constexpr uint16_t kClusterRevision = 1;
CHIP_ERROR ReadClusterRevision(EndpointId endpoint, AttributeValueEncoder & aEncoder)
{
return aEncoder.Encode(kClusterRevision);
}
CHIP_ERROR ReadGroupKeyMap(EndpointId endpoint, AttributeValueEncoder & aEncoder)
{
auto provider = GetGroupDataProvider();
VerifyOrReturnError(nullptr != provider, CHIP_ERROR_INTERNAL);
CHIP_ERROR err = aEncoder.EncodeList([provider](const auto & encoder) -> CHIP_ERROR {
CHIP_ERROR encodeStatus = CHIP_NO_ERROR;
for (auto & fabric : Server::GetInstance().GetFabricTable())
{
auto fabric_index = fabric.GetFabricIndex();
auto iter = provider->IterateGroupKeys(fabric_index);
VerifyOrReturnError(nullptr != iter, CHIP_ERROR_NO_MEMORY);
GroupDataProvider::GroupKey mapping;
while (iter->Next(mapping))
{
GroupKeyManagement::Structs::GroupKeyMapStruct::Type key = {
.groupId = mapping.group_id,
.groupKeySetID = mapping.keyset_id,
.fabricIndex = fabric_index,
};
encodeStatus = encoder.Encode(key);
if (encodeStatus != CHIP_NO_ERROR)
{
break;
}
}
iter->Release();
if (encodeStatus != CHIP_NO_ERROR)
{
break;
}
}
return encodeStatus;
});
return err;
}
CHIP_ERROR WriteGroupKeyMap(const ConcreteDataAttributePath & aPath, AttributeValueDecoder & aDecoder)
{
auto fabric_index = aDecoder.AccessingFabricIndex();
auto provider = GetGroupDataProvider();
if (!aPath.IsListItemOperation())
{
Attributes::GroupKeyMap::TypeInfo::DecodableType list;
size_t new_count;
VerifyOrReturnError(nullptr != provider, CHIP_ERROR_INTERNAL);
ReturnErrorOnFailure(aDecoder.Decode(list));
ReturnErrorOnFailure(list.ComputeSize(&new_count));
// Remove existing keys, ignore errors
provider->RemoveGroupKeys(fabric_index);
// Add the new keys
auto iter = list.begin();
size_t i = 0;
while (iter.Next())
{
const auto & value = iter.GetValue();
VerifyOrReturnError(fabric_index == value.fabricIndex, CHIP_ERROR_INVALID_FABRIC_INDEX);
// Cannot map to IPK, see `GroupKeyMapStruct` in Group Key Management cluster spec
VerifyOrReturnError(value.groupKeySetID != 0, CHIP_IM_GLOBAL_STATUS(ConstraintError));
ReturnErrorOnFailure(provider->SetGroupKeyAt(value.fabricIndex, i++,
GroupDataProvider::GroupKey(value.groupId, value.groupKeySetID)));
}
ReturnErrorOnFailure(iter.GetStatus());
}
else if (aPath.mListOp == ConcreteDataAttributePath::ListOperation::AppendItem)
{
Structs::GroupKeyMapStruct::DecodableType value;
size_t current_count = 0;
VerifyOrReturnError(nullptr != provider, CHIP_ERROR_INTERNAL);
ReturnErrorOnFailure(aDecoder.Decode(value));
VerifyOrReturnError(fabric_index == value.fabricIndex, CHIP_ERROR_INVALID_FABRIC_INDEX);
// Cannot map to IPK, see `GroupKeyMapStruct` in Group Key Management cluster spec
VerifyOrReturnError(value.groupKeySetID != 0, CHIP_IM_GLOBAL_STATUS(ConstraintError));
{
auto iter = provider->IterateGroupKeys(fabric_index);
current_count = iter->Count();
iter->Release();
}
ReturnErrorOnFailure(provider->SetGroupKeyAt(value.fabricIndex, current_count,
GroupDataProvider::GroupKey(value.groupId, value.groupKeySetID)));
}
else
{
return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;
}
return CHIP_NO_ERROR;
}
CHIP_ERROR ReadGroupTable(EndpointId endpoint, AttributeValueEncoder & aEncoder)
{
auto provider = GetGroupDataProvider();
VerifyOrReturnError(nullptr != provider, CHIP_ERROR_INTERNAL);
CHIP_ERROR err = aEncoder.EncodeList([provider](const auto & encoder) -> CHIP_ERROR {
CHIP_ERROR encodeStatus = CHIP_NO_ERROR;
for (auto & fabric : Server::GetInstance().GetFabricTable())
{
auto fabric_index = fabric.GetFabricIndex();
auto iter = provider->IterateGroupInfo(fabric_index);
VerifyOrReturnError(nullptr != iter, CHIP_ERROR_NO_MEMORY);
GroupDataProvider::GroupInfo info;
while (iter->Next(info))
{
encodeStatus = encoder.Encode(GroupTableCodec(provider, fabric_index, info));
if (encodeStatus != CHIP_NO_ERROR)
{
break;
}
}
iter->Release();
if (encodeStatus != CHIP_NO_ERROR)
{
break;
}
}
return encodeStatus;
});
return err;
}
CHIP_ERROR ReadMaxGroupsPerFabric(EndpointId endpoint, AttributeValueEncoder & aEncoder)
{
auto * provider = GetGroupDataProvider();
VerifyOrReturnError(nullptr != provider, CHIP_ERROR_INTERNAL);
return aEncoder.Encode(provider->GetMaxGroupsPerFabric());
}
CHIP_ERROR ReadMaxGroupKeysPerFabric(EndpointId endpoint, AttributeValueEncoder & aEncoder)
{
auto * provider = GetGroupDataProvider();
VerifyOrReturnError(nullptr != provider, CHIP_ERROR_INTERNAL);
return aEncoder.Encode(provider->GetMaxGroupKeysPerFabric());
}
};
Status
ValidateKeySetWriteArguments(const chip::app::Clusters::GroupKeyManagement::Commands::KeySetWrite::DecodableType & commandData)
{
// SPEC: If the EpochKey0 field is null or its associated EpochStartTime0 field is null, then this command SHALL fail with an
// INVALID_COMMAND status code responded to the client.
if (commandData.groupKeySet.epochKey0.IsNull() || commandData.groupKeySet.epochStartTime0.IsNull())
{
return Status::InvalidCommand;
}
// SPEC: If the EpochStartTime0 is set to 0, then this command SHALL fail with an INVALID_COMMAND status code responded to the
// client.
if (0 == commandData.groupKeySet.epochStartTime0.Value())
{
return Status::InvalidCommand;
}
// By now we at least have epochKey0.
static_assert(GroupDataProvider::EpochKey::kLengthBytes == 16,
"Expect EpochKey internal data structure to have a length of 16 bytes.");
// SPEC: If the EpochKey0 field's length is not exactly 16 bytes, then this command SHALL fail with a CONSTRAINT_ERROR status
// code responded to the client.
if (commandData.groupKeySet.epochKey0.Value().size() != GroupDataProvider::EpochKey::kLengthBytes)
{
return Status::ConstraintError;
}
// Already known to be false by now
bool epoch_key0_is_null = false;
uint64_t epoch_start_time0 = commandData.groupKeySet.epochStartTime0.Value();
bool epoch_key1_is_null = commandData.groupKeySet.epochKey1.IsNull();
bool epoch_start_time1_is_null = commandData.groupKeySet.epochStartTime1.IsNull();
uint64_t epoch_start_time1 = 0; // Will be overridden when known to be present.
// SPEC: If exactly one of the EpochKey1 or EpochStartTime1 is null, rather than both being null, or neither being null, then
// this command SHALL fail with an INVALID_COMMAND status code responded to the client.
if (epoch_key1_is_null != epoch_start_time1_is_null)
{
return Status::InvalidCommand;
}
if (!epoch_key1_is_null)
{
// SPEC: If the EpochKey1 field is not null, then the EpochKey0 field SHALL NOT be null. Otherwise this command SHALL fail
// with an INVALID_COMMAND status code responded to the client.
if (epoch_key0_is_null)
{
return Status::InvalidCommand;
}
// SPEC: If the EpochKey1 field is not null, and the field's length is not exactly 16 bytes, then this command SHALL fail
// with a CONSTRAINT_ERROR status code responded to the client.
if (commandData.groupKeySet.epochKey1.Value().size() != GroupDataProvider::EpochKey::kLengthBytes)
{
return Status::ConstraintError;
}
// By now, if EpochKey1 was present, we know EpochStartTime1 was also present.
epoch_start_time1 = commandData.groupKeySet.epochStartTime1.Value();
// SPEC: If the EpochKey1 field is not null, its associated EpochStartTime1 field SHALL NOT be null and SHALL contain a
// later epoch start time than the epoch start time found in the EpochStartTime0 field. Otherwise this command SHALL fail
// with an INVALID_COMMAND status code responded to the client.
bool epoch1_later_than_epoch0 = epoch_start_time1 > epoch_start_time0;
if (!epoch1_later_than_epoch0)
{
return Status::InvalidCommand;
}
}
bool epoch_key2_is_null = commandData.groupKeySet.epochKey2.IsNull();
bool epoch_start_time2_is_null = commandData.groupKeySet.epochStartTime2.IsNull();
// SPEC: If exactly one of the EpochKey2 or EpochStartTime2 is null, rather than both being null, or neither being null, then
// this command SHALL fail with an INVALID_COMMAND status code responded to the client.
if (epoch_key2_is_null != epoch_start_time2_is_null)
{
return Status::InvalidCommand;
}
if (!epoch_key2_is_null)
{
// SPEC: If the EpochKey2 field is not null, then the EpochKey1 and EpochKey0 fields SHALL NOT be null. Otherwise this
// command SHALL fail with an INVALID_COMMAND status code responded to the client.
if (epoch_key0_is_null || epoch_key1_is_null)
{
return Status::InvalidCommand;
}
// SPEC: If the EpochKey2 field is not null, and the field's length is not exactly 16 bytes, then this command SHALL fail
// with a CONSTRAINT_ERROR status code responded to the client.
if (commandData.groupKeySet.epochKey2.Value().size() != GroupDataProvider::EpochKey::kLengthBytes)
{
return Status::ConstraintError;
}
// By now, if EpochKey2 was present, we know EpochStartTime2 was also present.
uint64_t epoch_start_time2 = commandData.groupKeySet.epochStartTime2.Value();
// SPEC: If the EpochKey2 field is not null, its associated EpochStartTime2 field SHALL NOT be null and SHALL contain a
// later epoch start time than the epoch start time found in the EpochStartTime1 field. Otherwise this command SHALL fail
// with an INVALID_COMMAND status code responded to the client.
bool epoch2_later_than_epoch1 = epoch_start_time2 > epoch_start_time1;
if (!epoch2_later_than_epoch1)
{
return Status::InvalidCommand;
}
}
return Status::Success;
}
bool GetProviderAndFabric(chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath,
Credentials::GroupDataProvider ** outGroupDataProvider, const FabricInfo ** outFabricInfo)
{
VerifyOrDie(commandObj != nullptr);
VerifyOrDie(outGroupDataProvider != nullptr);
VerifyOrDie(outFabricInfo != nullptr);
// Internal failures on internal inconsistencies.
auto provider = GetGroupDataProvider();
auto fabric = Server::GetInstance().GetFabricTable().FindFabricWithIndex(commandObj->GetAccessingFabricIndex());
if (nullptr == provider)
{
commandObj->AddStatus(commandPath, Status::Failure, "Internal consistency error on provider!");
return false;
}
if (nullptr == fabric)
{
commandObj->AddStatus(commandPath, Status::Failure, "Internal consistency error on access fabric!");
return false;
}
*outGroupDataProvider = provider;
*outFabricInfo = fabric;
return true;
}
GroupKeyManagementAttributeAccess gAttribute;
} // anonymous namespace
void MatterGroupKeyManagementPluginServerInitCallback()
{
AttributeAccessInterfaceRegistry::Instance().Register(&gAttribute);
}
//
// Commands
//
bool emberAfGroupKeyManagementClusterKeySetWriteCallback(
chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath,
const chip::app::Clusters::GroupKeyManagement::Commands::KeySetWrite::DecodableType & commandData)
{
Credentials::GroupDataProvider * provider = nullptr;
const FabricInfo * fabric = nullptr;
if (!GetProviderAndFabric(commandObj, commandPath, &provider, &fabric))
{
// Command will already have status populated from validation.
return true;
}
// Pre-validate all complex data dependency assumptions about the epoch keys
Status status = ValidateKeySetWriteArguments(commandData);
if (status != Status::Success)
{
commandObj->AddStatus(commandPath, status, "Failure to validate KeySet data dependencies.");
return true;
}
if (commandData.groupKeySet.groupKeySecurityPolicy == GroupKeySecurityPolicyEnum::kUnknownEnumValue)
{
// If a client indicates an enumeration value to the server, that is not
// supported by the server, because it is ... a new value unrecognized
// by a legacy server, then the server SHALL generate a general
// constraint error
commandObj->AddStatus(commandPath, Status::ConstraintError, "Received unknown GroupKeySecurityPolicyEnum value");
return true;
}
if (!GroupKeyManagementAttributeAccess::IsMCSPSupported() &&
commandData.groupKeySet.groupKeySecurityPolicy == GroupKeySecurityPolicyEnum::kCacheAndSync)
{
// When CacheAndSync is not supported in the FeatureMap of this cluster,
// any action attempting to set CacheAndSync in the
// GroupKeySecurityPolicy field SHALL fail with an INVALID_COMMAND
// error.
commandObj->AddStatus(commandPath, Status::InvalidCommand,
"Received a CacheAndSync GroupKeySecurityPolicyEnum when MCSP not supported");
return true;
}
// All flight checks completed: by now we know that non-null keys are all valid and correct size.
bool epoch_key1_present = !commandData.groupKeySet.epochKey1.IsNull();
bool epoch_key2_present = !commandData.groupKeySet.epochKey2.IsNull();
GroupDataProvider::KeySet keyset(commandData.groupKeySet.groupKeySetID, commandData.groupKeySet.groupKeySecurityPolicy, 0);
// Epoch Key 0 always present
keyset.epoch_keys[0].start_time = commandData.groupKeySet.epochStartTime0.Value();
memcpy(keyset.epoch_keys[0].key, commandData.groupKeySet.epochKey0.Value().data(), GroupDataProvider::EpochKey::kLengthBytes);
keyset.num_keys_used++;
// Epoch Key 1
if (epoch_key1_present)
{
keyset.epoch_keys[1].start_time = commandData.groupKeySet.epochStartTime1.Value();
memcpy(keyset.epoch_keys[1].key, commandData.groupKeySet.epochKey1.Value().data(),
GroupDataProvider::EpochKey::kLengthBytes);
keyset.num_keys_used++;
}
// Epoch Key 2
if (epoch_key2_present)
{
keyset.epoch_keys[2].start_time = commandData.groupKeySet.epochStartTime2.Value();
memcpy(keyset.epoch_keys[2].key, commandData.groupKeySet.epochKey2.Value().data(),
GroupDataProvider::EpochKey::kLengthBytes);
keyset.num_keys_used++;
}
uint8_t compressed_fabric_id_buffer[sizeof(uint64_t)];
MutableByteSpan compressed_fabric_id(compressed_fabric_id_buffer);
CHIP_ERROR err = fabric->GetCompressedFabricIdBytes(compressed_fabric_id);
if (CHIP_NO_ERROR != err)
{
commandObj->AddStatus(commandPath, Status::Failure);
return true;
}
// Set KeySet
err = provider->SetKeySet(fabric->GetFabricIndex(), compressed_fabric_id, keyset);
if (CHIP_ERROR_INVALID_LIST_LENGTH == err)
{
commandObj->AddStatus(commandPath, Status::ResourceExhausted, "Not enough space left to add a new KeySet");
return true;
}
if (CHIP_NO_ERROR == err)
{
ChipLogDetail(Zcl, "GroupKeyManagementCluster: KeySetWrite OK");
}
else
{
ChipLogDetail(Zcl, "GroupKeyManagementCluster: KeySetWrite: %" CHIP_ERROR_FORMAT, err.Format());
}
// Send response
commandObj->AddStatus(commandPath, StatusIB(err).mStatus);
return true;
}
bool emberAfGroupKeyManagementClusterKeySetReadCallback(
chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath,
const chip::app::Clusters::GroupKeyManagement::Commands::KeySetRead::DecodableType & commandData)
{
Credentials::GroupDataProvider * provider = nullptr;
const FabricInfo * fabric = nullptr;
if (!GetProviderAndFabric(commandObj, commandPath, &provider, &fabric))
{
// Command will already have status populated from validation.
return true;
}
FabricIndex fabricIndex = fabric->GetFabricIndex();
GroupDataProvider::KeySet keyset;
if (CHIP_NO_ERROR != provider->GetKeySet(fabricIndex, commandData.groupKeySetID, keyset))
{
// KeySet ID not found
commandObj->AddStatus(commandPath, Status::NotFound, "Keyset ID not found in KeySetRead");
return true;
}
// In KeySetReadResponse, EpochKey0, EpochKey1 and EpochKey2 key contents shall be null
GroupKeyManagement::Commands::KeySetReadResponse::Type response;
response.groupKeySet.groupKeySetID = keyset.keyset_id;
response.groupKeySet.groupKeySecurityPolicy = keyset.policy;
// Keyset 0
if (keyset.num_keys_used > 0)
{
response.groupKeySet.epochStartTime0.SetNonNull(keyset.epoch_keys[0].start_time);
}
else
{
response.groupKeySet.epochStartTime0.SetNull();
}
response.groupKeySet.epochKey0.SetNull();
// Keyset 1
if (keyset.num_keys_used > 1)
{
response.groupKeySet.epochStartTime1.SetNonNull(keyset.epoch_keys[1].start_time);
}
else
{
response.groupKeySet.epochStartTime1.SetNull();
}
response.groupKeySet.epochKey1.SetNull();
// Keyset 2
if (keyset.num_keys_used > 2)
{
response.groupKeySet.epochStartTime2.SetNonNull(keyset.epoch_keys[2].start_time);
}
else
{
response.groupKeySet.epochStartTime2.SetNull();
}
response.groupKeySet.epochKey2.SetNull();
commandObj->AddResponse(commandPath, response);
return true;
}
bool emberAfGroupKeyManagementClusterKeySetRemoveCallback(
chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath,
const chip::app::Clusters::GroupKeyManagement::Commands::KeySetRemove::DecodableType & commandData)
{
Credentials::GroupDataProvider * provider = nullptr;
const FabricInfo * fabric = nullptr;
if (!GetProviderAndFabric(commandObj, commandPath, &provider, &fabric))
{
// Command will already have status populated from validation.
return true;
}
if (commandData.groupKeySetID == GroupDataProvider::kIdentityProtectionKeySetId)
{
// SPEC: This command SHALL fail with an INVALID_COMMAND status code back to the initiator if the GroupKeySetID being
// removed is 0, which is the Key Set associated with the Identity Protection Key (IPK).
commandObj->AddStatus(commandPath, Status::InvalidCommand, "Attempted to KeySetRemove the identity protection key!");
return true;
}
// Remove keyset
FabricIndex fabricIndex = fabric->GetFabricIndex();
CHIP_ERROR err = provider->RemoveKeySet(fabricIndex, commandData.groupKeySetID);
Status status = Status::Success;
if (CHIP_ERROR_NOT_FOUND == err || CHIP_ERROR_KEY_NOT_FOUND == err)
{
status = Status::NotFound;
}
else if (CHIP_NO_ERROR != err)
{
status = Status::Failure;
}
// Send status response.
commandObj->AddStatus(commandPath, status, "KeySetRemove failed");
return true;
}
struct KeySetReadAllIndicesResponse
{
static constexpr CommandId GetCommandId() { return GroupKeyManagement::Commands::KeySetReadAllIndicesResponse::Id; }
static constexpr ClusterId GetClusterId() { return GroupKeyManagement::Id; }
GroupDataProvider::KeySetIterator * mIterator = nullptr;
KeySetReadAllIndicesResponse(GroupDataProvider::KeySetIterator * iter) : mIterator(iter) {}
CHIP_ERROR Encode(TLV::TLVWriter & writer, TLV::Tag tag) const
{
TLV::TLVType outer;
ReturnErrorOnFailure(writer.StartContainer(tag, TLV::kTLVType_Structure, outer));
TLV::TLVType array;
ReturnErrorOnFailure(writer.StartContainer(
TLV::ContextTag(GroupKeyManagement::Commands::KeySetReadAllIndicesResponse::Fields::kGroupKeySetIDs),
TLV::kTLVType_Array, array));
GroupDataProvider::KeySet keyset;
while (mIterator && mIterator->Next(keyset))
{
ReturnErrorOnFailure(app::DataModel::Encode(writer, TLV::AnonymousTag(), keyset.keyset_id));
}
ReturnErrorOnFailure(writer.EndContainer(array));
ReturnErrorOnFailure(writer.EndContainer(outer));
return CHIP_NO_ERROR;
}
};
bool emberAfGroupKeyManagementClusterKeySetReadAllIndicesCallback(
chip::app::CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath,
const chip::app::Clusters::GroupKeyManagement::Commands::KeySetReadAllIndices::DecodableType & commandData)
{
Credentials::GroupDataProvider * provider = nullptr;
const FabricInfo * fabric = nullptr;
if (!GetProviderAndFabric(commandObj, commandPath, &provider, &fabric))
{
// Command will already have status populated from validation.
return true;
}
FabricIndex fabricIndex = fabric->GetFabricIndex();
auto keysIt = provider->IterateKeySets(fabricIndex);
if (nullptr == keysIt)
{
commandObj->AddStatus(commandPath, Status::Failure, "Failed iteration of key set indices!");
return true;
}
commandObj->AddResponse(commandPath, KeySetReadAllIndicesResponse(keysIt));
keysIt->Release();
return true;
}