Line data Source code
1 : /*
2 : *
3 : * Copyright (c) 2021-2022 Project CHIP Authors
4 : *
5 : * Licensed under the Apache License, Version 2.0 (the "License");
6 : * you may not use this file except in compliance with the License.
7 : * You may obtain a copy of the License at
8 : *
9 : * http://www.apache.org/licenses/LICENSE-2.0
10 : *
11 : * Unless required by applicable law or agreed to in writing, software
12 : * distributed under the License is distributed on an "AS IS" BASIS,
13 : * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 : * See the License for the specific language governing permissions and
15 : * limitations under the License.
16 : */
17 : #pragma once
18 :
19 : #include <optional>
20 : #include <stdint.h>
21 : #include <sys/types.h>
22 :
23 : #include <app/util/basic-types.h>
24 : #include <crypto/CHIPCryptoPAL.h>
25 : #include <lib/core/CHIPError.h>
26 : #include <lib/core/ClusterEnums.h>
27 : #include <lib/support/CHIPMemString.h>
28 : #include <lib/support/CommonIterator.h>
29 :
30 : namespace chip {
31 : namespace Credentials {
32 :
33 : class GroupDataProvider
34 : {
35 : public:
36 : using SecurityPolicy = app::Clusters::GroupKeyManagement::GroupKeySecurityPolicyEnum;
37 : static constexpr KeysetId kIdentityProtectionKeySetId = 0;
38 : static constexpr size_t kMaxListeners = 2;
39 :
40 : struct GroupInfo
41 : {
42 : static constexpr size_t kGroupNameMax = CHIP_CONFIG_MAX_GROUP_NAME_LENGTH;
43 : enum class Flags : uint8_t
44 : {
45 : kHasAuxiliaryACL = 0b00000001,
46 : kMcastAddrPolicy = 0b00000010,
47 : };
48 : static constexpr uint8_t kFlagsDefault = to_underlying(GroupInfo::Flags::kMcastAddrPolicy);
49 :
50 : // Identifies group within the scope of the given Fabric
51 : GroupId group_id = kUndefinedGroupId;
52 : // Lastest group name written for a given GroupId on any Endpoint via the Groups cluster
53 : char name[kGroupNameMax + 1] = { 0 };
54 : uint8_t flags = kFlagsDefault;
55 : uint16_t count = 0;
56 :
57 2939 : GroupInfo() { SetName(nullptr); }
58 6 : GroupInfo(const GroupInfo & other) { Copy(other); }
59 2374 : GroupInfo(const char * groupName) { SetName(groupName); }
60 : GroupInfo(const CharSpan & groupName) { SetName(groupName); }
61 5842 : GroupInfo(GroupId id, const char * groupName, uint8_t groupFlags = kFlagsDefault) : group_id(id), flags(groupFlags)
62 : {
63 5842 : SetName(groupName);
64 5842 : }
65 33 : GroupInfo(GroupId id, const CharSpan & groupName, uint8_t groupFlags = kFlagsDefault) : group_id(id), flags(groupFlags)
66 : {
67 33 : SetName(groupName);
68 33 : }
69 16051 : void SetName(const char * groupName)
70 : {
71 16051 : if (nullptr == groupName)
72 : {
73 10957 : name[0] = 0;
74 : }
75 : else
76 : {
77 5094 : Platform::CopyString(name, groupName);
78 : }
79 16051 : }
80 8970 : void SetName(const CharSpan & groupName)
81 : {
82 8970 : if (nullptr == groupName.data())
83 : {
84 8938 : name[0] = 0;
85 : }
86 : else
87 : {
88 32 : Platform::CopyString(name, groupName);
89 : }
90 8970 : }
91 4888 : void Copy(const GroupInfo & other)
92 : {
93 4888 : if (this != &other)
94 : {
95 4888 : group_id = other.group_id;
96 4888 : flags = other.flags;
97 4888 : SetName(other.name);
98 : }
99 4888 : }
100 1122 : bool HasAuxiliaryACL() const { return (flags & static_cast<uint8_t>(Flags::kHasAuxiliaryACL)); }
101 4023 : bool UsePerGroupAddress() const { return (flags & static_cast<uint8_t>(Flags::kMcastAddrPolicy)); }
102 :
103 32 : bool operator==(const GroupInfo & other) const
104 : {
105 32 : return (this->group_id == other.group_id) && !strncmp(this->name, other.name, kGroupNameMax);
106 : }
107 1 : GroupInfo & operator=(const GroupInfo & other)
108 : {
109 1 : Copy(other);
110 1 : return *this;
111 : }
112 : };
113 :
114 : struct GroupKey
115 : {
116 68 : GroupKey() = default;
117 1062 : GroupKey(GroupId group, KeysetId keyset) : group_id(group), keyset_id(keyset) {}
118 : // Identifies group within the scope of the given Fabric
119 : GroupId group_id = kUndefinedGroupId;
120 : // Set of group keys that generate operational group keys for use with this group
121 : KeysetId keyset_id = 0;
122 28 : bool operator==(const GroupKey & other) const
123 : {
124 28 : return this->group_id == other.group_id && this->keyset_id == other.keyset_id;
125 : }
126 : };
127 :
128 : struct GroupEndpoint
129 : {
130 1427 : GroupEndpoint() = default;
131 2205 : GroupEndpoint(GroupId group, EndpointId endpoint) : group_id(group), endpoint_id(endpoint) {}
132 : // Identifies group within the scope of the given Fabric
133 : GroupId group_id = kUndefinedGroupId;
134 : // Endpoint on the Node to which messages to this group may be forwarded
135 : EndpointId endpoint_id = kInvalidEndpointId;
136 :
137 : bool operator==(const GroupEndpoint & other) const
138 : {
139 : return this->group_id == other.group_id && this->endpoint_id == other.endpoint_id;
140 : }
141 : };
142 :
143 : struct GroupSession
144 : {
145 9 : GroupSession() = default;
146 : GroupId group_id = kUndefinedGroupId;
147 : FabricIndex fabric_index;
148 : SecurityPolicy security_policy;
149 : Crypto::SymmetricKeyContext * keyContext = nullptr;
150 : };
151 :
152 : // An EpochKey is a single key usable to determine an operational group key
153 : struct EpochKey
154 : {
155 : static constexpr size_t kLengthBytes = Crypto::CHIP_CRYPTO_SYMMETRIC_KEY_LENGTH_BYTES;
156 : // Validity start time in microseconds since 2000-01-01T00:00:00 UTC ("the Epoch")
157 : uint64_t start_time;
158 : // Actual key bits. Depending on context, it may be a raw epoch key (as seen within `SetKeySet` calls)
159 : // or it may be the derived operational group key (as seen in any other usage).
160 : uint8_t key[kLengthBytes];
161 :
162 513 : void Clear()
163 : {
164 513 : start_time = 0;
165 513 : Crypto::ClearSecretData(&key[0], sizeof(key));
166 513 : }
167 : };
168 :
169 : // A operational group key set, usable by many GroupState mappings
170 : struct KeySet
171 : {
172 : static constexpr size_t kEpochKeysMax = 3;
173 :
174 198 : KeySet() = default;
175 210 : KeySet(uint16_t id, SecurityPolicy policy_id, uint8_t num_keys) : keyset_id(id), policy(policy_id), num_keys_used(num_keys)
176 210 : {}
177 :
178 : // The actual keys for the group key set
179 : EpochKey epoch_keys[kEpochKeysMax];
180 : // Logical id provided by the Administrator that configured the entry
181 : uint16_t keyset_id = 0;
182 : // Security policy to use for groups that use this keyset
183 : SecurityPolicy policy = SecurityPolicy::kCacheAndSync;
184 : // Number of keys present
185 : uint8_t num_keys_used = 0;
186 :
187 : bool operator==(const KeySet & other) const
188 : {
189 : VerifyOrReturnError(this->policy == other.policy && this->num_keys_used == other.num_keys_used, false);
190 : return !memcmp(this->epoch_keys, other.epoch_keys, this->num_keys_used * sizeof(EpochKey));
191 : }
192 :
193 144 : void ClearKeys()
194 : {
195 576 : for (size_t key_idx = 0; key_idx < kEpochKeysMax; ++key_idx)
196 : {
197 432 : epoch_keys[key_idx].Clear();
198 : }
199 144 : }
200 : };
201 :
202 : /**
203 : * Interface to listen for changes in the Group info.
204 : */
205 : class GroupListener
206 : {
207 : public:
208 168 : virtual ~GroupListener() = default;
209 : /**
210 : * Callback invoked when a new group is added.
211 : *
212 : * @param[in] new_group GroupInfo structure of the new group.
213 : */
214 : virtual void OnGroupAdded(FabricIndex fabric_index, const GroupInfo & new_group) = 0;
215 : /**
216 : * Callback invoked when an existing group is removed.
217 : *
218 : * @param[in] old_group GroupInfo structure of the removed group.
219 : */
220 : virtual void OnGroupRemoved(FabricIndex fabric_index, const GroupInfo & old_group) = 0;
221 : /**
222 : * Callback invoked when an existing group is modified.
223 : * The modifications may be any of the following:
224 : * - Endpoints List modified
225 : * - KeySetID modified
226 : * - Flags modified (kHasAuxiliaryACL or kMcastAddrPolicy)
227 : *
228 : * Note that this callback is not invoked when the group is added or removed.
229 : * Those events are handled by the OnGroupAdded and OnGroupRemoved callbacks respectively.
230 : *
231 : * @param[in] modified_group_id ID of the modified group.
232 : */
233 84 : virtual void OnGroupModified(FabricIndex fabric_index, const GroupId & modified_group_id){};
234 : };
235 :
236 : using GroupInfoIterator = CommonIterator<GroupInfo>;
237 : using GroupKeyIterator = CommonIterator<GroupKey>;
238 : using EndpointIterator = CommonIterator<GroupEndpoint>;
239 : using KeySetIterator = CommonIterator<KeySet>;
240 : using GroupSessionIterator = CommonIterator<GroupSession>;
241 :
242 97 : GroupDataProvider(uint16_t maxGroupsPerFabric, uint16_t maxGroupKeysPerFabric) :
243 97 : mMaxGroupsPerFabric(maxGroupsPerFabric), mMaxGroupKeysPerFabric(maxGroupKeysPerFabric)
244 97 : {}
245 :
246 : enum class GroupCleanupPolicy
247 : {
248 : kDeleteGroupIfEmpty, // Default behavior for legacy Groups
249 : kKeepGroupIfEmpty // Required for Groupcast Sender feature
250 : };
251 :
252 97 : virtual ~GroupDataProvider() = default;
253 :
254 : // Not copyable
255 : GroupDataProvider(const GroupDataProvider &) = delete;
256 : GroupDataProvider & operator=(const GroupDataProvider &) = delete;
257 :
258 133 : uint16_t GetMaxGroupsPerFabric() const { return mMaxGroupsPerFabric; }
259 8 : uint16_t GetMaxGroupKeysPerFabric() const { return mMaxGroupKeysPerFabric; }
260 :
261 : /**
262 : * Initialize the GroupDataProvider, including possibly any persistent
263 : * data store initialization done by the implementation. Must be called once
264 : * before any other API succeeds.
265 : *
266 : * @retval #CHIP_ERROR_INCORRECT_STATE if called when already initialized.
267 : * @retval #CHIP_NO_ERROR on success
268 : */
269 : virtual CHIP_ERROR Init() = 0;
270 : virtual void Finish() = 0;
271 :
272 : //
273 : // Group Table
274 : //
275 :
276 : // By id
277 : virtual CHIP_ERROR SetGroupInfo(FabricIndex fabric_index, const GroupInfo & info) = 0;
278 : virtual CHIP_ERROR GetGroupInfo(FabricIndex fabric_index, GroupId group_id, GroupInfo & info) = 0;
279 : virtual CHIP_ERROR RemoveGroupInfo(FabricIndex fabric_index, GroupId group_id) = 0;
280 : // By index
281 : virtual CHIP_ERROR SetGroupInfoAt(FabricIndex fabric_index, size_t index, const GroupInfo & info) = 0;
282 : virtual CHIP_ERROR GetGroupInfoAt(FabricIndex fabric_index, size_t index, GroupInfo & info) = 0;
283 : virtual CHIP_ERROR RemoveGroupInfoAt(FabricIndex fabric_index, size_t index) = 0;
284 : // Endpoints
285 : virtual bool HasEndpoint(FabricIndex fabric_index, GroupId group_id, EndpointId endpoint_id) = 0;
286 : virtual CHIP_ERROR AddEndpoint(FabricIndex fabric_index, GroupId group_id, EndpointId endpoint_id) = 0;
287 : virtual CHIP_ERROR RemoveEndpoint(FabricIndex fabric_index, GroupId group_id, EndpointId endpoint_id,
288 : GroupCleanupPolicy cleanupPolicy) = 0;
289 : virtual CHIP_ERROR RemoveEndpointAllGroups(FabricIndex fabric_index, EndpointId endpoint_id,
290 : GroupCleanupPolicy cleanupPolicy) = 0;
291 : virtual CHIP_ERROR RemoveEndpoint(FabricIndex fabric_index, GroupId group_id, EndpointId endpoint_id) = 0;
292 : virtual CHIP_ERROR RemoveEndpoint(FabricIndex fabric_index, EndpointId endpoint_id) = 0;
293 : virtual CHIP_ERROR RemoveEndpoints(FabricIndex fabric_index, GroupId group_id) = 0;
294 : // Iterators
295 : /**
296 : * Creates an iterator that may be used to obtain the list of groups associated with the given fabric.
297 : * In order to release the allocated memory, the Release() method must be called after the iteration is finished.
298 : * Modifying the group table during the iteration is currently not supported, and may yield unexpected behaviour.
299 : * @retval An instance of EndpointIterator on success
300 : * @retval nullptr if no iterator instances are available.
301 : */
302 : virtual GroupInfoIterator * IterateGroupInfo(FabricIndex fabric_index) = 0;
303 : /**
304 : * Creates an iterator that may be used to obtain the list of (group, endpoint) pairs associated with the given fabric.
305 : * In order to release the allocated memory, the Release() method must be called after the iteration is finished.
306 : * Modifying the group table during the iteration is currently not supported, and may yield unexpected behaviour.
307 : * If you wish to iterate only the endpoints of a particular group id you can provide the optional `group_id` to do so.
308 : * @retval An instance of EndpointIterator on success
309 : * @retval nullptr if no iterator instances are available.
310 : */
311 : virtual EndpointIterator * IterateEndpoints(FabricIndex fabric_index, std::optional<GroupId> group_id = std::nullopt) = 0;
312 :
313 : //
314 : // Group-Key map
315 : //
316 :
317 : virtual CHIP_ERROR SetGroupKey(FabricIndex fabric_index, GroupId group_id, KeysetId keyset_id) = 0;
318 : virtual CHIP_ERROR SetGroupKeyAt(FabricIndex fabric_index, size_t index, const GroupKey & info) = 0;
319 : virtual CHIP_ERROR GetGroupKey(FabricIndex fabric_index, GroupId group_id, KeysetId & keyset_id) = 0;
320 : virtual CHIP_ERROR GetGroupKeyAt(FabricIndex fabric_index, size_t index, GroupKey & info) = 0;
321 : virtual CHIP_ERROR RemoveGroupKeyAt(FabricIndex fabric_index, size_t index) = 0;
322 : virtual CHIP_ERROR RemoveGroupKeys(FabricIndex fabric_index) = 0;
323 :
324 : /**
325 : * Creates an iterator that may be used to obtain the list of (group, keyset) pairs associated with the given fabric.
326 : * In order to release the allocated memory, the Release() method must be called after the iteration is finished.
327 : * Modifying the keyset mappings during the iteration is currently not supported, and may yield unexpected behaviour.
328 : * @retval An instance of GroupKeyIterator on success
329 : * @retval nullptr if no iterator instances are available.
330 : */
331 : virtual GroupKeyIterator * IterateGroupKeys(FabricIndex fabric_index) = 0;
332 :
333 : //
334 : // Key Sets
335 : //
336 :
337 : virtual CHIP_ERROR SetKeySet(FabricIndex fabric_index, const ByteSpan & compressed_fabric_id, const KeySet & keys) = 0;
338 : virtual CHIP_ERROR GetKeySet(FabricIndex fabric_index, KeysetId keyset_id, KeySet & keys) = 0;
339 : virtual CHIP_ERROR RemoveKeySet(FabricIndex fabric_index, KeysetId keyset_id) = 0;
340 :
341 : /**
342 : * @brief Obtain the actual operational Identity Protection Key (IPK) keyset for a given
343 : * fabric. These keys are used by the CASE protocol, and do not participate in
344 : * any direct traffic encryption. Since the identity protection operational keyset
345 : * is used in multiple key derivations and procedures, it cannot be hidden behind a
346 : * SymmetricKeyContext, and must be obtainable by value.
347 : *
348 : * @param fabric_index - Fabric index for which to get the IPK operational keyset
349 : * @param out_keyset - Reference to a KeySet where the IPK keys will be stored on success
350 : * @return CHIP_NO_ERROR on success, CHIP_ERROR_NOT_FOUND if the IPK keyset is somehow unavailable
351 : * or another CHIP_ERROR value if an internal storage error occurs.
352 : */
353 : virtual CHIP_ERROR GetIpkKeySet(FabricIndex fabric_index, KeySet & out_keyset) = 0;
354 :
355 : /**
356 : * Creates an iterator that may be used to obtain the list of key sets associated with the given fabric.
357 : * In order to release the allocated memory, the Release() method must be called after the iteration is finished.
358 : * Modifying the key sets table during the iteration is currently not supported, and may yield unexpected behaviour.
359 : *
360 : * @retval An instance of KeySetIterator on success
361 : * @retval nullptr if no iterator instances are available.
362 : */
363 : virtual KeySetIterator * IterateKeySets(FabricIndex fabric_index) = 0;
364 :
365 : // Fabrics
366 : virtual CHIP_ERROR RemoveFabric(FabricIndex fabric_index) = 0;
367 :
368 : // Decryption
369 : virtual GroupSessionIterator * IterateGroupSessions(uint16_t session_id) = 0;
370 : virtual Crypto::SymmetricKeyContext * GetKeyContext(FabricIndex fabric_index, GroupId group_id) = 0;
371 :
372 : // Listener
373 35 : void SetListener(GroupListener * listener)
374 : {
375 53 : for (size_t i = 0; listener && (i < kMaxListeners); ++i)
376 : {
377 52 : if (nullptr == mListeners[i])
378 : {
379 34 : mListeners[i] = listener;
380 34 : return;
381 : }
382 : }
383 : }
384 33 : void RemoveListener(GroupListener * listener)
385 : {
386 51 : for (size_t i = 0; listener && (i < kMaxListeners); ++i)
387 : {
388 50 : if (listener == mListeners[i])
389 : {
390 32 : mListeners[i] = nullptr;
391 32 : return;
392 : }
393 : }
394 : }
395 :
396 17 : void SetGroupcastEnabled(bool groupcastVal) { mGroupcastEnabled = groupcastVal; }
397 :
398 1492 : bool IsGroupcastEnabled() { return mGroupcastEnabled; }
399 :
400 : // Groupcast
401 : virtual uint16_t getMaxMembershipCount() = 0;
402 : virtual uint16_t getMaxMcastAddrCount() = 0;
403 :
404 : /**
405 : * @brief Check if a notification is needed for Auxiliary ACL changes and reset the flag.
406 : *
407 : * This method returns true if the last set of operations (e.g., SetGroupInfo, RemoveGroupInfo)
408 : * somehow changed the Auxiliary ACL status of a group. Calling this method resets the internal flag.
409 : *
410 : * @return true if a notification is needed, false otherwise.
411 : */
412 : virtual bool ConsumeAuxAclNotificationNeeded() = 0;
413 :
414 : protected:
415 317 : void GroupAdded(FabricIndex fabric_index, const GroupInfo & new_group)
416 : {
417 951 : for (auto * listener : mListeners)
418 : {
419 634 : if (listener != nullptr)
420 : {
421 146 : listener->OnGroupAdded(fabric_index, new_group);
422 : }
423 : }
424 317 : }
425 67 : void GroupRemoved(FabricIndex fabric_index, const GroupInfo & old_group)
426 : {
427 201 : for (auto * listener : mListeners)
428 : {
429 134 : if (listener != nullptr)
430 : {
431 68 : listener->OnGroupRemoved(fabric_index, old_group);
432 : }
433 : }
434 67 : }
435 1642 : void GroupModified(FabricIndex fabric_index, const GroupId & modified_group_id)
436 : {
437 4926 : for (auto * listener : mListeners)
438 : {
439 3284 : if (listener != nullptr)
440 : {
441 2280 : listener->OnGroupModified(fabric_index, modified_group_id);
442 : }
443 : }
444 1642 : }
445 : const uint16_t mMaxGroupsPerFabric;
446 : const uint16_t mMaxGroupKeysPerFabric;
447 : GroupListener * mListeners[kMaxListeners] = { nullptr };
448 : bool mGroupcastEnabled = false;
449 : };
450 :
451 : /**
452 : * @brief Utility Set the IPK Epoch key on a GroupDataProvider assuming a single IPK
453 : *
454 : * This utility replaces having to call `GroupDataProvider::SetKeySet` for the simple situation of a
455 : * single IPK for a fabric, if a single epoch key is used. Start time will be set to 0 ("was always valid")
456 : *
457 : * @param provider - pointer to GroupDataProvider on which to set the IPK
458 : * @param fabric_index - fabric index within the GroupDataProvider for which to set the IPK
459 : * @param ipk_epoch_span - Span containing the IPK epoch key
460 : * @param compressed_fabric_id - Compressed fabric ID associated with the fabric, for key derivation
461 : * @return CHIP_NO_ERROR on success, CHIP_ERROR_INVALID_ARGUMENT on any bad argument, other CHIP_ERROR values
462 : * from implementation on other errors
463 : */
464 1 : inline CHIP_ERROR SetSingleIpkEpochKey(GroupDataProvider * provider, FabricIndex fabric_index, const ByteSpan & ipk_epoch_span,
465 : const ByteSpan & compressed_fabric_id)
466 : {
467 : GroupDataProvider::KeySet ipkKeySet(GroupDataProvider::kIdentityProtectionKeySetId,
468 1 : GroupDataProvider::SecurityPolicy::kTrustFirst, 1);
469 :
470 1 : VerifyOrReturnError(provider != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
471 1 : VerifyOrReturnError(ipk_epoch_span.size() == sizeof(ipkKeySet.epoch_keys[0].key), CHIP_ERROR_INVALID_ARGUMENT);
472 1 : VerifyOrReturnError(compressed_fabric_id.size() == sizeof(uint64_t), CHIP_ERROR_INVALID_ARGUMENT);
473 :
474 1 : ipkKeySet.epoch_keys[0].start_time = 0;
475 1 : memcpy(&ipkKeySet.epoch_keys[0].key, ipk_epoch_span.data(), ipk_epoch_span.size());
476 :
477 : // Set a single IPK, validate key derivation follows spec
478 1 : return provider->SetKeySet(fabric_index, compressed_fabric_id, ipkKeySet);
479 : }
480 :
481 : /**
482 : * Instance getter for the global GroupDataProvider.
483 : *
484 : * Callers have to externally synchronize usage of this function.
485 : *
486 : * @return The global Group Data Provider
487 : */
488 : GroupDataProvider * GetGroupDataProvider();
489 :
490 : /**
491 : * Instance setter for the global GroupDataProvider.
492 : *
493 : * Callers have to externally synchronize usage of this function.
494 : *
495 : * The `provider` can be set to nullptr if the owner is done with it fully.
496 : *
497 : * @param[in] provider pointer to the Group Data Provider global isntance to use
498 : */
499 : void SetGroupDataProvider(GroupDataProvider * provider);
500 :
501 : } // namespace Credentials
502 : } // namespace chip
|