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