Line data Source code
1 : /*
2 : *
3 : * Copyright (c) 2020 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 :
18 : #pragma once
19 :
20 : #include <app/AppConfig.h>
21 : #include <app/icd/server/ICDServerConfig.h>
22 :
23 : #include <access/AccessControl.h>
24 : #include <access/examples/ExampleAccessControlDelegate.h>
25 : #include <app/CASEClientPool.h>
26 : #include <app/CASESessionManager.h>
27 : #include <app/DefaultSafeAttributePersistenceProvider.h>
28 : #include <app/FailSafeContext.h>
29 : #include <app/OperationalSessionSetupPool.h>
30 : #include <app/SimpleSubscriptionResumptionStorage.h>
31 : #include <app/TestEventTriggerDelegate.h>
32 : #include <app/server/AclStorage.h>
33 : #include <app/server/AppDelegate.h>
34 : #include <app/server/CommissioningWindowManager.h>
35 : #include <app/server/DefaultAclStorage.h>
36 : #include <app/server/JointFabricDatastore.h>
37 : #include <credentials/CertificateValidityPolicy.h>
38 : #include <credentials/FabricTable.h>
39 : #include <credentials/GroupDataProvider.h>
40 : #include <credentials/GroupDataProviderImpl.h>
41 : #include <credentials/OperationalCertificateStore.h>
42 : #include <credentials/PersistentStorageOpCertStore.h>
43 : #include <crypto/DefaultSessionKeystore.h>
44 : #include <crypto/OperationalKeystore.h>
45 : #include <crypto/PersistentStorageOperationalKeystore.h>
46 : #include <inet/InetConfig.h>
47 : #include <lib/core/CHIPConfig.h>
48 : #include <lib/support/SafeInt.h>
49 : #include <messaging/ExchangeMgr.h>
50 : #include <platform/DeviceInstanceInfoProvider.h>
51 : #include <platform/KeyValueStoreManager.h>
52 : #include <platform/KvsPersistentStorageDelegate.h>
53 : #include <protocols/secure_channel/CASEServer.h>
54 : #include <protocols/secure_channel/MessageCounterManager.h>
55 : #include <protocols/secure_channel/PASESession.h>
56 : #include <protocols/secure_channel/RendezvousParameters.h>
57 : #include <protocols/secure_channel/UnsolicitedStatusHandler.h>
58 : #if CHIP_CONFIG_ENABLE_SESSION_RESUMPTION
59 : #include <protocols/secure_channel/SimpleSessionResumptionStorage.h>
60 : #endif
61 : #include <protocols/user_directed_commissioning/UserDirectedCommissioning.h>
62 : #include <system/SystemClock.h>
63 : #include <transport/SessionManager.h>
64 : #include <transport/TransportMgr.h>
65 : #include <transport/TransportMgrBase.h>
66 : #if CONFIG_NETWORK_LAYER_BLE
67 : #include <transport/raw/BLE.h>
68 : #endif
69 : #if CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
70 : #include <transport/raw/WiFiPAF.h>
71 : #endif
72 : #include <app/TimerDelegates.h>
73 : #include <app/reporting/ReportSchedulerImpl.h>
74 : #include <transport/raw/UDP.h>
75 :
76 : #if CHIP_CONFIG_ENABLE_ICD_SERVER
77 : #include <app/icd/server/ICDManager.h> // nogncheck
78 :
79 : #if CHIP_CONFIG_ENABLE_ICD_CIP
80 : #include <app/icd/server/DefaultICDCheckInBackOffStrategy.h> // nogncheck
81 : #include <app/icd/server/ICDCheckInBackOffStrategy.h> // nogncheck
82 : #endif // CHIP_CONFIG_ENABLE_ICD_CIP
83 : #endif // CHIP_CONFIG_ENABLE_ICD_SERVER
84 :
85 : namespace chip {
86 :
87 : inline constexpr size_t kMaxBlePendingPackets = 1;
88 :
89 : #if INET_CONFIG_ENABLE_TCP_ENDPOINT
90 : inline constexpr size_t kMaxTcpActiveConnectionCount = CHIP_CONFIG_MAX_ACTIVE_TCP_CONNECTIONS;
91 :
92 : inline constexpr size_t kMaxTcpPendingPackets = CHIP_CONFIG_MAX_TCP_PENDING_PACKETS;
93 : #endif // INET_CONFIG_ENABLE_TCP_ENDPOINT
94 :
95 : //
96 : // NOTE: Please do not alter the order of template specialization here as the logic
97 : // in the Server impl depends on this.
98 : //
99 : using ServerTransportMgr = chip::TransportMgr<chip::Transport::UDP
100 : #if INET_CONFIG_ENABLE_IPV4
101 : ,
102 : chip::Transport::UDP
103 : #endif
104 : #if CONFIG_NETWORK_LAYER_BLE
105 : ,
106 : chip::Transport::BLE<kMaxBlePendingPackets>
107 : #endif
108 : #if INET_CONFIG_ENABLE_TCP_ENDPOINT
109 : ,
110 : chip::Transport::TCP<kMaxTcpActiveConnectionCount, kMaxTcpPendingPackets>
111 : #endif
112 : #if CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
113 : ,
114 : chip::Transport::WiFiPAFBase
115 : #endif
116 : >;
117 :
118 : #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT
119 : using UdcTransportMgr = TransportMgr<Transport::UDP /* IPv6 */
120 : #if INET_CONFIG_ENABLE_IPV4
121 : ,
122 : Transport::UDP /* IPv4 */
123 : #endif
124 : >;
125 : #endif
126 :
127 : struct ServerInitParams
128 : {
129 : ServerInitParams() = default;
130 :
131 : // Not copyable
132 : ServerInitParams(const ServerInitParams &) = delete;
133 : ServerInitParams & operator=(const ServerInitParams &) = delete;
134 :
135 : // Application delegate to handle some commissioning lifecycle events
136 : AppDelegate * appDelegate = nullptr;
137 : // device discovery timeout
138 : System::Clock::Seconds32 discoveryTimeout = System::Clock::Seconds32(CHIP_DEVICE_CONFIG_DISCOVERY_TIMEOUT_SECS);
139 : // Port to use for Matter commissioning/operational traffic
140 : uint16_t operationalServicePort = CHIP_PORT;
141 : // Port to use for UDC if supported
142 : uint16_t userDirectedCommissioningPort = CHIP_UDC_PORT;
143 : // Interface on which to run daemon
144 : Inet::InterfaceId interfaceId = Inet::InterfaceId::Null();
145 :
146 : // Persistent storage delegate: MUST be injected. Used to maintain storage by much common code.
147 : // Must be initialized before being provided.
148 : PersistentStorageDelegate * persistentStorageDelegate = nullptr;
149 : // Session resumption storage: Optional. Support session resumption when provided.
150 : // Must be initialized before being provided.
151 : SessionResumptionStorage * sessionResumptionStorage = nullptr;
152 : // Session resumption storage: Optional. Support session resumption when provided.
153 : // Must be initialized before being provided.
154 : app::SubscriptionResumptionStorage * subscriptionResumptionStorage = nullptr;
155 : // Certificate validity policy: Optional. If none is injected, CHIPCert
156 : // enforces a default policy.
157 : Credentials::CertificateValidityPolicy * certificateValidityPolicy = nullptr;
158 : // Group data provider: MUST be injected. Used to maintain critical keys such as the Identity
159 : // Protection Key (IPK) for CASE. Must be initialized before being provided.
160 : Credentials::GroupDataProvider * groupDataProvider = nullptr;
161 : // Session keystore: MUST be injected. Used to derive and manage lifecycle of symmetric keys.
162 : Crypto::SessionKeystore * sessionKeystore = nullptr;
163 : // Access control delegate: MUST be injected. Used to look up access control rules. Must be
164 : // initialized before being provided.
165 : Access::AccessControl::Delegate * accessDelegate = nullptr;
166 : // ACL storage: MUST be injected. Used to store ACL entries in persistent storage. Must NOT
167 : // be initialized before being provided.
168 : app::AclStorage * aclStorage = nullptr;
169 :
170 : #if CHIP_CONFIG_USE_ACCESS_RESTRICTIONS
171 : // Access Restriction implementation: MUST be injected if MNGD feature enabled. Used to enforce
172 : // access restrictions that are managed by the device.
173 : Access::AccessRestrictionProvider * accessRestrictionProvider = nullptr;
174 : #endif
175 :
176 : // Network native params can be injected depending on the
177 : // selected Endpoint implementation
178 : void * endpointNativeParams = nullptr;
179 : // Optional. Support test event triggers when provided. Must be initialized before being
180 : // provided.
181 : TestEventTriggerDelegate * testEventTriggerDelegate = nullptr;
182 : // Operational keystore with access to the operational keys: MUST be injected.
183 : Crypto::OperationalKeystore * operationalKeystore = nullptr;
184 : // Operational certificate store with access to the operational certs in persisted storage:
185 : // must not be null at timne of Server::Init().
186 : Credentials::OperationalCertificateStore * opCertStore = nullptr;
187 : // Required, if not provided, the Server::Init() WILL fail.
188 : app::reporting::ReportScheduler * reportScheduler = nullptr;
189 : #if CHIP_CONFIG_ENABLE_ICD_CIP
190 : // Optional. Support for the ICD Check-In BackOff strategy. Must be initialized before being provided.
191 : // If the ICD Check-In protocol use-case is supported and no strategy is provided, server will use the default strategy.
192 : app::ICDCheckInBackOffStrategy * icdCheckInBackOffStrategy = nullptr;
193 : #endif // CHIP_CONFIG_ENABLE_ICD_CIP
194 :
195 : // MUST NOT be null during initialization: every application must define the
196 : // data model it wants to use. Backwards-compatibility can use `CodegenDataModelProviderInstance`
197 : // for ember/zap-generated models.
198 : chip::app::DataModel::Provider * dataModelProvider = nullptr;
199 : };
200 :
201 : /**
202 : * Transitional version of ServerInitParams to assist SDK integrators in
203 : * transitioning to injecting product/platform-owned resources. This version
204 : * of `ServerInitParams` statically owns and initializes (via the
205 : * `InitializeStaticResourcesBeforeServerInit()` method) the persistent storage
206 : * delegate, the group data provider, and the access control delegate. This is to reduce
207 : * the amount of copied boilerplate in all the example initializations (e.g. AppTask.cpp,
208 : * main.cpp).
209 : *
210 : * This version SHOULD BE USED ONLY FOR THE IN-TREE EXAMPLES.
211 : *
212 : * ACTION ITEMS FOR TRANSITION from a example in-tree to a product:
213 : *
214 : * While this could be used indefinitely, it does not exemplify orderly management of
215 : * application-injected resources. It is recommended for actual products to instead:
216 : * - Use the basic ServerInitParams in the application
217 : * - Have the application own an instance of the resources being injected in its own
218 : * state (e.g. an implementation of PersistentStorageDelegate and GroupDataProvider
219 : * interfaces).
220 : * - Initialize the injected resources prior to calling Server::Init()
221 : * - De-initialize the injected resources after calling Server::Shutdown()
222 : *
223 : * WARNING: DO NOT replicate the pattern shown here of having a subclass of ServerInitParams
224 : * own the resources outside of examples. This was done to reduce the amount of change
225 : * to existing examples while still supporting non-example versions of the
226 : * resources to be injected.
227 : */
228 : struct CommonCaseDeviceServerInitParams : public ServerInitParams
229 : {
230 : CommonCaseDeviceServerInitParams() = default;
231 :
232 : // Not copyable
233 : CommonCaseDeviceServerInitParams(const CommonCaseDeviceServerInitParams &) = delete;
234 : CommonCaseDeviceServerInitParams & operator=(const CommonCaseDeviceServerInitParams &) = delete;
235 :
236 : /**
237 : * Call this before Server::Init() to initialize the internally-owned resources.
238 : * Server::Init() will fail if this is not done, since several params required to
239 : * be non-null will be null without calling this method. ** See the transition method
240 : * in the outer comment of this class **.
241 : *
242 : * @return CHIP_NO_ERROR on success or a CHIP_ERROR value from APIs called to initialize
243 : * resources on failure.
244 : */
245 : CHIP_ERROR InitializeStaticResourcesBeforeServerInit()
246 : {
247 : // KVS-based persistent storage delegate injection
248 : if (persistentStorageDelegate == nullptr)
249 : {
250 : chip::DeviceLayer::PersistedStorage::KeyValueStoreManager & kvsManager =
251 : DeviceLayer::PersistedStorage::KeyValueStoreMgr();
252 : ReturnErrorOnFailure(sKvsPersistenStorageDelegate.Init(&kvsManager));
253 : this->persistentStorageDelegate = &sKvsPersistenStorageDelegate;
254 : }
255 :
256 : // PersistentStorageDelegate "software-based" operational key access injection
257 : if (this->operationalKeystore == nullptr)
258 : {
259 : // WARNING: PersistentStorageOperationalKeystore::Finish() is never called. It's fine for
260 : // for examples and for now.
261 : ReturnErrorOnFailure(sPersistentStorageOperationalKeystore.Init(this->persistentStorageDelegate));
262 : this->operationalKeystore = &sPersistentStorageOperationalKeystore;
263 : }
264 :
265 : // OpCertStore can be injected but default to persistent storage default
266 : // for simplicity of the examples.
267 : if (this->opCertStore == nullptr)
268 : {
269 : // WARNING: PersistentStorageOpCertStore::Finish() is never called. It's fine for
270 : // for examples and for now, since all storage is immediate for that impl.
271 : ReturnErrorOnFailure(sPersistentStorageOpCertStore.Init(this->persistentStorageDelegate));
272 : this->opCertStore = &sPersistentStorageOpCertStore;
273 : }
274 :
275 : // Injection of report scheduler WILL lead to two schedulers being allocated. As recommended above, this should only be used
276 : // for IN-TREE examples. If a default scheduler is desired, the basic ServerInitParams should be used by the application and
277 : // CommonCaseDeviceServerInitParams should not be allocated.
278 : if (this->reportScheduler == nullptr)
279 : {
280 : reportScheduler = &sReportScheduler;
281 : }
282 :
283 : // Session Keystore injection
284 : this->sessionKeystore = &sSessionKeystore;
285 :
286 : // Group Data provider injection
287 : sGroupDataProvider.SetStorageDelegate(this->persistentStorageDelegate);
288 : sGroupDataProvider.SetSessionKeystore(this->sessionKeystore);
289 : ReturnErrorOnFailure(sGroupDataProvider.Init());
290 : this->groupDataProvider = &sGroupDataProvider;
291 :
292 : #if CHIP_CONFIG_ENABLE_SESSION_RESUMPTION
293 : ReturnErrorOnFailure(sSessionResumptionStorage.Init(this->persistentStorageDelegate));
294 : this->sessionResumptionStorage = &sSessionResumptionStorage;
295 : #else
296 : this->sessionResumptionStorage = nullptr;
297 : #endif
298 :
299 : // Inject access control delegate
300 : this->accessDelegate = Access::Examples::GetAccessControlDelegate();
301 :
302 : // Inject ACL storage. (Don't initialize it.)
303 : this->aclStorage = &sAclStorage;
304 :
305 : #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
306 : ChipLogProgress(AppServer, "Initializing subscription resumption storage...");
307 : ReturnErrorOnFailure(sSubscriptionResumptionStorage.Init(this->persistentStorageDelegate));
308 : this->subscriptionResumptionStorage = &sSubscriptionResumptionStorage;
309 : #else
310 : ChipLogProgress(AppServer, "Subscription persistence not supported");
311 : #endif
312 :
313 : #if CHIP_CONFIG_ENABLE_ICD_CIP
314 : if (this->icdCheckInBackOffStrategy == nullptr)
315 : {
316 : this->icdCheckInBackOffStrategy = &sDefaultICDCheckInBackOffStrategy;
317 : }
318 : #endif
319 :
320 : return CHIP_NO_ERROR;
321 : }
322 :
323 : private:
324 : static KvsPersistentStorageDelegate sKvsPersistenStorageDelegate;
325 : static PersistentStorageOperationalKeystore sPersistentStorageOperationalKeystore;
326 : static Credentials::PersistentStorageOpCertStore sPersistentStorageOpCertStore;
327 : static Credentials::GroupDataProviderImpl sGroupDataProvider;
328 : static chip::app::DefaultTimerDelegate sTimerDelegate;
329 : static app::reporting::ReportSchedulerImpl sReportScheduler;
330 :
331 : #if CHIP_CONFIG_ENABLE_SESSION_RESUMPTION
332 : static SimpleSessionResumptionStorage sSessionResumptionStorage;
333 : #endif
334 : #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
335 : static app::SimpleSubscriptionResumptionStorage sSubscriptionResumptionStorage;
336 : #endif
337 : static app::DefaultAclStorage sAclStorage;
338 : static Crypto::DefaultSessionKeystore sSessionKeystore;
339 : #if CHIP_CONFIG_ENABLE_ICD_CIP
340 : static app::DefaultICDCheckInBackOffStrategy sDefaultICDCheckInBackOffStrategy;
341 : #endif
342 : };
343 :
344 : /**
345 : * The `Server` singleton class is an aggregate for all the resources needed to run a
346 : * Node that is both Commissionable and mainly used as an end-node with server clusters.
347 : * In other words, it aggregates the state needed for the type of Node used for most
348 : * products that are not mainly controller/administrator role.
349 : *
350 : * This sington class expects `ServerInitParams` initialization parameters but does not
351 : * own the resources injected from `ServerInitParams`. Any object pointers/references
352 : * passed in ServerInitParams must be pre-initialized externally, and shutdown/finalized
353 : * after `Server::Shutdown()` is called.
354 : *
355 : * TODO: Separate lifecycle ownership for some more capabilities that should not belong to
356 : * common logic, such as `GenerateShutDownEvent`.
357 : *
358 : * TODO: Replace all uses of GetInstance() to "reach in" to this state from all cluster
359 : * server common logic that deal with global node state with either a common NodeState
360 : * compatible with OperationalDeviceProxy/DeviceProxy, or with injection at common
361 : * SDK logic init.
362 : */
363 : class Server
364 : {
365 : public:
366 : CHIP_ERROR Init(const ServerInitParams & initParams);
367 :
368 : #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT
369 : CHIP_ERROR
370 : SendUserDirectedCommissioningRequest(chip::Transport::PeerAddress commissioner,
371 : Protocols::UserDirectedCommissioning::IdentificationDeclaration & id);
372 :
373 : Protocols::UserDirectedCommissioning::UserDirectedCommissioningClient * GetUserDirectedCommissioningClient()
374 : {
375 : return gUDCClient;
376 : }
377 : #endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT
378 :
379 : /**
380 : * @brief Call this function to rejoin existing groups found in the GroupDataProvider
381 : */
382 : void RejoinExistingMulticastGroups();
383 :
384 5 : FabricTable & GetFabricTable() { return mFabrics; }
385 :
386 : CASESessionManager * GetCASESessionManager() { return &mCASESessionManager; }
387 :
388 11 : Messaging::ExchangeManager & GetExchangeManager() { return mExchangeMgr; }
389 :
390 6 : SessionManager & GetSecureSessionManager() { return mSessions; }
391 :
392 0 : SessionResumptionStorage * GetSessionResumptionStorage() { return mSessionResumptionStorage; }
393 :
394 0 : app::SubscriptionResumptionStorage * GetSubscriptionResumptionStorage() { return mSubscriptionResumptionStorage; }
395 :
396 0 : TransportMgrBase & GetTransportManager() { return mTransports; }
397 :
398 0 : Credentials::GroupDataProvider * GetGroupDataProvider() { return mGroupsProvider; }
399 :
400 : Crypto::SessionKeystore * GetSessionKeystore() const { return mSessionKeystore; }
401 :
402 : #if CONFIG_NETWORK_LAYER_BLE
403 4 : Ble::BleLayer * GetBleLayerObject() { return mBleLayer; }
404 : #endif
405 :
406 0 : CommissioningWindowManager & GetCommissioningWindowManager() { return mCommissioningWindowManager; }
407 :
408 0 : PersistentStorageDelegate & GetPersistentStorage() { return *mDeviceStorage; }
409 :
410 6 : app::FailSafeContext & GetFailSafeContext() { return mFailSafeContext; }
411 :
412 : TestEventTriggerDelegate * GetTestEventTriggerDelegate() { return mTestEventTriggerDelegate; }
413 :
414 : Crypto::OperationalKeystore * GetOperationalKeystore() { return mOperationalKeystore; }
415 :
416 : Credentials::OperationalCertificateStore * GetOpCertStore() { return mOpCertStore; }
417 :
418 : app::DefaultSafeAttributePersistenceProvider & GetDefaultAttributePersister() { return mAttributePersister; }
419 :
420 : app::reporting::ReportScheduler * GetReportScheduler() { return mReportScheduler; }
421 :
422 : app::JointFabricDatastore & GetJointFabricDatastore() { return mJointFabricDatastore; }
423 :
424 : #if CHIP_CONFIG_ENABLE_ICD_SERVER
425 : app::ICDManager & GetICDManager() { return mICDManager; }
426 :
427 : #if CHIP_CONFIG_ENABLE_ICD_CIP
428 : /**
429 : * @brief Function to determine if a Check-In message would be sent at Boot up
430 : *
431 : * @param aFabricIndex client fabric index
432 : * @param subjectID client subject ID
433 : * @return true Check-In message would be sent on boot up.
434 : * @return false Device has a persisted subscription with the client. See CHIP_CONFIG_PERSIST_SUBSCRIPTIONS.
435 : */
436 : bool ShouldCheckInMsgsBeSentAtBootFunction(FabricIndex aFabricIndex, NodeId subjectID);
437 : #endif // CHIP_CONFIG_ENABLE_ICD_CIP
438 : #endif // CHIP_CONFIG_ENABLE_ICD_SERVER
439 :
440 : /**
441 : * This function causes the ShutDown event to be generated async on the
442 : * Matter event loop. Should be called before stopping the event loop.
443 : */
444 : void GenerateShutDownEvent();
445 :
446 : void Shutdown();
447 :
448 : void ScheduleFactoryReset();
449 :
450 : System::Clock::Microseconds64 TimeSinceInit() const
451 : {
452 : return System::SystemClock().GetMonotonicMicroseconds64() - mInitTimestamp;
453 : }
454 :
455 0 : static Server & GetInstance() { return sServer; }
456 :
457 : private:
458 2 : Server() {}
459 :
460 : static Server sServer;
461 :
462 : void InitFailSafe();
463 : void OnPlatformEvent(const DeviceLayer::ChipDeviceEvent & event);
464 : void CheckServerReadyEvent();
465 :
466 : void PostFactoryResetEvent();
467 :
468 : static void OnPlatformEventWrapper(const DeviceLayer::ChipDeviceEvent * event, intptr_t);
469 :
470 : #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
471 : /**
472 : * @brief Called at Server::Init time to resume persisted subscriptions if the feature flag is enabled
473 : */
474 : void ResumeSubscriptions();
475 : #endif
476 :
477 : class GroupDataProviderListener final : public Credentials::GroupDataProvider::GroupListener
478 : {
479 : public:
480 2 : GroupDataProviderListener() {}
481 :
482 1 : CHIP_ERROR Init(Server * server)
483 : {
484 1 : VerifyOrReturnError(server != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
485 :
486 1 : mServer = server;
487 1 : return CHIP_NO_ERROR;
488 : };
489 :
490 0 : void OnGroupAdded(chip::FabricIndex fabric_index, const Credentials::GroupDataProvider::GroupInfo & new_group) override
491 : {
492 0 : const FabricInfo * fabric = mServer->GetFabricTable().FindFabricWithIndex(fabric_index);
493 0 : if (fabric == nullptr)
494 : {
495 0 : ChipLogError(AppServer, "Group added to nonexistent fabric?");
496 0 : return;
497 : }
498 :
499 0 : if (mServer->GetTransportManager().MulticastGroupJoinLeave(
500 0 : Transport::PeerAddress::Multicast(fabric->GetFabricId(), new_group.group_id), true) != CHIP_NO_ERROR)
501 : {
502 0 : ChipLogError(AppServer, "Unable to listen to group");
503 : }
504 : };
505 :
506 0 : void OnGroupRemoved(chip::FabricIndex fabric_index, const Credentials::GroupDataProvider::GroupInfo & old_group) override
507 : {
508 0 : const FabricInfo * fabric = mServer->GetFabricTable().FindFabricWithIndex(fabric_index);
509 0 : if (fabric == nullptr)
510 : {
511 0 : ChipLogError(AppServer, "Group removed from nonexistent fabric?");
512 0 : return;
513 : }
514 :
515 0 : mServer->GetTransportManager().MulticastGroupJoinLeave(
516 0 : Transport::PeerAddress::Multicast(fabric->GetFabricId(), old_group.group_id), false);
517 : };
518 :
519 : private:
520 : Server * mServer;
521 : };
522 :
523 : class ServerFabricDelegate final : public chip::FabricTable::Delegate
524 : {
525 : public:
526 2 : ServerFabricDelegate() {}
527 :
528 1 : CHIP_ERROR Init(Server * server)
529 : {
530 1 : VerifyOrReturnError(server != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
531 :
532 1 : mServer = server;
533 1 : return CHIP_NO_ERROR;
534 : }
535 :
536 0 : void OnFabricRemoved(const FabricTable & fabricTable, FabricIndex fabricIndex) override
537 : {
538 : (void) fabricTable;
539 0 : ClearCASEResumptionStateOnFabricChange(fabricIndex);
540 0 : ClearSubscriptionResumptionStateOnFabricChange(fabricIndex);
541 :
542 0 : Credentials::GroupDataProvider * groupDataProvider = mServer->GetGroupDataProvider();
543 0 : if (groupDataProvider != nullptr)
544 : {
545 0 : CHIP_ERROR err = groupDataProvider->RemoveFabric(fabricIndex);
546 0 : if (err != CHIP_NO_ERROR)
547 : {
548 0 : ChipLogError(AppServer,
549 : "Warning, failed to delete GroupDataProvider state for fabric index 0x%x: %" CHIP_ERROR_FORMAT,
550 : static_cast<unsigned>(fabricIndex), err.Format());
551 : }
552 : }
553 :
554 : // Remove access control entries in reverse order (it could be any order, but reverse order
555 : // will cause less churn in persistent storage).
556 0 : CHIP_ERROR aclErr = Access::GetAccessControl().DeleteAllEntriesForFabric(fabricIndex);
557 0 : if (aclErr != CHIP_NO_ERROR)
558 : {
559 0 : ChipLogError(AppServer, "Warning, failed to delete access control state for fabric index 0x%x: %" CHIP_ERROR_FORMAT,
560 : static_cast<unsigned>(fabricIndex), aclErr.Format());
561 : }
562 :
563 : // Remove ACL extension entry for the given fabricIndex.
564 0 : auto & storage = mServer->GetPersistentStorage();
565 0 : aclErr = storage.SyncDeleteKeyValue(DefaultStorageKeyAllocator::AccessControlExtensionEntry(fabricIndex).KeyName());
566 :
567 0 : if (aclErr != CHIP_NO_ERROR && aclErr != CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND)
568 : {
569 0 : ChipLogError(AppServer, "Warning, failed to delete ACL extension entry for fabric index 0x%x: %" CHIP_ERROR_FORMAT,
570 : static_cast<unsigned>(fabricIndex), aclErr.Format());
571 : }
572 :
573 0 : mServer->GetCommissioningWindowManager().OnFabricRemoved(fabricIndex);
574 0 : }
575 :
576 0 : void OnFabricUpdated(const FabricTable & fabricTable, chip::FabricIndex fabricIndex) override
577 : {
578 : (void) fabricTable;
579 0 : ClearCASEResumptionStateOnFabricChange(fabricIndex);
580 0 : }
581 :
582 : private:
583 0 : void ClearCASEResumptionStateOnFabricChange(chip::FabricIndex fabricIndex)
584 : {
585 0 : auto * sessionResumptionStorage = mServer->GetSessionResumptionStorage();
586 0 : VerifyOrReturn(sessionResumptionStorage != nullptr);
587 0 : CHIP_ERROR err = sessionResumptionStorage->DeleteAll(fabricIndex);
588 0 : if (err != CHIP_NO_ERROR)
589 : {
590 0 : ChipLogError(AppServer,
591 : "Warning, failed to delete session resumption state for fabric index 0x%x: %" CHIP_ERROR_FORMAT,
592 : static_cast<unsigned>(fabricIndex), err.Format());
593 : }
594 : }
595 :
596 0 : void ClearSubscriptionResumptionStateOnFabricChange(chip::FabricIndex fabricIndex)
597 : {
598 0 : auto * subscriptionResumptionStorage = mServer->GetSubscriptionResumptionStorage();
599 0 : VerifyOrReturn(subscriptionResumptionStorage != nullptr);
600 0 : CHIP_ERROR err = subscriptionResumptionStorage->DeleteAll(fabricIndex);
601 0 : if (err != CHIP_NO_ERROR)
602 : {
603 0 : ChipLogError(AppServer,
604 : "Warning, failed to delete subscription resumption state for fabric index 0x%x: %" CHIP_ERROR_FORMAT,
605 : static_cast<unsigned>(fabricIndex), err.Format());
606 : }
607 : }
608 :
609 : Server * mServer = nullptr;
610 : };
611 :
612 : /**
613 : * Since root certificates for Matter nodes cannot be updated in a reasonable
614 : * way, it doesn't make sense to enforce expiration time on root certificates.
615 : * This policy allows through root certificates, even if they're expired, and
616 : * otherwise delegates to the provided policy, or to the default policy if no
617 : * policy is provided.
618 : */
619 : class IgnoreRootExpirationValidityPolicy : public Credentials::CertificateValidityPolicy
620 : {
621 : public:
622 2 : IgnoreRootExpirationValidityPolicy() {}
623 :
624 1 : void Init(Credentials::CertificateValidityPolicy * providedPolicy) { mProvidedPolicy = providedPolicy; }
625 :
626 0 : CHIP_ERROR ApplyCertificateValidityPolicy(const Credentials::ChipCertificateData * cert, uint8_t depth,
627 : Credentials::CertificateValidityResult result) override
628 : {
629 0 : switch (result)
630 : {
631 0 : case Credentials::CertificateValidityResult::kExpired:
632 : case Credentials::CertificateValidityResult::kExpiredAtLastKnownGoodTime:
633 : case Credentials::CertificateValidityResult::kTimeUnknown: {
634 : Credentials::CertType certType;
635 0 : ReturnErrorOnFailure(cert->mSubjectDN.GetCertType(certType));
636 0 : if (certType == Credentials::CertType::kRoot)
637 : {
638 0 : return CHIP_NO_ERROR;
639 : }
640 :
641 0 : break;
642 : }
643 0 : default:
644 0 : break;
645 : }
646 :
647 0 : if (mProvidedPolicy)
648 : {
649 0 : return mProvidedPolicy->ApplyCertificateValidityPolicy(cert, depth, result);
650 : }
651 :
652 0 : return Credentials::CertificateValidityPolicy::ApplyDefaultPolicy(cert, depth, result);
653 : }
654 :
655 : private:
656 : Credentials::CertificateValidityPolicy * mProvidedPolicy = nullptr;
657 : };
658 :
659 : #if CONFIG_NETWORK_LAYER_BLE
660 : Ble::BleLayer * mBleLayer = nullptr;
661 : #endif
662 :
663 : // By default, use a certificate validation policy compatible with non-wall-clock-time-synced
664 : // embedded systems.
665 : static Credentials::IgnoreCertificateValidityPeriodPolicy sDefaultCertValidityPolicy;
666 :
667 : ServerTransportMgr mTransports;
668 : SessionManager mSessions;
669 : CASEServer mCASEServer;
670 :
671 : CASESessionManager mCASESessionManager;
672 : CASEClientPool<CHIP_CONFIG_DEVICE_MAX_ACTIVE_CASE_CLIENTS> mCASEClientPool;
673 : OperationalSessionSetupPool<CHIP_CONFIG_DEVICE_MAX_ACTIVE_DEVICES> mSessionSetupPool;
674 :
675 : Protocols::SecureChannel::UnsolicitedStatusHandler mUnsolicitedStatusHandler;
676 : Messaging::ExchangeManager mExchangeMgr;
677 : FabricTable mFabrics;
678 : secure_channel::MessageCounterManager mMessageCounterManager;
679 : #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT
680 : Protocols::UserDirectedCommissioning::UserDirectedCommissioningClient * gUDCClient = nullptr;
681 : // mUdcTransportMgr is for insecure communication (ex. user directed commissioning)
682 : // specifically, the commissioner declaration message (sent by commissioner to commissionee)
683 : UdcTransportMgr * mUdcTransportMgr = nullptr;
684 : uint16_t mCdcListenPort = CHIP_UDC_COMMISSIONEE_PORT;
685 : #endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT
686 : CommissioningWindowManager mCommissioningWindowManager;
687 :
688 : IgnoreRootExpirationValidityPolicy mCertificateValidityPolicy;
689 :
690 : PersistentStorageDelegate * mDeviceStorage;
691 : SessionResumptionStorage * mSessionResumptionStorage;
692 : app::SubscriptionResumptionStorage * mSubscriptionResumptionStorage;
693 : Credentials::GroupDataProvider * mGroupsProvider;
694 : Crypto::SessionKeystore * mSessionKeystore;
695 : app::DefaultSafeAttributePersistenceProvider mAttributePersister;
696 : GroupDataProviderListener mListener;
697 : ServerFabricDelegate mFabricDelegate;
698 : app::reporting::ReportScheduler * mReportScheduler;
699 :
700 : Access::AccessControl mAccessControl;
701 : app::AclStorage * mAclStorage;
702 :
703 : app::JointFabricDatastore mJointFabricDatastore;
704 :
705 : TestEventTriggerDelegate * mTestEventTriggerDelegate;
706 : Crypto::OperationalKeystore * mOperationalKeystore;
707 : Credentials::OperationalCertificateStore * mOpCertStore;
708 : app::FailSafeContext mFailSafeContext;
709 :
710 : bool mIsDnssdReady = false;
711 : uint16_t mOperationalServicePort;
712 : uint16_t mUserDirectedCommissioningPort;
713 : Inet::InterfaceId mInterfaceId;
714 :
715 : System::Clock::Microseconds64 mInitTimestamp;
716 : #if CHIP_CONFIG_ENABLE_ICD_SERVER
717 : app::ICDManager mICDManager;
718 : #endif // CHIP_CONFIG_ENABLE_ICD_SERVER
719 : };
720 :
721 : } // namespace chip
|