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 4 : 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 1 : Server() {}
454 :
455 : static Server sServer;
456 :
457 : void InitFailSafe();
458 : void OnPlatformEvent(const DeviceLayer::ChipDeviceEvent & event);
459 : void CheckServerReadyEvent();
460 :
461 : static void OnPlatformEventWrapper(const DeviceLayer::ChipDeviceEvent * event, intptr_t);
462 :
463 : #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
464 : /**
465 : * @brief Called at Server::Init time to resume persisted subscriptions if the feature flag is enabled
466 : */
467 : void ResumeSubscriptions();
468 : #endif
469 :
470 : class GroupDataProviderListener final : public Credentials::GroupDataProvider::GroupListener
471 : {
472 : public:
473 1 : GroupDataProviderListener() {}
474 :
475 1 : CHIP_ERROR Init(Server * server)
476 : {
477 1 : VerifyOrReturnError(server != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
478 :
479 1 : mServer = server;
480 1 : return CHIP_NO_ERROR;
481 : };
482 :
483 0 : void OnGroupAdded(chip::FabricIndex fabric_index, const Credentials::GroupDataProvider::GroupInfo & new_group) override
484 : {
485 0 : const FabricInfo * fabric = mServer->GetFabricTable().FindFabricWithIndex(fabric_index);
486 0 : if (fabric == nullptr)
487 : {
488 0 : ChipLogError(AppServer, "Group added to nonexistent fabric?");
489 0 : return;
490 : }
491 :
492 0 : if (mServer->GetTransportManager().MulticastGroupJoinLeave(
493 0 : Transport::PeerAddress::Multicast(fabric->GetFabricId(), new_group.group_id), true) != CHIP_NO_ERROR)
494 : {
495 0 : ChipLogError(AppServer, "Unable to listen to group");
496 : }
497 : };
498 :
499 0 : void OnGroupRemoved(chip::FabricIndex fabric_index, const Credentials::GroupDataProvider::GroupInfo & old_group) override
500 : {
501 0 : const FabricInfo * fabric = mServer->GetFabricTable().FindFabricWithIndex(fabric_index);
502 0 : if (fabric == nullptr)
503 : {
504 0 : ChipLogError(AppServer, "Group removed from nonexistent fabric?");
505 0 : return;
506 : }
507 :
508 0 : mServer->GetTransportManager().MulticastGroupJoinLeave(
509 0 : Transport::PeerAddress::Multicast(fabric->GetFabricId(), old_group.group_id), false);
510 : };
511 :
512 : private:
513 : Server * mServer;
514 : };
515 :
516 : class ServerFabricDelegate final : public chip::FabricTable::Delegate
517 : {
518 : public:
519 1 : ServerFabricDelegate() {}
520 :
521 1 : CHIP_ERROR Init(Server * server)
522 : {
523 1 : VerifyOrReturnError(server != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
524 :
525 1 : mServer = server;
526 1 : return CHIP_NO_ERROR;
527 : }
528 :
529 0 : void OnFabricRemoved(const FabricTable & fabricTable, FabricIndex fabricIndex) override
530 : {
531 : (void) fabricTable;
532 0 : ClearCASEResumptionStateOnFabricChange(fabricIndex);
533 0 : ClearSubscriptionResumptionStateOnFabricChange(fabricIndex);
534 :
535 0 : Credentials::GroupDataProvider * groupDataProvider = mServer->GetGroupDataProvider();
536 0 : if (groupDataProvider != nullptr)
537 : {
538 0 : CHIP_ERROR err = groupDataProvider->RemoveFabric(fabricIndex);
539 0 : if (err != CHIP_NO_ERROR)
540 : {
541 0 : ChipLogError(AppServer,
542 : "Warning, failed to delete GroupDataProvider state for fabric index 0x%x: %" CHIP_ERROR_FORMAT,
543 : static_cast<unsigned>(fabricIndex), err.Format());
544 : }
545 : }
546 :
547 : // Remove access control entries in reverse order (it could be any order, but reverse order
548 : // will cause less churn in persistent storage).
549 0 : CHIP_ERROR aclErr = Access::GetAccessControl().DeleteAllEntriesForFabric(fabricIndex);
550 0 : if (aclErr != CHIP_NO_ERROR)
551 : {
552 0 : ChipLogError(AppServer, "Warning, failed to delete access control state for fabric index 0x%x: %" CHIP_ERROR_FORMAT,
553 : static_cast<unsigned>(fabricIndex), aclErr.Format());
554 : }
555 :
556 : // Remove ACL extension entry for the given fabricIndex.
557 0 : auto & storage = mServer->GetPersistentStorage();
558 0 : aclErr = storage.SyncDeleteKeyValue(DefaultStorageKeyAllocator::AccessControlExtensionEntry(fabricIndex).KeyName());
559 :
560 0 : if (aclErr != CHIP_NO_ERROR && aclErr != CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND)
561 : {
562 0 : ChipLogError(AppServer, "Warning, failed to delete ACL extension entry for fabric index 0x%x: %" CHIP_ERROR_FORMAT,
563 : static_cast<unsigned>(fabricIndex), aclErr.Format());
564 : }
565 :
566 0 : mServer->GetCommissioningWindowManager().OnFabricRemoved(fabricIndex);
567 0 : }
568 :
569 0 : void OnFabricUpdated(const FabricTable & fabricTable, chip::FabricIndex fabricIndex) override
570 : {
571 : (void) fabricTable;
572 0 : ClearCASEResumptionStateOnFabricChange(fabricIndex);
573 0 : }
574 :
575 : private:
576 0 : void ClearCASEResumptionStateOnFabricChange(chip::FabricIndex fabricIndex)
577 : {
578 0 : auto * sessionResumptionStorage = mServer->GetSessionResumptionStorage();
579 0 : VerifyOrReturn(sessionResumptionStorage != nullptr);
580 0 : CHIP_ERROR err = sessionResumptionStorage->DeleteAll(fabricIndex);
581 0 : if (err != CHIP_NO_ERROR)
582 : {
583 0 : ChipLogError(AppServer,
584 : "Warning, failed to delete session resumption state for fabric index 0x%x: %" CHIP_ERROR_FORMAT,
585 : static_cast<unsigned>(fabricIndex), err.Format());
586 : }
587 : }
588 :
589 0 : void ClearSubscriptionResumptionStateOnFabricChange(chip::FabricIndex fabricIndex)
590 : {
591 0 : auto * subscriptionResumptionStorage = mServer->GetSubscriptionResumptionStorage();
592 0 : VerifyOrReturn(subscriptionResumptionStorage != nullptr);
593 0 : CHIP_ERROR err = subscriptionResumptionStorage->DeleteAll(fabricIndex);
594 0 : if (err != CHIP_NO_ERROR)
595 : {
596 0 : ChipLogError(AppServer,
597 : "Warning, failed to delete subscription resumption state for fabric index 0x%x: %" CHIP_ERROR_FORMAT,
598 : static_cast<unsigned>(fabricIndex), err.Format());
599 : }
600 : }
601 :
602 : Server * mServer = nullptr;
603 : };
604 :
605 : /**
606 : * Since root certificates for Matter nodes cannot be updated in a reasonable
607 : * way, it doesn't make sense to enforce expiration time on root certificates.
608 : * This policy allows through root certificates, even if they're expired, and
609 : * otherwise delegates to the provided policy, or to the default policy if no
610 : * policy is provided.
611 : */
612 : class IgnoreRootExpirationValidityPolicy : public Credentials::CertificateValidityPolicy
613 : {
614 : public:
615 1 : IgnoreRootExpirationValidityPolicy() {}
616 :
617 1 : void Init(Credentials::CertificateValidityPolicy * providedPolicy) { mProvidedPolicy = providedPolicy; }
618 :
619 0 : CHIP_ERROR ApplyCertificateValidityPolicy(const Credentials::ChipCertificateData * cert, uint8_t depth,
620 : Credentials::CertificateValidityResult result) override
621 : {
622 0 : switch (result)
623 : {
624 0 : case Credentials::CertificateValidityResult::kExpired:
625 : case Credentials::CertificateValidityResult::kExpiredAtLastKnownGoodTime:
626 : case Credentials::CertificateValidityResult::kTimeUnknown: {
627 : Credentials::CertType certType;
628 0 : ReturnErrorOnFailure(cert->mSubjectDN.GetCertType(certType));
629 0 : if (certType == Credentials::CertType::kRoot)
630 : {
631 0 : return CHIP_NO_ERROR;
632 : }
633 :
634 0 : break;
635 : }
636 0 : default:
637 0 : break;
638 : }
639 :
640 0 : if (mProvidedPolicy)
641 : {
642 0 : return mProvidedPolicy->ApplyCertificateValidityPolicy(cert, depth, result);
643 : }
644 :
645 0 : return Credentials::CertificateValidityPolicy::ApplyDefaultPolicy(cert, depth, result);
646 : }
647 :
648 : private:
649 : Credentials::CertificateValidityPolicy * mProvidedPolicy = nullptr;
650 : };
651 :
652 : #if CONFIG_NETWORK_LAYER_BLE
653 : Ble::BleLayer * mBleLayer = nullptr;
654 : #endif
655 :
656 : // By default, use a certificate validation policy compatible with non-wall-clock-time-synced
657 : // embedded systems.
658 : static Credentials::IgnoreCertificateValidityPeriodPolicy sDefaultCertValidityPolicy;
659 :
660 : ServerTransportMgr mTransports;
661 : SessionManager mSessions;
662 : CASEServer mCASEServer;
663 :
664 : CASESessionManager mCASESessionManager;
665 : CASEClientPool<CHIP_CONFIG_DEVICE_MAX_ACTIVE_CASE_CLIENTS> mCASEClientPool;
666 : OperationalSessionSetupPool<CHIP_CONFIG_DEVICE_MAX_ACTIVE_DEVICES> mSessionSetupPool;
667 :
668 : Protocols::SecureChannel::UnsolicitedStatusHandler mUnsolicitedStatusHandler;
669 : Messaging::ExchangeManager mExchangeMgr;
670 : FabricTable mFabrics;
671 : secure_channel::MessageCounterManager mMessageCounterManager;
672 : #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT
673 : Protocols::UserDirectedCommissioning::UserDirectedCommissioningClient * gUDCClient = nullptr;
674 : // mUdcTransportMgr is for insecure communication (ex. user directed commissioning)
675 : // specifically, the commissioner declaration message (sent by commissioner to commissionee)
676 : UdcTransportMgr * mUdcTransportMgr = nullptr;
677 : uint16_t mCdcListenPort = CHIP_UDC_COMMISSIONEE_PORT;
678 : #endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY_CLIENT
679 : CommissioningWindowManager mCommissioningWindowManager;
680 :
681 : IgnoreRootExpirationValidityPolicy mCertificateValidityPolicy;
682 :
683 : PersistentStorageDelegate * mDeviceStorage;
684 : SessionResumptionStorage * mSessionResumptionStorage;
685 : app::SubscriptionResumptionStorage * mSubscriptionResumptionStorage;
686 : Credentials::GroupDataProvider * mGroupsProvider;
687 : Crypto::SessionKeystore * mSessionKeystore;
688 : app::DefaultSafeAttributePersistenceProvider mAttributePersister;
689 : GroupDataProviderListener mListener;
690 : ServerFabricDelegate mFabricDelegate;
691 : app::reporting::ReportScheduler * mReportScheduler;
692 :
693 : Access::AccessControl mAccessControl;
694 : app::AclStorage * mAclStorage;
695 :
696 : TestEventTriggerDelegate * mTestEventTriggerDelegate;
697 : Crypto::OperationalKeystore * mOperationalKeystore;
698 : Credentials::OperationalCertificateStore * mOpCertStore;
699 : app::FailSafeContext mFailSafeContext;
700 :
701 : bool mIsDnssdReady = false;
702 : uint16_t mOperationalServicePort;
703 : uint16_t mUserDirectedCommissioningPort;
704 : Inet::InterfaceId mInterfaceId;
705 :
706 : System::Clock::Microseconds64 mInitTimestamp;
707 : #if CHIP_CONFIG_ENABLE_ICD_SERVER
708 : app::ICDManager mICDManager;
709 : #endif // CHIP_CONFIG_ENABLE_ICD_SERVER
710 : };
711 :
712 : } // namespace chip
|