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