Line data Source code
1 : /*
2 : *
3 : * Copyright (c) 2020-2024 Project CHIP Authors
4 : * Copyright (c) 2013-2017 Nest Labs, Inc.
5 : * All rights reserved.
6 : *
7 : * Licensed under the Apache License, Version 2.0 (the "License");
8 : * you may not use this file except in compliance with the License.
9 : * You may obtain a copy of the License at
10 : *
11 : * http://www.apache.org/licenses/LICENSE-2.0
12 : *
13 : * Unless required by applicable law or agreed to in writing, software
14 : * distributed under the License is distributed on an "AS IS" BASIS,
15 : * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 : * See the License for the specific language governing permissions and
17 : * limitations under the License.
18 : */
19 :
20 : /**
21 : * @file
22 : * Implementation of CHIP Device Controller, a common class
23 : * that implements discovery, pairing and provisioning of CHIP
24 : * devices.
25 : *
26 : */
27 :
28 : // module header, comes first
29 : #include <controller/CHIPDeviceController.h>
30 :
31 : #include <app-common/zap-generated/ids/Attributes.h>
32 : #include <app-common/zap-generated/ids/Clusters.h>
33 :
34 : #include <app/InteractionModelEngine.h>
35 : #include <app/OperationalSessionSetup.h>
36 : #include <app/server/Dnssd.h>
37 : #include <controller/CurrentFabricRemover.h>
38 : #include <controller/InvokeInteraction.h>
39 : #include <controller/WriteInteraction.h>
40 : #include <credentials/CHIPCert.h>
41 : #include <credentials/DeviceAttestationCredsProvider.h>
42 : #include <crypto/CHIPCryptoPAL.h>
43 : #include <lib/core/CHIPCore.h>
44 : #include <lib/core/CHIPEncoding.h>
45 : #include <lib/core/CHIPSafeCasts.h>
46 : #include <lib/core/ErrorStr.h>
47 : #include <lib/core/NodeId.h>
48 : #include <lib/support/Base64.h>
49 : #include <lib/support/CHIPArgParser.hpp>
50 : #include <lib/support/CHIPMem.h>
51 : #include <lib/support/CodeUtils.h>
52 : #include <lib/support/PersistentStorageMacros.h>
53 : #include <lib/support/SafeInt.h>
54 : #include <lib/support/ScopedBuffer.h>
55 : #include <lib/support/ThreadOperationalDataset.h>
56 : #include <lib/support/TimeUtils.h>
57 : #include <lib/support/logging/CHIPLogging.h>
58 : #include <messaging/ExchangeContext.h>
59 : #include <platform/LockTracker.h>
60 : #include <protocols/secure_channel/MessageCounterManager.h>
61 : #include <setup_payload/QRCodeSetupPayloadParser.h>
62 : #include <tracing/macros.h>
63 : #include <tracing/metric_event.h>
64 :
65 : #if CONFIG_NETWORK_LAYER_BLE
66 : #include <ble/Ble.h>
67 : #include <transport/raw/BLE.h>
68 : #endif
69 : #if CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
70 : #include <transport/raw/WiFiPAF.h>
71 : #endif
72 :
73 : #if CHIP_DEVICE_CONFIG_ENABLE_NFC_BASED_COMMISSIONING
74 : #include <platform/internal/NFCCommissioningManager.h>
75 : #endif
76 :
77 : #include <algorithm>
78 : #include <array>
79 : #include <errno.h>
80 : #include <inttypes.h>
81 : #include <limits>
82 : #include <memory>
83 : #include <stdint.h>
84 : #include <stdlib.h>
85 : #include <string>
86 : #include <time.h>
87 :
88 : using namespace chip::app;
89 : using namespace chip::app::Clusters;
90 : using namespace chip::Inet;
91 : using namespace chip::System;
92 : using namespace chip::Transport;
93 : using namespace chip::Credentials;
94 : using namespace chip::Crypto;
95 : using namespace chip::Tracing;
96 :
97 : namespace chip {
98 : namespace Controller {
99 :
100 : using namespace chip::Encoding;
101 : #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY
102 : using namespace chip::Protocols::UserDirectedCommissioning;
103 : #endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY
104 :
105 88 : DeviceController::DeviceController()
106 : {
107 8 : mState = State::NotInitialized;
108 8 : }
109 :
110 0 : CHIP_ERROR DeviceController::Init(ControllerInitParams params)
111 : {
112 0 : assertChipStackLockedByCurrentThread();
113 :
114 0 : VerifyOrReturnError(mState == State::NotInitialized, CHIP_ERROR_INCORRECT_STATE);
115 0 : VerifyOrReturnError(params.systemState != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
116 :
117 0 : VerifyOrReturnError(params.systemState->SystemLayer() != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
118 0 : VerifyOrReturnError(params.systemState->UDPEndPointManager() != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
119 :
120 : #if CONFIG_NETWORK_LAYER_BLE
121 0 : VerifyOrReturnError(params.systemState->BleLayer() != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
122 : #endif
123 :
124 0 : VerifyOrReturnError(params.systemState->TransportMgr() != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
125 :
126 0 : ReturnErrorOnFailure(mDNSResolver.Init(params.systemState->UDPEndPointManager()));
127 0 : mDNSResolver.SetDiscoveryDelegate(this);
128 0 : RegisterDeviceDiscoveryDelegate(params.deviceDiscoveryDelegate);
129 :
130 0 : mVendorId = params.controllerVendorId;
131 0 : if (params.operationalKeypair != nullptr || !params.controllerNOC.empty() || !params.controllerRCAC.empty())
132 : {
133 0 : ReturnErrorOnFailure(InitControllerNOCChain(params));
134 : }
135 0 : else if (params.fabricIndex.HasValue())
136 : {
137 0 : VerifyOrReturnError(params.systemState->Fabrics()->FabricCount() > 0, CHIP_ERROR_INVALID_ARGUMENT);
138 0 : if (params.systemState->Fabrics()->FindFabricWithIndex(params.fabricIndex.Value()) != nullptr)
139 : {
140 0 : mFabricIndex = params.fabricIndex.Value();
141 : }
142 : else
143 : {
144 0 : ChipLogError(Controller, "There is no fabric corresponding to the given fabricIndex");
145 0 : return CHIP_ERROR_INVALID_ARGUMENT;
146 : }
147 : }
148 :
149 0 : mSystemState = params.systemState->Retain();
150 0 : mState = State::Initialized;
151 :
152 0 : mRemoveFromFabricTableOnShutdown = params.removeFromFabricTableOnShutdown;
153 0 : mDeleteFromFabricTableOnShutdown = params.deleteFromFabricTableOnShutdown;
154 :
155 0 : if (GetFabricIndex() != kUndefinedFabricIndex)
156 : {
157 0 : ChipLogProgress(Controller,
158 : "Joined the fabric at index %d. Fabric ID is 0x" ChipLogFormatX64
159 : " (Compressed Fabric ID: " ChipLogFormatX64 ")",
160 : GetFabricIndex(), ChipLogValueX64(GetFabricId()), ChipLogValueX64(GetCompressedFabricId()));
161 : }
162 :
163 0 : return CHIP_NO_ERROR;
164 : }
165 :
166 0 : CHIP_ERROR DeviceController::InitControllerNOCChain(const ControllerInitParams & params)
167 : {
168 0 : FabricInfo newFabric;
169 0 : constexpr uint32_t chipCertAllocatedLen = kMaxCHIPCertLength;
170 0 : chip::Platform::ScopedMemoryBuffer<uint8_t> rcacBuf;
171 0 : chip::Platform::ScopedMemoryBuffer<uint8_t> icacBuf;
172 0 : chip::Platform::ScopedMemoryBuffer<uint8_t> nocBuf;
173 0 : Credentials::P256PublicKeySpan rootPublicKeySpan;
174 : FabricId fabricId;
175 : NodeId nodeId;
176 0 : bool hasExternallyOwnedKeypair = false;
177 0 : Crypto::P256Keypair * externalOperationalKeypair = nullptr;
178 0 : VendorId newFabricVendorId = params.controllerVendorId;
179 :
180 : // There are three possibilities here in terms of what happens with our
181 : // operational key:
182 : // 1) We have an externally owned operational keypair.
183 : // 2) We have an operational keypair that the fabric table should clone via
184 : // serialize/deserialize.
185 : // 3) We have no keypair at all, and the fabric table has been initialized
186 : // with a key store.
187 0 : if (params.operationalKeypair != nullptr)
188 : {
189 0 : hasExternallyOwnedKeypair = params.hasExternallyOwnedOperationalKeypair;
190 0 : externalOperationalKeypair = params.operationalKeypair;
191 : }
192 :
193 0 : VerifyOrReturnError(rcacBuf.Alloc(chipCertAllocatedLen), CHIP_ERROR_NO_MEMORY);
194 0 : VerifyOrReturnError(icacBuf.Alloc(chipCertAllocatedLen), CHIP_ERROR_NO_MEMORY);
195 0 : VerifyOrReturnError(nocBuf.Alloc(chipCertAllocatedLen), CHIP_ERROR_NO_MEMORY);
196 :
197 0 : MutableByteSpan rcacSpan(rcacBuf.Get(), chipCertAllocatedLen);
198 :
199 0 : ReturnErrorOnFailure(ConvertX509CertToChipCert(params.controllerRCAC, rcacSpan));
200 0 : ReturnErrorOnFailure(Credentials::ExtractPublicKeyFromChipCert(rcacSpan, rootPublicKeySpan));
201 0 : Crypto::P256PublicKey rootPublicKey{ rootPublicKeySpan };
202 :
203 0 : MutableByteSpan icacSpan;
204 0 : if (params.controllerICAC.empty())
205 : {
206 0 : ChipLogProgress(Controller, "Intermediate CA is not needed");
207 : }
208 : else
209 : {
210 0 : icacSpan = MutableByteSpan(icacBuf.Get(), chipCertAllocatedLen);
211 0 : ReturnErrorOnFailure(ConvertX509CertToChipCert(params.controllerICAC, icacSpan));
212 : }
213 :
214 0 : MutableByteSpan nocSpan = MutableByteSpan(nocBuf.Get(), chipCertAllocatedLen);
215 :
216 0 : ReturnErrorOnFailure(ConvertX509CertToChipCert(params.controllerNOC, nocSpan));
217 0 : ReturnErrorOnFailure(ExtractNodeIdFabricIdFromOpCert(nocSpan, &nodeId, &fabricId));
218 :
219 0 : auto * fabricTable = params.systemState->Fabrics();
220 0 : const FabricInfo * fabricInfo = nullptr;
221 :
222 : //
223 : // When multiple controllers are permitted on the same fabric, we need to find fabrics with
224 : // nodeId as an extra discriminant since we can have multiple FabricInfo objects that all
225 : // collide on the same fabric. Not doing so may result in a match with an existing FabricInfo
226 : // instance that matches the fabric in the provided NOC but is associated with a different NodeId
227 : // that is already in use by another active controller instance. That will effectively cause it
228 : // to change its identity inadvertently, which is not acceptable.
229 : //
230 : // TODO: Figure out how to clean up unreclaimed FabricInfos restored from persistent
231 : // storage that are not in use by active DeviceController instances. Also, figure out
232 : // how to reclaim FabricInfo slots when a DeviceController instance is deleted.
233 : //
234 0 : if (params.permitMultiControllerFabrics)
235 : {
236 0 : fabricInfo = fabricTable->FindIdentity(rootPublicKey, fabricId, nodeId);
237 : }
238 : else
239 : {
240 0 : fabricInfo = fabricTable->FindFabric(rootPublicKey, fabricId);
241 : }
242 :
243 0 : bool fabricFoundInTable = (fabricInfo != nullptr);
244 :
245 0 : FabricIndex fabricIndex = fabricFoundInTable ? fabricInfo->GetFabricIndex() : kUndefinedFabricIndex;
246 :
247 0 : CHIP_ERROR err = CHIP_NO_ERROR;
248 :
249 0 : auto advertiseOperational =
250 0 : params.enableServerInteractions ? FabricTable::AdvertiseIdentity::Yes : FabricTable::AdvertiseIdentity::No;
251 :
252 : //
253 : // We permit colliding fabrics when multiple controllers are present on the same logical fabric
254 : // since each controller is associated with a unique FabricInfo 'identity' object and consequently,
255 : // a unique FabricIndex.
256 : //
257 : // This sets a flag that will be cleared automatically when the fabric is committed/reverted later
258 : // in this function.
259 : //
260 0 : if (params.permitMultiControllerFabrics)
261 : {
262 0 : fabricTable->PermitCollidingFabrics();
263 : }
264 :
265 : // We have 4 cases to handle legacy usage of direct operational key injection
266 0 : if (externalOperationalKeypair)
267 : {
268 : // Cases 1 and 2: Injected operational keys
269 :
270 : // CASE 1: Fabric update with injected key
271 0 : if (fabricFoundInTable)
272 : {
273 0 : err = fabricTable->UpdatePendingFabricWithProvidedOpKey(fabricIndex, nocSpan, icacSpan, externalOperationalKeypair,
274 : hasExternallyOwnedKeypair, advertiseOperational);
275 : }
276 : else
277 : // CASE 2: New fabric with injected key
278 : {
279 0 : err = fabricTable->AddNewPendingTrustedRootCert(rcacSpan);
280 0 : if (err == CHIP_NO_ERROR)
281 : {
282 0 : err = fabricTable->AddNewPendingFabricWithProvidedOpKey(nocSpan, icacSpan, newFabricVendorId,
283 : externalOperationalKeypair, hasExternallyOwnedKeypair,
284 : &fabricIndex, advertiseOperational);
285 : }
286 : }
287 : }
288 : else
289 : {
290 : // Cases 3 and 4: OperationalKeystore has the keys
291 :
292 : // CASE 3: Fabric update with operational keystore
293 0 : if (fabricFoundInTable)
294 : {
295 0 : VerifyOrReturnError(fabricTable->HasOperationalKeyForFabric(fabricIndex), CHIP_ERROR_KEY_NOT_FOUND);
296 :
297 0 : err = fabricTable->UpdatePendingFabricWithOperationalKeystore(fabricIndex, nocSpan, icacSpan, advertiseOperational);
298 : }
299 : else
300 : // CASE 4: New fabric with operational keystore
301 : {
302 0 : err = fabricTable->AddNewPendingTrustedRootCert(rcacSpan);
303 0 : if (err == CHIP_NO_ERROR)
304 : {
305 0 : err = fabricTable->AddNewPendingFabricWithOperationalKeystore(nocSpan, icacSpan, newFabricVendorId, &fabricIndex,
306 : advertiseOperational);
307 : }
308 :
309 0 : if (err == CHIP_NO_ERROR)
310 : {
311 : // Now that we know our planned fabric index, verify that the
312 : // keystore has a key for it.
313 0 : if (!fabricTable->HasOperationalKeyForFabric(fabricIndex))
314 : {
315 0 : err = CHIP_ERROR_KEY_NOT_FOUND;
316 : }
317 : }
318 : }
319 : }
320 :
321 : // Commit after setup, error-out on failure.
322 0 : if (err == CHIP_NO_ERROR)
323 : {
324 : // No need to revert on error: CommitPendingFabricData reverts internally on *any* error.
325 0 : err = fabricTable->CommitPendingFabricData();
326 : }
327 : else
328 : {
329 0 : fabricTable->RevertPendingFabricData();
330 : }
331 :
332 0 : ReturnErrorOnFailure(err);
333 0 : VerifyOrReturnError(fabricIndex != kUndefinedFabricIndex, CHIP_ERROR_INTERNAL);
334 :
335 0 : mFabricIndex = fabricIndex;
336 0 : mAdvertiseIdentity = advertiseOperational;
337 0 : return CHIP_NO_ERROR;
338 0 : }
339 :
340 0 : CHIP_ERROR DeviceController::UpdateControllerNOCChain(const ByteSpan & noc, const ByteSpan & icac,
341 : Crypto::P256Keypair * operationalKeypair,
342 : bool operationalKeypairExternalOwned)
343 : {
344 0 : VerifyOrReturnError(mFabricIndex != kUndefinedFabricIndex, CHIP_ERROR_INTERNAL);
345 0 : VerifyOrReturnError(mSystemState != nullptr, CHIP_ERROR_INTERNAL);
346 0 : FabricTable * fabricTable = mSystemState->Fabrics();
347 0 : CHIP_ERROR err = CHIP_NO_ERROR;
348 : FabricId fabricId;
349 : NodeId nodeId;
350 0 : CATValues oldCats;
351 0 : CATValues newCats;
352 0 : ReturnErrorOnFailure(ExtractNodeIdFabricIdFromOpCert(noc, &nodeId, &fabricId));
353 0 : ReturnErrorOnFailure(fabricTable->FetchCATs(mFabricIndex, oldCats));
354 0 : ReturnErrorOnFailure(ExtractCATsFromOpCert(noc, newCats));
355 :
356 0 : bool needCloseSession = true;
357 0 : if (GetFabricInfo()->GetNodeId() == nodeId && oldCats == newCats)
358 : {
359 0 : needCloseSession = false;
360 : }
361 :
362 0 : if (operationalKeypair != nullptr)
363 : {
364 0 : err = fabricTable->UpdatePendingFabricWithProvidedOpKey(mFabricIndex, noc, icac, operationalKeypair,
365 : operationalKeypairExternalOwned, mAdvertiseIdentity);
366 : }
367 : else
368 : {
369 0 : VerifyOrReturnError(fabricTable->HasOperationalKeyForFabric(mFabricIndex), CHIP_ERROR_KEY_NOT_FOUND);
370 0 : err = fabricTable->UpdatePendingFabricWithOperationalKeystore(mFabricIndex, noc, icac, mAdvertiseIdentity);
371 : }
372 :
373 0 : if (err == CHIP_NO_ERROR)
374 : {
375 0 : err = fabricTable->CommitPendingFabricData();
376 : }
377 : else
378 : {
379 0 : fabricTable->RevertPendingFabricData();
380 : }
381 :
382 0 : ReturnErrorOnFailure(err);
383 0 : if (needCloseSession)
384 : {
385 : // If the node id or CATs have changed, our existing CASE sessions are no longer valid,
386 : // because the other side will think anything coming over those sessions comes from our
387 : // old node ID, and the new CATs might not satisfy the ACL requirements of the other side.
388 0 : mSystemState->SessionMgr()->ExpireAllSessionsForFabric(mFabricIndex);
389 : }
390 0 : ChipLogProgress(Controller, "Controller NOC chain has updated");
391 0 : return CHIP_NO_ERROR;
392 : }
393 :
394 0 : void DeviceController::Shutdown()
395 : {
396 0 : assertChipStackLockedByCurrentThread();
397 :
398 0 : VerifyOrReturn(mState != State::NotInitialized);
399 :
400 : // If our state is initialialized it means mSystemState is valid,
401 : // and we can use it below before we release our reference to it.
402 0 : ChipLogDetail(Controller, "Shutting down the controller");
403 0 : mState = State::NotInitialized;
404 :
405 0 : if (mFabricIndex != kUndefinedFabricIndex)
406 : {
407 : // Shut down any subscription clients for this fabric.
408 0 : app::InteractionModelEngine::GetInstance()->ShutdownSubscriptions(mFabricIndex);
409 :
410 : // Shut down any ongoing CASE session activity we have. We're going to
411 : // assume that all sessions for our fabric belong to us here.
412 0 : mSystemState->CASESessionMgr()->ReleaseSessionsForFabric(mFabricIndex);
413 :
414 : // Shut down any bdx transfers we're acting as the server for.
415 0 : mSystemState->BDXTransferServer()->AbortTransfersForFabric(mFabricIndex);
416 :
417 : // TODO: The CASE session manager does not shut down existing CASE
418 : // sessions. It just shuts down any ongoing CASE session establishment
419 : // we're in the middle of as initiator. Maybe it should shut down
420 : // existing sessions too?
421 0 : mSystemState->SessionMgr()->ExpireAllSessionsForFabric(mFabricIndex);
422 :
423 0 : if (mDeleteFromFabricTableOnShutdown)
424 : {
425 0 : mSystemState->Fabrics()->Delete(mFabricIndex);
426 : }
427 0 : else if (mRemoveFromFabricTableOnShutdown)
428 : {
429 0 : mSystemState->Fabrics()->Forget(mFabricIndex);
430 : }
431 : }
432 :
433 0 : mSystemState->Release();
434 0 : mSystemState = nullptr;
435 :
436 0 : mDNSResolver.Shutdown();
437 0 : mDeviceDiscoveryDelegate = nullptr;
438 : }
439 :
440 0 : CHIP_ERROR DeviceController::GetPeerAddressAndPort(NodeId peerId, Inet::IPAddress & addr, uint16_t & port)
441 : {
442 0 : VerifyOrReturnError(mState == State::Initialized, CHIP_ERROR_INCORRECT_STATE);
443 0 : Transport::PeerAddress peerAddr;
444 0 : ReturnErrorOnFailure(mSystemState->CASESessionMgr()->GetPeerAddress(GetPeerScopedId(peerId), peerAddr));
445 0 : addr = peerAddr.GetIPAddress();
446 0 : port = peerAddr.GetPort();
447 0 : return CHIP_NO_ERROR;
448 : }
449 :
450 0 : CHIP_ERROR DeviceController::GetPeerAddress(NodeId nodeId, Transport::PeerAddress & addr)
451 : {
452 0 : VerifyOrReturnError(mState == State::Initialized, CHIP_ERROR_INCORRECT_STATE);
453 0 : ReturnErrorOnFailure(mSystemState->CASESessionMgr()->GetPeerAddress(GetPeerScopedId(nodeId), addr));
454 :
455 0 : return CHIP_NO_ERROR;
456 : }
457 :
458 0 : CHIP_ERROR DeviceController::ComputePASEVerifier(uint32_t iterations, uint32_t setupPincode, const ByteSpan & salt,
459 : Spake2pVerifier & outVerifier)
460 : {
461 0 : ReturnErrorOnFailure(PASESession::GeneratePASEVerifier(outVerifier, iterations, salt, /* useRandomPIN= */ false, setupPincode));
462 :
463 0 : return CHIP_NO_ERROR;
464 : }
465 :
466 0 : ControllerDeviceInitParams DeviceController::GetControllerDeviceInitParams()
467 : {
468 : return ControllerDeviceInitParams{
469 0 : .sessionManager = mSystemState->SessionMgr(),
470 0 : .exchangeMgr = mSystemState->ExchangeMgr(),
471 0 : };
472 : }
473 :
474 0 : DeviceCommissioner::DeviceCommissioner() :
475 0 : mOnDeviceConnectedCallback(OnDeviceConnectedFn, this), mOnDeviceConnectionFailureCallback(OnDeviceConnectionFailureFn, this),
476 : #if CHIP_DEVICE_CONFIG_ENABLE_AUTOMATIC_CASE_RETRIES
477 0 : mOnDeviceConnectionRetryCallback(OnDeviceConnectionRetryFn, this),
478 : #endif // CHIP_DEVICE_CONFIG_ENABLE_AUTOMATIC_CASE_RETRIES
479 0 : mDeviceAttestationInformationVerificationCallback(OnDeviceAttestationInformationVerification, this),
480 0 : mDeviceNOCChainCallback(OnDeviceNOCChainGeneration, this), mSetUpCodePairer(this)
481 : {
482 : #if CHIP_DEVICE_CONFIG_ENABLE_JOINT_FABRIC
483 : (void) mPeerAdminJFAdminClusterEndpointId;
484 : #endif // CHIP_DEVICE_CONFIG_ENABLE_JOINT_FABRIC
485 0 : }
486 :
487 0 : CHIP_ERROR DeviceCommissioner::Init(CommissionerInitParams params)
488 : {
489 0 : VerifyOrReturnError(params.operationalCredentialsDelegate != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
490 0 : mOperationalCredentialsDelegate = params.operationalCredentialsDelegate;
491 0 : ReturnErrorOnFailure(DeviceController::Init(params));
492 :
493 0 : mPairingDelegate = params.pairingDelegate;
494 :
495 : // Configure device attestation validation
496 0 : mDeviceAttestationVerifier = params.deviceAttestationVerifier;
497 0 : if (mDeviceAttestationVerifier == nullptr)
498 : {
499 0 : mDeviceAttestationVerifier = Credentials::GetDeviceAttestationVerifier();
500 0 : if (mDeviceAttestationVerifier == nullptr)
501 : {
502 0 : ChipLogError(Controller,
503 : "Missing DeviceAttestationVerifier configuration at DeviceCommissioner init and none set with "
504 : "Credentials::SetDeviceAttestationVerifier()!");
505 0 : return CHIP_ERROR_INVALID_ARGUMENT;
506 : }
507 :
508 : // We fell back on a default from singleton accessor.
509 0 : ChipLogProgress(Controller,
510 : "*** Missing DeviceAttestationVerifier configuration at DeviceCommissioner init: using global default, "
511 : "consider passing one in CommissionerInitParams.");
512 : }
513 :
514 0 : if (params.defaultCommissioner != nullptr)
515 : {
516 0 : mDefaultCommissioner = params.defaultCommissioner;
517 : }
518 : // Otherwise leave it pointing to mAutoCommissioner.
519 :
520 : #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY // make this commissioner discoverable
521 : mUdcTransportMgr = chip::Platform::New<UdcTransportMgr>();
522 : ReturnErrorOnFailure(mUdcTransportMgr->Init(Transport::UdpListenParameters(mSystemState->UDPEndPointManager())
523 : .SetAddressType(Inet::IPAddressType::kIPv6)
524 : .SetListenPort(static_cast<uint16_t>(mUdcListenPort))
525 : #if INET_CONFIG_ENABLE_IPV4
526 : ,
527 : Transport::UdpListenParameters(mSystemState->UDPEndPointManager())
528 : .SetAddressType(Inet::IPAddressType::kIPv4)
529 : .SetListenPort(static_cast<uint16_t>(mUdcListenPort))
530 : #endif // INET_CONFIG_ENABLE_IPV4
531 : ));
532 :
533 : mUdcServer = chip::Platform::New<UserDirectedCommissioningServer>();
534 : mUdcTransportMgr->SetSessionManager(mUdcServer);
535 : mUdcServer->SetTransportManager(mUdcTransportMgr);
536 :
537 : mUdcServer->SetInstanceNameResolver(this);
538 : #endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY
539 :
540 0 : mSetUpCodePairer.SetSystemLayer(mSystemState->SystemLayer());
541 : #if CONFIG_NETWORK_LAYER_BLE
542 0 : mSetUpCodePairer.SetBleLayer(mSystemState->BleLayer());
543 : #endif // CONFIG_NETWORK_LAYER_BLE
544 :
545 0 : return CHIP_NO_ERROR;
546 : }
547 :
548 0 : void DeviceCommissioner::Shutdown()
549 : {
550 0 : VerifyOrReturn(mState != State::NotInitialized);
551 :
552 0 : ChipLogDetail(Controller, "Shutting down the commissioner");
553 :
554 0 : mSetUpCodePairer.StopPairing();
555 :
556 : // Check to see if pairing in progress before shutting down
557 0 : CommissioneeDeviceProxy * device = mDeviceInPASEEstablishment;
558 0 : if (device != nullptr && device->IsSessionSetupInProgress())
559 : {
560 0 : ChipLogDetail(Controller, "Setup in progress, stopping setup before shutting down");
561 0 : OnSessionEstablishmentError(CHIP_ERROR_CONNECTION_ABORTED);
562 : }
563 :
564 0 : CancelCommissioningInteractions();
565 :
566 : #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY // make this commissioner discoverable
567 : if (mUdcTransportMgr != nullptr)
568 : {
569 : chip::Platform::Delete(mUdcTransportMgr);
570 : mUdcTransportMgr = nullptr;
571 : }
572 : if (mUdcServer != nullptr)
573 : {
574 : mUdcServer->SetInstanceNameResolver(nullptr);
575 : chip::Platform::Delete(mUdcServer);
576 : mUdcServer = nullptr;
577 : }
578 : #endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY
579 : #if CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
580 0 : WiFiPAF::WiFiPAFLayer::GetWiFiPAFLayer().Shutdown(
581 0 : [](uint32_t id, WiFiPAF::WiFiPafRole role) { DeviceLayer::ConnectivityMgr().WiFiPAFShutdown(id, role); });
582 : #endif
583 :
584 : // Release everything from the commissionee device pool here.
585 : // Make sure to use ReleaseCommissioneeDevice so we don't keep dangling
586 : // pointers to the device objects.
587 0 : mCommissioneeDevicePool.ForEachActiveObject([this](auto * commissioneeDevice) {
588 0 : ReleaseCommissioneeDevice(commissioneeDevice);
589 0 : return Loop::Continue;
590 : });
591 :
592 0 : DeviceController::Shutdown();
593 : }
594 :
595 0 : CommissioneeDeviceProxy * DeviceCommissioner::FindCommissioneeDevice(NodeId id)
596 : {
597 : MATTER_TRACE_SCOPE("FindCommissioneeDevice", "DeviceCommissioner");
598 0 : CommissioneeDeviceProxy * foundDevice = nullptr;
599 0 : mCommissioneeDevicePool.ForEachActiveObject([&](auto * deviceProxy) {
600 0 : if (deviceProxy->GetDeviceId() == id || deviceProxy->GetTemporaryCommissioningId() == id)
601 : {
602 0 : foundDevice = deviceProxy;
603 0 : return Loop::Break;
604 : }
605 0 : return Loop::Continue;
606 : });
607 :
608 0 : return foundDevice;
609 : }
610 :
611 0 : CommissioneeDeviceProxy * DeviceCommissioner::FindCommissioneeDevice(const Transport::PeerAddress & peerAddress)
612 : {
613 0 : CommissioneeDeviceProxy * foundDevice = nullptr;
614 0 : mCommissioneeDevicePool.ForEachActiveObject([&](auto * deviceProxy) {
615 0 : if (deviceProxy->GetPeerAddress() == peerAddress)
616 : {
617 0 : foundDevice = deviceProxy;
618 0 : return Loop::Break;
619 : }
620 0 : return Loop::Continue;
621 : });
622 :
623 0 : return foundDevice;
624 : }
625 :
626 0 : void DeviceCommissioner::ReleaseCommissioneeDevice(CommissioneeDeviceProxy * device)
627 : {
628 : #if CONFIG_NETWORK_LAYER_BLE
629 0 : if (mSystemState->BleLayer() != nullptr && device->GetDeviceTransportType() == Transport::Type::kBle)
630 : {
631 : // We only support one BLE connection, so if this is BLE, close it
632 0 : ChipLogProgress(Discovery, "Closing all BLE connections");
633 0 : mSystemState->BleLayer()->CloseAllBleConnections();
634 : }
635 : #endif
636 :
637 : #if CHIP_DEVICE_CONFIG_ENABLE_NFC_BASED_COMMISSIONING
638 : Nfc::NFCReaderTransport * readerTransport = DeviceLayer::Internal::NFCCommissioningMgr().GetNFCReaderTransport();
639 : if (readerTransport)
640 : {
641 : ChipLogProgress(Controller, "Stopping discovery of all NFC tags");
642 : readerTransport->StopDiscoveringTags();
643 : }
644 : #endif
645 :
646 : // Make sure that there will be no dangling pointer
647 0 : if (mDeviceInPASEEstablishment == device)
648 : {
649 0 : mDeviceInPASEEstablishment = nullptr;
650 : }
651 0 : if (mDeviceBeingCommissioned == device)
652 : {
653 0 : mDeviceBeingCommissioned = nullptr;
654 : }
655 :
656 : // Release the commissionee device after we have nulled out our pointers,
657 : // because that can call back in to us with error notifications as the
658 : // session is released.
659 0 : mCommissioneeDevicePool.ReleaseObject(device);
660 0 : }
661 :
662 0 : CHIP_ERROR DeviceCommissioner::GetDeviceBeingCommissioned(NodeId deviceId, CommissioneeDeviceProxy ** out_device)
663 : {
664 0 : VerifyOrReturnError(out_device != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
665 0 : CommissioneeDeviceProxy * device = FindCommissioneeDevice(deviceId);
666 :
667 0 : VerifyOrReturnError(device != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
668 :
669 0 : *out_device = device;
670 :
671 0 : return CHIP_NO_ERROR;
672 : }
673 :
674 0 : CHIP_ERROR DeviceCommissioner::PairDevice(NodeId remoteDeviceId, const char * setUpCode, const CommissioningParameters & params,
675 : DiscoveryType discoveryType, Optional<Dnssd::CommonResolutionData> resolutionData)
676 : {
677 : MATTER_TRACE_SCOPE("PairDevice", "DeviceCommissioner");
678 :
679 0 : ReturnErrorOnFailure(mDefaultCommissioner->SetCommissioningParameters(params));
680 :
681 0 : return mSetUpCodePairer.PairDevice(remoteDeviceId, setUpCode, SetupCodePairerBehaviour::kCommission, discoveryType,
682 0 : resolutionData);
683 : }
684 :
685 0 : CHIP_ERROR DeviceCommissioner::PairDevice(NodeId remoteDeviceId, const char * setUpCode, DiscoveryType discoveryType,
686 : Optional<Dnssd::CommonResolutionData> resolutionData)
687 : {
688 : MATTER_TRACE_SCOPE("PairDevice", "DeviceCommissioner");
689 0 : return mSetUpCodePairer.PairDevice(remoteDeviceId, setUpCode, SetupCodePairerBehaviour::kCommission, discoveryType,
690 0 : resolutionData);
691 : }
692 :
693 0 : CHIP_ERROR DeviceCommissioner::PairDevice(NodeId remoteDeviceId, RendezvousParameters & params)
694 : {
695 : MATTER_TRACE_SCOPE("PairDevice", "DeviceCommissioner");
696 0 : ReturnErrorOnFailureWithMetric(kMetricDeviceCommissionerCommission, EstablishPASEConnection(remoteDeviceId, params));
697 0 : auto errorCode = Commission(remoteDeviceId);
698 0 : VerifyOrDoWithMetric(kMetricDeviceCommissionerCommission, CHIP_NO_ERROR == errorCode, errorCode);
699 0 : return errorCode;
700 : }
701 :
702 0 : CHIP_ERROR DeviceCommissioner::PairDevice(NodeId remoteDeviceId, RendezvousParameters & rendezvousParams,
703 : CommissioningParameters & commissioningParams)
704 : {
705 : MATTER_TRACE_SCOPE("PairDevice", "DeviceCommissioner");
706 0 : ReturnErrorOnFailureWithMetric(kMetricDeviceCommissionerCommission, EstablishPASEConnection(remoteDeviceId, rendezvousParams));
707 0 : auto errorCode = Commission(remoteDeviceId, commissioningParams);
708 0 : VerifyOrDoWithMetric(kMetricDeviceCommissionerCommission, CHIP_NO_ERROR == errorCode, errorCode);
709 0 : return errorCode;
710 : }
711 :
712 0 : CHIP_ERROR DeviceCommissioner::EstablishPASEConnection(NodeId remoteDeviceId, const char * setUpCode, DiscoveryType discoveryType,
713 : Optional<Dnssd::CommonResolutionData> resolutionData)
714 : {
715 : MATTER_TRACE_SCOPE("EstablishPASEConnection", "DeviceCommissioner");
716 0 : return mSetUpCodePairer.PairDevice(remoteDeviceId, setUpCode, SetupCodePairerBehaviour::kPaseOnly, discoveryType,
717 0 : resolutionData);
718 : }
719 :
720 0 : CHIP_ERROR DeviceCommissioner::EstablishPASEConnection(NodeId remoteDeviceId, RendezvousParameters & params)
721 : {
722 : MATTER_TRACE_SCOPE("EstablishPASEConnection", "DeviceCommissioner");
723 : MATTER_LOG_METRIC_BEGIN(kMetricDeviceCommissionerPASESession);
724 :
725 0 : CHIP_ERROR err = CHIP_NO_ERROR;
726 0 : CommissioneeDeviceProxy * device = nullptr;
727 0 : CommissioneeDeviceProxy * current = nullptr;
728 0 : Transport::PeerAddress peerAddress = Transport::PeerAddress::UDP(Inet::IPAddress::Any);
729 :
730 0 : Messaging::ExchangeContext * exchangeCtxt = nullptr;
731 0 : Optional<SessionHandle> session;
732 :
733 0 : VerifyOrExit(mState == State::Initialized, err = CHIP_ERROR_INCORRECT_STATE);
734 0 : VerifyOrExit(mDeviceInPASEEstablishment == nullptr, err = CHIP_ERROR_INCORRECT_STATE);
735 :
736 : // TODO(#13940): We need to specify the peer address for BLE transport in bindings.
737 0 : if (params.GetPeerAddress().GetTransportType() == Transport::Type::kBle ||
738 0 : params.GetPeerAddress().GetTransportType() == Transport::Type::kUndefined)
739 : {
740 : #if CONFIG_NETWORK_LAYER_BLE
741 : #if CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE
742 : ConnectBleTransportToSelf();
743 : #endif // CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE
744 0 : if (!params.HasBleLayer())
745 : {
746 0 : params.SetPeerAddress(Transport::PeerAddress::BLE());
747 : }
748 0 : peerAddress = Transport::PeerAddress::BLE();
749 : #endif // CONFIG_NETWORK_LAYER_BLE
750 : }
751 0 : else if (params.GetPeerAddress().GetTransportType() == Transport::Type::kTcp ||
752 0 : params.GetPeerAddress().GetTransportType() == Transport::Type::kUdp)
753 : {
754 0 : peerAddress = Transport::PeerAddress::UDP(params.GetPeerAddress().GetIPAddress(), params.GetPeerAddress().GetPort(),
755 0 : params.GetPeerAddress().GetInterface());
756 : }
757 : #if CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
758 0 : else if (params.GetPeerAddress().GetTransportType() == Transport::Type::kWiFiPAF)
759 : {
760 0 : peerAddress = Transport::PeerAddress::WiFiPAF(remoteDeviceId);
761 : }
762 : #endif // CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
763 :
764 0 : current = FindCommissioneeDevice(peerAddress);
765 0 : if (current != nullptr)
766 : {
767 0 : if (current->GetDeviceId() == remoteDeviceId)
768 : {
769 : // We might be able to just reuse its connection if it has one or is
770 : // working on one.
771 0 : if (current->IsSecureConnected())
772 : {
773 0 : if (mPairingDelegate)
774 : {
775 : // We already have an open secure session to this device, call the callback immediately and early return.
776 : // We don't know what the right RendezvousParameters are here.
777 0 : mPairingDelegate->OnPairingComplete(CHIP_NO_ERROR, std::nullopt, std::nullopt);
778 : }
779 : MATTER_LOG_METRIC_END(kMetricDeviceCommissionerPASESession, CHIP_NO_ERROR);
780 0 : return CHIP_NO_ERROR;
781 : }
782 0 : if (current->IsSessionSetupInProgress())
783 : {
784 : // We're not connected yet, but we're in the process of connecting. Pairing delegate will get a callback when
785 : // connection completes
786 0 : return CHIP_NO_ERROR;
787 : }
788 : }
789 :
790 : // Either the consumer wants to assign a different device id to this
791 : // peer address now (so we can't reuse the commissionee device we have
792 : // already) or something has gone strange. Delete the old device, try
793 : // again.
794 0 : ChipLogError(Controller, "Found unconnected device, removing");
795 0 : ReleaseCommissioneeDevice(current);
796 : }
797 :
798 0 : device = mCommissioneeDevicePool.CreateObject();
799 0 : VerifyOrExit(device != nullptr, err = CHIP_ERROR_NO_MEMORY);
800 :
801 0 : mDeviceInPASEEstablishment = device;
802 0 : device->Init(GetControllerDeviceInitParams(), remoteDeviceId, peerAddress);
803 0 : device->UpdateDeviceData(params.GetPeerAddress(), params.GetMRPConfig());
804 :
805 : #if CONFIG_NETWORK_LAYER_BLE
806 0 : if (params.GetPeerAddress().GetTransportType() == Transport::Type::kBle)
807 : {
808 0 : if (params.HasConnectionObject())
809 : {
810 0 : SuccessOrExit(err = mSystemState->BleLayer()->NewBleConnectionByObject(params.GetConnectionObject()));
811 : }
812 0 : else if (params.HasDiscoveredObject())
813 : {
814 : // The RendezvousParameters argument needs to be recovered if the search succeed, so save them
815 : // for later.
816 0 : mRendezvousParametersForDeviceDiscoveredOverBle = params;
817 0 : SuccessOrExit(err = mSystemState->BleLayer()->NewBleConnectionByObject(params.GetDiscoveredObject(), this,
818 : OnDiscoveredDeviceOverBleSuccess,
819 : OnDiscoveredDeviceOverBleError));
820 0 : ExitNow(CHIP_NO_ERROR);
821 : }
822 0 : else if (params.HasDiscriminator())
823 : {
824 : // The RendezvousParameters argument needs to be recovered if the search succeed, so save them
825 : // for later.
826 0 : mRendezvousParametersForDeviceDiscoveredOverBle = params;
827 :
828 0 : SuccessOrExit(err = mSystemState->BleLayer()->NewBleConnectionByDiscriminator(params.GetSetupDiscriminator().value(),
829 : this, OnDiscoveredDeviceOverBleSuccess,
830 : OnDiscoveredDeviceOverBleError));
831 0 : ExitNow(CHIP_NO_ERROR);
832 : }
833 : else
834 : {
835 0 : ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT);
836 : }
837 : }
838 : #endif
839 : #if CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
840 0 : if (params.GetPeerAddress().GetTransportType() == Transport::Type::kWiFiPAF)
841 : {
842 0 : if (DeviceLayer::ConnectivityMgr().GetWiFiPAF()->GetWiFiPAFState() != WiFiPAF::State::kConnected)
843 : {
844 0 : ChipLogProgress(Controller, "WiFi-PAF: Subscribing to the NAN-USD devices, nodeId: %lu",
845 : params.GetPeerAddress().GetRemoteId());
846 0 : mRendezvousParametersForDeviceDiscoveredOverWiFiPAF = params;
847 0 : auto nodeId = params.GetPeerAddress().GetRemoteId();
848 0 : const SetupDiscriminator connDiscriminator(params.GetSetupDiscriminator().value());
849 0 : VerifyOrReturnValue(!connDiscriminator.IsShortDiscriminator(), CHIP_ERROR_INVALID_ARGUMENT,
850 : ChipLogError(Controller, "Error, Long discriminator is required"));
851 0 : uint16_t discriminator = connDiscriminator.GetLongValue();
852 0 : WiFiPAF::WiFiPAFSession sessionInfo = { .role = WiFiPAF::WiFiPafRole::kWiFiPafRole_Subscriber,
853 : .nodeId = nodeId,
854 0 : .discriminator = discriminator };
855 0 : ReturnErrorOnFailure(
856 : DeviceLayer::ConnectivityMgr().GetWiFiPAF()->AddPafSession(WiFiPAF::PafInfoAccess::kAccNodeInfo, sessionInfo));
857 0 : DeviceLayer::ConnectivityMgr().WiFiPAFSubscribe(discriminator, reinterpret_cast<void *>(this),
858 : OnWiFiPAFSubscribeComplete, OnWiFiPAFSubscribeError);
859 0 : ExitNow(CHIP_NO_ERROR);
860 : }
861 : }
862 : #endif
863 0 : session = mSystemState->SessionMgr()->CreateUnauthenticatedSession(params.GetPeerAddress(), params.GetMRPConfig());
864 0 : VerifyOrExit(session.HasValue(), err = CHIP_ERROR_NO_MEMORY);
865 :
866 : // Allocate the exchange immediately before calling PASESession::Pair.
867 : //
868 : // PASESession::Pair takes ownership of the exchange and will free it on
869 : // error, but can only do this if it is actually called. Allocating the
870 : // exchange context right before calling Pair ensures that if allocation
871 : // succeeds, PASESession has taken ownership.
872 0 : exchangeCtxt = mSystemState->ExchangeMgr()->NewContext(session.Value(), &device->GetPairing());
873 0 : VerifyOrExit(exchangeCtxt != nullptr, err = CHIP_ERROR_INTERNAL);
874 :
875 0 : err = device->GetPairing().Pair(*mSystemState->SessionMgr(), params.GetSetupPINCode(), GetLocalMRPConfig(), exchangeCtxt, this);
876 0 : SuccessOrExit(err);
877 :
878 0 : mRendezvousParametersForPASEEstablishment = params;
879 :
880 0 : exit:
881 0 : if (err != CHIP_NO_ERROR)
882 : {
883 0 : if (device != nullptr)
884 : {
885 0 : ReleaseCommissioneeDevice(device);
886 : }
887 : MATTER_LOG_METRIC_END(kMetricDeviceCommissionerPASESession, err);
888 : }
889 :
890 0 : return err;
891 0 : }
892 :
893 : #if CONFIG_NETWORK_LAYER_BLE
894 0 : void DeviceCommissioner::OnDiscoveredDeviceOverBleSuccess(void * appState, BLE_CONNECTION_OBJECT connObj)
895 : {
896 0 : auto self = static_cast<DeviceCommissioner *>(appState);
897 0 : auto device = self->mDeviceInPASEEstablishment;
898 :
899 0 : if (nullptr != device && device->GetDeviceTransportType() == Transport::Type::kBle)
900 : {
901 0 : auto remoteId = device->GetDeviceId();
902 :
903 0 : auto params = self->mRendezvousParametersForDeviceDiscoveredOverBle;
904 0 : params.SetConnectionObject(connObj);
905 0 : self->mRendezvousParametersForDeviceDiscoveredOverBle = RendezvousParameters();
906 :
907 0 : self->ReleaseCommissioneeDevice(device);
908 0 : LogErrorOnFailure(self->EstablishPASEConnection(remoteId, params));
909 : }
910 0 : }
911 :
912 0 : void DeviceCommissioner::OnDiscoveredDeviceOverBleError(void * appState, CHIP_ERROR err)
913 : {
914 0 : auto self = static_cast<DeviceCommissioner *>(appState);
915 0 : auto device = self->mDeviceInPASEEstablishment;
916 :
917 0 : if (nullptr != device && device->GetDeviceTransportType() == Transport::Type::kBle)
918 : {
919 0 : self->ReleaseCommissioneeDevice(device);
920 0 : self->mRendezvousParametersForDeviceDiscoveredOverBle = RendezvousParameters();
921 :
922 : // Callback is required when BLE discovery fails, otherwise the caller will always be in a suspended state
923 : // A better way to handle it should define a new error code
924 0 : if (self->mPairingDelegate != nullptr)
925 : {
926 0 : self->mPairingDelegate->OnPairingComplete(err, std::nullopt, std::nullopt);
927 : }
928 : }
929 0 : }
930 : #endif // CONFIG_NETWORK_LAYER_BLE
931 :
932 : #if CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
933 0 : void DeviceCommissioner::OnWiFiPAFSubscribeComplete(void * appState)
934 : {
935 0 : auto self = reinterpret_cast<DeviceCommissioner *>(appState);
936 0 : auto device = self->mDeviceInPASEEstablishment;
937 :
938 0 : if (nullptr != device && device->GetDeviceTransportType() == Transport::Type::kWiFiPAF)
939 : {
940 0 : ChipLogProgress(Controller, "WiFi-PAF: Subscription Completed, dev_id = %lu", device->GetDeviceId());
941 0 : auto remoteId = device->GetDeviceId();
942 0 : auto params = self->mRendezvousParametersForDeviceDiscoveredOverWiFiPAF;
943 :
944 0 : self->mRendezvousParametersForDeviceDiscoveredOverWiFiPAF = RendezvousParameters();
945 0 : self->ReleaseCommissioneeDevice(device);
946 0 : LogErrorOnFailure(self->EstablishPASEConnection(remoteId, params));
947 : }
948 0 : }
949 :
950 0 : void DeviceCommissioner::OnWiFiPAFSubscribeError(void * appState, CHIP_ERROR err)
951 : {
952 0 : auto self = (DeviceCommissioner *) appState;
953 0 : auto device = self->mDeviceInPASEEstablishment;
954 :
955 0 : if (nullptr != device && device->GetDeviceTransportType() == Transport::Type::kWiFiPAF)
956 : {
957 0 : ChipLogError(Controller, "WiFi-PAF: Subscription Error, id = %lu, err = %" CHIP_ERROR_FORMAT, device->GetDeviceId(),
958 : err.Format());
959 0 : self->ReleaseCommissioneeDevice(device);
960 0 : self->mRendezvousParametersForDeviceDiscoveredOverWiFiPAF = RendezvousParameters();
961 0 : if (self->mPairingDelegate != nullptr)
962 : {
963 0 : self->mPairingDelegate->OnPairingComplete(err, std::nullopt, std::nullopt);
964 : }
965 : }
966 0 : }
967 : #endif
968 :
969 0 : CHIP_ERROR DeviceCommissioner::Commission(NodeId remoteDeviceId, CommissioningParameters & params)
970 : {
971 0 : ReturnErrorOnFailureWithMetric(kMetricDeviceCommissionerCommission, mDefaultCommissioner->SetCommissioningParameters(params));
972 0 : auto errorCode = Commission(remoteDeviceId);
973 0 : VerifyOrDoWithMetric(kMetricDeviceCommissionerCommission, CHIP_NO_ERROR == errorCode, errorCode);
974 0 : return errorCode;
975 : }
976 :
977 0 : CHIP_ERROR DeviceCommissioner::Commission(NodeId remoteDeviceId)
978 : {
979 : MATTER_TRACE_SCOPE("Commission", "DeviceCommissioner");
980 :
981 0 : CommissioneeDeviceProxy * device = FindCommissioneeDevice(remoteDeviceId);
982 0 : if (device == nullptr || (!device->IsSecureConnected() && !device->IsSessionSetupInProgress()))
983 : {
984 0 : ChipLogError(Controller, "Invalid device for commissioning " ChipLogFormatX64, ChipLogValueX64(remoteDeviceId));
985 0 : return CHIP_ERROR_INCORRECT_STATE;
986 : }
987 0 : if (!device->IsSecureConnected() && device != mDeviceInPASEEstablishment)
988 : {
989 : // We should not end up in this state because we won't attempt to establish more than one connection at a time.
990 0 : ChipLogError(Controller, "Device is not connected and not being paired " ChipLogFormatX64, ChipLogValueX64(remoteDeviceId));
991 0 : return CHIP_ERROR_INCORRECT_STATE;
992 : }
993 :
994 0 : if (mCommissioningStage != CommissioningStage::kSecurePairing)
995 : {
996 0 : ChipLogError(Controller, "Commissioning already in progress (stage '%s') - not restarting",
997 : StageToString(mCommissioningStage));
998 0 : return CHIP_ERROR_INCORRECT_STATE;
999 : }
1000 :
1001 0 : ChipLogProgress(Controller, "Commission called for node ID 0x" ChipLogFormatX64, ChipLogValueX64(remoteDeviceId));
1002 :
1003 0 : mDefaultCommissioner->SetOperationalCredentialsDelegate(mOperationalCredentialsDelegate);
1004 0 : if (device->IsSecureConnected())
1005 : {
1006 : MATTER_LOG_METRIC_BEGIN(kMetricDeviceCommissionerCommission);
1007 0 : mDefaultCommissioner->StartCommissioning(this, device);
1008 : }
1009 : else
1010 : {
1011 0 : mRunCommissioningAfterConnection = true;
1012 : }
1013 0 : return CHIP_NO_ERROR;
1014 : }
1015 :
1016 : CHIP_ERROR
1017 0 : DeviceCommissioner::ContinueCommissioningAfterDeviceAttestation(DeviceProxy * device,
1018 : Credentials::AttestationVerificationResult attestationResult)
1019 : {
1020 : MATTER_TRACE_SCOPE("continueCommissioningDevice", "DeviceCommissioner");
1021 :
1022 0 : if (device == nullptr || device != mDeviceBeingCommissioned)
1023 : {
1024 0 : ChipLogError(Controller, "Invalid device for commissioning %p", device);
1025 0 : return CHIP_ERROR_INCORRECT_STATE;
1026 : }
1027 0 : CommissioneeDeviceProxy * commissioneeDevice = FindCommissioneeDevice(device->GetDeviceId());
1028 0 : if (commissioneeDevice == nullptr)
1029 : {
1030 0 : ChipLogError(Controller, "Couldn't find commissionee device");
1031 0 : return CHIP_ERROR_INCORRECT_STATE;
1032 : }
1033 0 : if (!commissioneeDevice->IsSecureConnected() || commissioneeDevice != mDeviceBeingCommissioned)
1034 : {
1035 0 : ChipLogError(Controller, "Invalid device for commissioning after attestation failure: 0x" ChipLogFormatX64,
1036 : ChipLogValueX64(commissioneeDevice->GetDeviceId()));
1037 0 : return CHIP_ERROR_INCORRECT_STATE;
1038 : }
1039 :
1040 0 : if (mCommissioningStage != CommissioningStage::kAttestationRevocationCheck)
1041 : {
1042 0 : ChipLogError(Controller, "Commissioning is not attestation verification phase");
1043 0 : return CHIP_ERROR_INCORRECT_STATE;
1044 : }
1045 :
1046 0 : ChipLogProgress(Controller, "Continuing commissioning after attestation failure for device ID 0x" ChipLogFormatX64,
1047 : ChipLogValueX64(commissioneeDevice->GetDeviceId()));
1048 :
1049 0 : if (attestationResult != AttestationVerificationResult::kSuccess)
1050 : {
1051 0 : ChipLogError(Controller, "Client selected error: %u for failed 'Attestation Information' for device",
1052 : to_underlying(attestationResult));
1053 :
1054 0 : CommissioningDelegate::CommissioningReport report;
1055 0 : report.Set<AttestationErrorInfo>(attestationResult);
1056 0 : CommissioningStageComplete(CHIP_ERROR_INTERNAL, report);
1057 0 : }
1058 : else
1059 : {
1060 0 : ChipLogProgress(Controller, "Overriding attestation failure per client and continuing commissioning");
1061 0 : CommissioningStageComplete(CHIP_NO_ERROR);
1062 : }
1063 0 : return CHIP_NO_ERROR;
1064 : }
1065 :
1066 : #if CHIP_DEVICE_CONFIG_ENABLE_NFC_BASED_COMMISSIONING
1067 : CHIP_ERROR DeviceCommissioner::ContinueCommissioningAfterConnectNetworkRequest(NodeId remoteDeviceId)
1068 : {
1069 : MATTER_TRACE_SCOPE("continueCommissioningAfterConnectNetworkRequest", "DeviceCommissioner");
1070 :
1071 : // Move to kEvictPreviousCaseSessions stage since the next stage will be to find the device
1072 : // on the operational network
1073 : mCommissioningStage = CommissioningStage::kEvictPreviousCaseSessions;
1074 :
1075 : // Setup device being commissioned
1076 : CommissioneeDeviceProxy * device = nullptr;
1077 : if (!mDeviceBeingCommissioned)
1078 : {
1079 : device = mCommissioneeDevicePool.CreateObject();
1080 : if (!device)
1081 : return CHIP_ERROR_NO_MEMORY;
1082 :
1083 : Transport::PeerAddress peerAddress = Transport::PeerAddress::UDP(Inet::IPAddress::Any);
1084 : device->Init(GetControllerDeviceInitParams(), remoteDeviceId, peerAddress);
1085 : mDeviceBeingCommissioned = device;
1086 : }
1087 :
1088 : mDefaultCommissioner->SetOperationalCredentialsDelegate(mOperationalCredentialsDelegate);
1089 :
1090 : ChipLogProgress(Controller, "Continuing commissioning after connect to network complete for device ID 0x" ChipLogFormatX64,
1091 : ChipLogValueX64(remoteDeviceId));
1092 :
1093 : MATTER_LOG_METRIC_BEGIN(kMetricDeviceCommissioningOperationalSetup);
1094 : CHIP_ERROR err = mDefaultCommissioner->StartCommissioning(this, device);
1095 : if (err != CHIP_NO_ERROR)
1096 : {
1097 : MATTER_LOG_METRIC_END(kMetricDeviceCommissioningOperationalSetup, err);
1098 : }
1099 : return err;
1100 : }
1101 : #endif
1102 :
1103 0 : CHIP_ERROR DeviceCommissioner::StopPairing(NodeId remoteDeviceId)
1104 : {
1105 0 : VerifyOrReturnError(mState == State::Initialized, CHIP_ERROR_INCORRECT_STATE);
1106 0 : VerifyOrReturnError(remoteDeviceId != kUndefinedNodeId, CHIP_ERROR_INVALID_ARGUMENT);
1107 :
1108 0 : ChipLogProgress(Controller, "StopPairing called for node ID 0x" ChipLogFormatX64, ChipLogValueX64(remoteDeviceId));
1109 :
1110 : // If we're still in the process of discovering the device, just stop the SetUpCodePairer
1111 0 : if (mSetUpCodePairer.StopPairing(remoteDeviceId))
1112 : {
1113 0 : mRunCommissioningAfterConnection = false;
1114 0 : OnSessionEstablishmentError(CHIP_ERROR_CANCELLED);
1115 0 : return CHIP_NO_ERROR;
1116 : }
1117 :
1118 : // Otherwise we might be pairing and / or commissioning it.
1119 0 : CommissioneeDeviceProxy * device = FindCommissioneeDevice(remoteDeviceId);
1120 0 : VerifyOrReturnError(device != nullptr, CHIP_ERROR_INVALID_DEVICE_DESCRIPTOR);
1121 :
1122 0 : if (mDeviceBeingCommissioned == device)
1123 : {
1124 0 : CancelCommissioningInteractions();
1125 0 : CommissioningStageComplete(CHIP_ERROR_CANCELLED);
1126 : }
1127 : else
1128 : {
1129 0 : ReleaseCommissioneeDevice(device);
1130 : }
1131 0 : return CHIP_NO_ERROR;
1132 : }
1133 :
1134 0 : void DeviceCommissioner::CancelCommissioningInteractions()
1135 : {
1136 0 : if (mReadClient)
1137 : {
1138 0 : ChipLogDetail(Controller, "Cancelling read request for step '%s'", StageToString(mCommissioningStage));
1139 0 : mReadClient.reset(); // destructor cancels
1140 0 : mAttributeCache.reset();
1141 : }
1142 0 : if (mInvokeCancelFn)
1143 : {
1144 0 : ChipLogDetail(Controller, "Cancelling command invocation for step '%s'", StageToString(mCommissioningStage));
1145 0 : mInvokeCancelFn();
1146 0 : mInvokeCancelFn = nullptr;
1147 : }
1148 0 : if (mWriteCancelFn)
1149 : {
1150 0 : ChipLogDetail(Controller, "Cancelling write request for step '%s'", StageToString(mCommissioningStage));
1151 0 : mWriteCancelFn();
1152 0 : mWriteCancelFn = nullptr;
1153 : }
1154 0 : if (mOnDeviceConnectedCallback.IsRegistered())
1155 : {
1156 0 : ChipLogDetail(Controller, "Cancelling CASE setup for step '%s'", StageToString(mCommissioningStage));
1157 0 : CancelCASECallbacks();
1158 : }
1159 0 : }
1160 :
1161 0 : void DeviceCommissioner::CancelCASECallbacks()
1162 : {
1163 0 : mOnDeviceConnectedCallback.Cancel();
1164 0 : mOnDeviceConnectionFailureCallback.Cancel();
1165 : #if CHIP_DEVICE_CONFIG_ENABLE_AUTOMATIC_CASE_RETRIES
1166 0 : mOnDeviceConnectionRetryCallback.Cancel();
1167 : #endif
1168 0 : }
1169 :
1170 0 : CHIP_ERROR DeviceCommissioner::UnpairDevice(NodeId remoteDeviceId)
1171 : {
1172 : MATTER_TRACE_SCOPE("UnpairDevice", "DeviceCommissioner");
1173 0 : VerifyOrReturnError(mState == State::Initialized, CHIP_ERROR_INCORRECT_STATE);
1174 :
1175 0 : return AutoCurrentFabricRemover::RemoveCurrentFabric(this, remoteDeviceId);
1176 : }
1177 :
1178 0 : void DeviceCommissioner::RendezvousCleanup(CHIP_ERROR status)
1179 : {
1180 0 : if (mDeviceInPASEEstablishment != nullptr)
1181 : {
1182 : // Release the commissionee device. For BLE, this is stored,
1183 : // for IP commissioning, we have taken a reference to the
1184 : // operational node to send the completion command.
1185 0 : ReleaseCommissioneeDevice(mDeviceInPASEEstablishment);
1186 :
1187 0 : if (mPairingDelegate != nullptr)
1188 : {
1189 0 : mPairingDelegate->OnPairingComplete(status, std::nullopt, std::nullopt);
1190 : }
1191 : }
1192 0 : }
1193 :
1194 0 : void DeviceCommissioner::OnSessionEstablishmentError(CHIP_ERROR err)
1195 : {
1196 : MATTER_LOG_METRIC_END(kMetricDeviceCommissionerPASESession, err);
1197 :
1198 0 : mRendezvousParametersForPASEEstablishment.reset();
1199 :
1200 0 : if (mPairingDelegate != nullptr)
1201 : {
1202 0 : mPairingDelegate->OnStatusUpdate(DevicePairingDelegate::SecurePairingFailed);
1203 : }
1204 :
1205 0 : RendezvousCleanup(err);
1206 0 : }
1207 :
1208 0 : void DeviceCommissioner::OnSessionEstablished(const SessionHandle & session)
1209 : {
1210 : // PASE session established.
1211 0 : CommissioneeDeviceProxy * device = mDeviceInPASEEstablishment;
1212 :
1213 : // We are in the callback for this pairing. Reset so we can pair another device.
1214 0 : mDeviceInPASEEstablishment = nullptr;
1215 :
1216 : // Make sure to clear out mRendezvousParametersForPASEEstablishment no
1217 : // matter what.
1218 0 : std::optional<RendezvousParameters> paseParameters;
1219 0 : paseParameters.swap(mRendezvousParametersForPASEEstablishment);
1220 :
1221 0 : VerifyOrReturn(device != nullptr, OnSessionEstablishmentError(CHIP_ERROR_INVALID_DEVICE_DESCRIPTOR));
1222 :
1223 0 : CHIP_ERROR err = device->SetConnected(session);
1224 0 : if (err != CHIP_NO_ERROR)
1225 : {
1226 0 : ChipLogError(Controller, "Failed in setting up secure channel: %" CHIP_ERROR_FORMAT, err.Format());
1227 0 : OnSessionEstablishmentError(err);
1228 0 : return;
1229 : }
1230 :
1231 0 : ChipLogDetail(Controller, "Remote device completed SPAKE2+ handshake");
1232 :
1233 : MATTER_LOG_METRIC_END(kMetricDeviceCommissionerPASESession, CHIP_NO_ERROR);
1234 0 : if (mPairingDelegate != nullptr)
1235 : {
1236 : // If we started with a string payload, then at this point mPairingDelegate is
1237 : // mSetUpCodePairer, and it will provide the right SetupPayload argument to
1238 : // OnPairingComplete as needed. If mPairingDelegate is not
1239 : // mSetUpCodePairer, then we don't have a SetupPayload to provide.
1240 0 : mPairingDelegate->OnPairingComplete(CHIP_NO_ERROR, paseParameters, std::nullopt);
1241 : }
1242 :
1243 0 : if (mRunCommissioningAfterConnection)
1244 : {
1245 0 : mRunCommissioningAfterConnection = false;
1246 : MATTER_LOG_METRIC_BEGIN(kMetricDeviceCommissionerCommission);
1247 0 : mDefaultCommissioner->StartCommissioning(this, device);
1248 : }
1249 : }
1250 :
1251 0 : CHIP_ERROR DeviceCommissioner::SendCertificateChainRequestCommand(DeviceProxy * device,
1252 : Credentials::CertificateType certificateType,
1253 : Optional<System::Clock::Timeout> timeout)
1254 : {
1255 : MATTER_TRACE_SCOPE("SendCertificateChainRequestCommand", "DeviceCommissioner");
1256 0 : ChipLogDetail(Controller, "Sending Certificate Chain request to %p device", device);
1257 0 : VerifyOrReturnError(device != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
1258 :
1259 0 : OperationalCredentials::Commands::CertificateChainRequest::Type request;
1260 0 : request.certificateType = static_cast<OperationalCredentials::CertificateChainTypeEnum>(certificateType);
1261 0 : return SendCommissioningCommand(device, request, OnCertificateChainResponse, OnCertificateChainFailureResponse, kRootEndpointId,
1262 0 : timeout);
1263 : }
1264 :
1265 0 : void DeviceCommissioner::OnCertificateChainFailureResponse(void * context, CHIP_ERROR error)
1266 : {
1267 : MATTER_TRACE_SCOPE("OnCertificateChainFailureResponse", "DeviceCommissioner");
1268 0 : ChipLogProgress(Controller, "Device failed to receive the Certificate Chain request Response: %" CHIP_ERROR_FORMAT,
1269 : error.Format());
1270 0 : DeviceCommissioner * commissioner = reinterpret_cast<DeviceCommissioner *>(context);
1271 0 : commissioner->CommissioningStageComplete(error);
1272 0 : }
1273 :
1274 0 : void DeviceCommissioner::OnCertificateChainResponse(
1275 : void * context, const chip::app::Clusters::OperationalCredentials::Commands::CertificateChainResponse::DecodableType & response)
1276 : {
1277 : MATTER_TRACE_SCOPE("OnCertificateChainResponse", "DeviceCommissioner");
1278 0 : ChipLogProgress(Controller, "Received certificate chain from the device");
1279 0 : DeviceCommissioner * commissioner = reinterpret_cast<DeviceCommissioner *>(context);
1280 :
1281 0 : CommissioningDelegate::CommissioningReport report;
1282 0 : report.Set<RequestedCertificate>(RequestedCertificate(response.certificate));
1283 :
1284 0 : commissioner->CommissioningStageComplete(CHIP_NO_ERROR, report);
1285 0 : }
1286 :
1287 0 : CHIP_ERROR DeviceCommissioner::SendAttestationRequestCommand(DeviceProxy * device, const ByteSpan & attestationNonce,
1288 : Optional<System::Clock::Timeout> timeout)
1289 : {
1290 : MATTER_TRACE_SCOPE("SendAttestationRequestCommand", "DeviceCommissioner");
1291 0 : ChipLogDetail(Controller, "Sending Attestation request to %p device", device);
1292 0 : VerifyOrReturnError(device != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
1293 :
1294 0 : OperationalCredentials::Commands::AttestationRequest::Type request;
1295 0 : request.attestationNonce = attestationNonce;
1296 :
1297 0 : ReturnErrorOnFailure(
1298 : SendCommissioningCommand(device, request, OnAttestationResponse, OnAttestationFailureResponse, kRootEndpointId, timeout));
1299 0 : ChipLogDetail(Controller, "Sent Attestation request, waiting for the Attestation Information");
1300 0 : return CHIP_NO_ERROR;
1301 : }
1302 :
1303 0 : void DeviceCommissioner::OnAttestationFailureResponse(void * context, CHIP_ERROR error)
1304 : {
1305 : MATTER_TRACE_SCOPE("OnAttestationFailureResponse", "DeviceCommissioner");
1306 0 : ChipLogProgress(Controller, "Device failed to receive the Attestation Information Response: %" CHIP_ERROR_FORMAT,
1307 : error.Format());
1308 0 : DeviceCommissioner * commissioner = reinterpret_cast<DeviceCommissioner *>(context);
1309 0 : commissioner->CommissioningStageComplete(error);
1310 0 : }
1311 :
1312 0 : void DeviceCommissioner::OnAttestationResponse(void * context,
1313 : const OperationalCredentials::Commands::AttestationResponse::DecodableType & data)
1314 : {
1315 : MATTER_TRACE_SCOPE("OnAttestationResponse", "DeviceCommissioner");
1316 0 : ChipLogProgress(Controller, "Received Attestation Information from the device");
1317 0 : DeviceCommissioner * commissioner = reinterpret_cast<DeviceCommissioner *>(context);
1318 :
1319 0 : CommissioningDelegate::CommissioningReport report;
1320 0 : report.Set<AttestationResponse>(AttestationResponse(data.attestationElements, data.attestationSignature));
1321 0 : commissioner->CommissioningStageComplete(CHIP_NO_ERROR, report);
1322 0 : }
1323 :
1324 0 : void DeviceCommissioner::OnDeviceAttestationInformationVerification(
1325 : void * context, const Credentials::DeviceAttestationVerifier::AttestationInfo & info, AttestationVerificationResult result)
1326 : {
1327 : MATTER_TRACE_SCOPE("OnDeviceAttestationInformationVerification", "DeviceCommissioner");
1328 0 : DeviceCommissioner * commissioner = reinterpret_cast<DeviceCommissioner *>(context);
1329 :
1330 0 : if (commissioner->mCommissioningStage == CommissioningStage::kAttestationVerification)
1331 : {
1332 : // Check for revoked DAC Chain before calling delegate. Enter next stage.
1333 :
1334 0 : CommissioningDelegate::CommissioningReport report;
1335 0 : report.Set<AttestationErrorInfo>(result);
1336 :
1337 0 : return commissioner->CommissioningStageComplete(
1338 0 : result == AttestationVerificationResult::kSuccess ? CHIP_NO_ERROR : CHIP_ERROR_FAILED_DEVICE_ATTESTATION, report);
1339 0 : }
1340 :
1341 0 : if (!commissioner->mDeviceBeingCommissioned)
1342 : {
1343 0 : ChipLogError(Controller, "Device attestation verification result received when we're not commissioning a device");
1344 0 : return;
1345 : }
1346 :
1347 0 : auto & params = commissioner->mDefaultCommissioner->GetCommissioningParameters();
1348 0 : Credentials::DeviceAttestationDelegate * deviceAttestationDelegate = params.GetDeviceAttestationDelegate();
1349 :
1350 0 : if (params.GetCompletionStatus().attestationResult.HasValue())
1351 : {
1352 0 : auto previousResult = params.GetCompletionStatus().attestationResult.Value();
1353 0 : if (previousResult != AttestationVerificationResult::kSuccess)
1354 : {
1355 0 : result = previousResult;
1356 : }
1357 : }
1358 :
1359 0 : if (result != AttestationVerificationResult::kSuccess)
1360 : {
1361 0 : CommissioningDelegate::CommissioningReport report;
1362 0 : report.Set<AttestationErrorInfo>(result);
1363 0 : if (result == AttestationVerificationResult::kNotImplemented)
1364 : {
1365 0 : ChipLogError(Controller,
1366 : "Failed in verifying 'Attestation Information' command received from the device due to default "
1367 : "DeviceAttestationVerifier Class not being overridden by a real implementation.");
1368 0 : commissioner->CommissioningStageComplete(CHIP_ERROR_NOT_IMPLEMENTED, report);
1369 0 : return;
1370 : }
1371 :
1372 0 : ChipLogError(Controller, "Failed in verifying 'Attestation Information' command received from the device: err %hu (%s)",
1373 : static_cast<uint16_t>(result), GetAttestationResultDescription(result));
1374 : // Go look at AttestationVerificationResult enum in src/credentials/attestation_verifier/DeviceAttestationVerifier.h to
1375 : // understand the errors.
1376 :
1377 : // If a device attestation status delegate is installed, delegate handling of failure to the client and let them
1378 : // decide on whether to proceed further or not.
1379 0 : if (deviceAttestationDelegate)
1380 : {
1381 0 : commissioner->ExtendArmFailSafeForDeviceAttestation(info, result);
1382 : }
1383 : else
1384 : {
1385 0 : commissioner->CommissioningStageComplete(CHIP_ERROR_FAILED_DEVICE_ATTESTATION, report);
1386 : }
1387 0 : }
1388 : else
1389 : {
1390 0 : if (deviceAttestationDelegate && deviceAttestationDelegate->ShouldWaitAfterDeviceAttestation())
1391 : {
1392 0 : commissioner->ExtendArmFailSafeForDeviceAttestation(info, result);
1393 : }
1394 : else
1395 : {
1396 0 : ChipLogProgress(Controller, "Successfully validated 'Attestation Information' command received from the device.");
1397 0 : commissioner->CommissioningStageComplete(CHIP_NO_ERROR);
1398 : }
1399 : }
1400 : }
1401 :
1402 0 : void DeviceCommissioner::OnArmFailSafeExtendedForDeviceAttestation(
1403 : void * context, const GeneralCommissioning::Commands::ArmFailSafeResponse::DecodableType &)
1404 : {
1405 0 : ChipLogProgress(Controller, "Successfully extended fail-safe timer to handle DA failure");
1406 0 : DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
1407 :
1408 : // We have completed our command invoke, but we're not going to finish the
1409 : // commissioning step until our client examines the attestation
1410 : // information. Clear out mInvokeCancelFn (which points at the
1411 : // CommandSender we just finished using) now, so it's not dangling.
1412 0 : commissioner->mInvokeCancelFn = nullptr;
1413 :
1414 0 : commissioner->HandleDeviceAttestationCompleted();
1415 0 : }
1416 :
1417 0 : void DeviceCommissioner::HandleDeviceAttestationCompleted()
1418 : {
1419 0 : if (!mDeviceBeingCommissioned)
1420 : {
1421 0 : return;
1422 : }
1423 :
1424 0 : auto & params = mDefaultCommissioner->GetCommissioningParameters();
1425 0 : Credentials::DeviceAttestationDelegate * deviceAttestationDelegate = params.GetDeviceAttestationDelegate();
1426 0 : if (deviceAttestationDelegate)
1427 : {
1428 0 : ChipLogProgress(Controller, "Device attestation completed, delegating continuation to client");
1429 0 : deviceAttestationDelegate->OnDeviceAttestationCompleted(this, mDeviceBeingCommissioned, *mAttestationDeviceInfo,
1430 : mAttestationResult);
1431 : }
1432 : else
1433 : {
1434 0 : ChipLogError(Controller, "Need to wait for device attestation delegate, but no delegate available. Failing commissioning");
1435 0 : CommissioningDelegate::CommissioningReport report;
1436 0 : report.Set<AttestationErrorInfo>(mAttestationResult);
1437 0 : CommissioningStageComplete(CHIP_ERROR_INTERNAL, report);
1438 0 : }
1439 : }
1440 :
1441 0 : void DeviceCommissioner::OnFailedToExtendedArmFailSafeDeviceAttestation(void * context, CHIP_ERROR error)
1442 : {
1443 0 : ChipLogProgress(Controller, "Failed to extend fail-safe timer to handle attestation failure: %" CHIP_ERROR_FORMAT,
1444 : error.Format());
1445 0 : DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
1446 :
1447 0 : CommissioningDelegate::CommissioningReport report;
1448 0 : report.Set<AttestationErrorInfo>(commissioner->mAttestationResult);
1449 0 : commissioner->CommissioningStageComplete(CHIP_ERROR_INTERNAL, report);
1450 0 : }
1451 :
1452 0 : void DeviceCommissioner::OnICDManagementRegisterClientResponse(
1453 : void * context, const app::Clusters::IcdManagement::Commands::RegisterClientResponse::DecodableType & data)
1454 : {
1455 0 : CHIP_ERROR err = CHIP_NO_ERROR;
1456 0 : DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
1457 0 : VerifyOrExit(commissioner != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
1458 0 : VerifyOrExit(commissioner->mCommissioningStage == CommissioningStage::kICDRegistration, err = CHIP_ERROR_INCORRECT_STATE);
1459 0 : VerifyOrExit(commissioner->mDeviceBeingCommissioned != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
1460 :
1461 0 : if (commissioner->mPairingDelegate != nullptr)
1462 : {
1463 0 : commissioner->mPairingDelegate->OnICDRegistrationComplete(
1464 0 : ScopedNodeId(commissioner->mDeviceBeingCommissioned->GetDeviceId(), commissioner->GetFabricIndex()), data.ICDCounter);
1465 : }
1466 :
1467 0 : exit:
1468 0 : CommissioningDelegate::CommissioningReport report;
1469 0 : commissioner->CommissioningStageComplete(err, report);
1470 0 : }
1471 :
1472 0 : void DeviceCommissioner::OnICDManagementStayActiveResponse(
1473 : void * context, const app::Clusters::IcdManagement::Commands::StayActiveResponse::DecodableType & data)
1474 : {
1475 0 : CHIP_ERROR err = CHIP_NO_ERROR;
1476 0 : DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
1477 0 : VerifyOrExit(commissioner != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
1478 0 : VerifyOrExit(commissioner->mCommissioningStage == CommissioningStage::kICDSendStayActive, err = CHIP_ERROR_INCORRECT_STATE);
1479 0 : VerifyOrExit(commissioner->mDeviceBeingCommissioned != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
1480 :
1481 0 : if (commissioner->mPairingDelegate != nullptr)
1482 : {
1483 0 : commissioner->mPairingDelegate->OnICDStayActiveComplete(
1484 :
1485 0 : ScopedNodeId(commissioner->mDeviceBeingCommissioned->GetDeviceId(), commissioner->GetFabricIndex()),
1486 0 : data.promisedActiveDuration);
1487 : }
1488 :
1489 0 : exit:
1490 0 : CommissioningDelegate::CommissioningReport report;
1491 0 : commissioner->CommissioningStageComplete(CHIP_NO_ERROR, report);
1492 0 : }
1493 :
1494 0 : bool DeviceCommissioner::ExtendArmFailSafeInternal(DeviceProxy * proxy, CommissioningStage step, uint16_t armFailSafeTimeout,
1495 : Optional<System::Clock::Timeout> commandTimeout,
1496 : OnExtendFailsafeSuccess onSuccess, OnExtendFailsafeFailure onFailure,
1497 : bool fireAndForget)
1498 : {
1499 : using namespace System;
1500 : using namespace System::Clock;
1501 0 : auto now = SystemClock().GetMonotonicTimestamp();
1502 0 : auto newFailSafeTimeout = now + Seconds16(armFailSafeTimeout);
1503 0 : if (newFailSafeTimeout < proxy->GetFailSafeExpirationTimestamp())
1504 : {
1505 0 : ChipLogProgress(
1506 : Controller, "Skipping arming failsafe: new time (%u seconds from now) before old time (%u seconds from now)",
1507 : armFailSafeTimeout, std::chrono::duration_cast<Seconds16>(proxy->GetFailSafeExpirationTimestamp() - now).count());
1508 0 : return false;
1509 : }
1510 :
1511 0 : uint64_t breadcrumb = static_cast<uint64_t>(step);
1512 0 : GeneralCommissioning::Commands::ArmFailSafe::Type request;
1513 0 : request.expiryLengthSeconds = armFailSafeTimeout;
1514 0 : request.breadcrumb = breadcrumb;
1515 0 : ChipLogProgress(Controller, "Arming failsafe (%u seconds)", request.expiryLengthSeconds);
1516 0 : CHIP_ERROR err = SendCommissioningCommand(proxy, request, onSuccess, onFailure, kRootEndpointId, commandTimeout, fireAndForget);
1517 0 : if (err != CHIP_NO_ERROR)
1518 : {
1519 0 : onFailure((!fireAndForget) ? this : nullptr, err);
1520 0 : return true; // we have called onFailure already
1521 : }
1522 :
1523 : // Note: The stored timestamp may become invalid if we fail asynchronously
1524 0 : proxy->SetFailSafeExpirationTimestamp(newFailSafeTimeout);
1525 0 : return true;
1526 : }
1527 :
1528 0 : void DeviceCommissioner::ExtendArmFailSafeForDeviceAttestation(const Credentials::DeviceAttestationVerifier::AttestationInfo & info,
1529 : Credentials::AttestationVerificationResult result)
1530 : {
1531 0 : mAttestationResult = result;
1532 :
1533 0 : auto & params = mDefaultCommissioner->GetCommissioningParameters();
1534 0 : Credentials::DeviceAttestationDelegate * deviceAttestationDelegate = params.GetDeviceAttestationDelegate();
1535 :
1536 0 : mAttestationDeviceInfo = Platform::MakeUnique<Credentials::DeviceAttestationVerifier::AttestationDeviceInfo>(info);
1537 :
1538 0 : auto expiryLengthSeconds = deviceAttestationDelegate->FailSafeExpiryTimeoutSecs();
1539 0 : bool waitForFailsafeExtension = expiryLengthSeconds.HasValue();
1540 0 : if (waitForFailsafeExtension)
1541 : {
1542 0 : ChipLogProgress(Controller, "Changing fail-safe timer to %u seconds to handle DA failure", expiryLengthSeconds.Value());
1543 : // Per spec, anything we do with the fail-safe armed must not time out
1544 : // in less than kMinimumCommissioningStepTimeout.
1545 : waitForFailsafeExtension =
1546 0 : ExtendArmFailSafeInternal(mDeviceBeingCommissioned, mCommissioningStage, expiryLengthSeconds.Value(),
1547 0 : MakeOptional(kMinimumCommissioningStepTimeout), OnArmFailSafeExtendedForDeviceAttestation,
1548 : OnFailedToExtendedArmFailSafeDeviceAttestation, /* fireAndForget = */ false);
1549 : }
1550 : else
1551 : {
1552 0 : ChipLogProgress(Controller, "Proceeding without changing fail-safe timer value as delegate has not set it");
1553 : }
1554 :
1555 0 : if (!waitForFailsafeExtension)
1556 : {
1557 0 : HandleDeviceAttestationCompleted();
1558 : }
1559 0 : }
1560 :
1561 0 : CHIP_ERROR DeviceCommissioner::ValidateAttestationInfo(const Credentials::DeviceAttestationVerifier::AttestationInfo & info)
1562 : {
1563 : MATTER_TRACE_SCOPE("ValidateAttestationInfo", "DeviceCommissioner");
1564 0 : VerifyOrReturnError(mState == State::Initialized, CHIP_ERROR_INCORRECT_STATE);
1565 0 : VerifyOrReturnError(mDeviceAttestationVerifier != nullptr, CHIP_ERROR_INCORRECT_STATE);
1566 :
1567 0 : mDeviceAttestationVerifier->VerifyAttestationInformation(info, &mDeviceAttestationInformationVerificationCallback);
1568 :
1569 : // TODO: Validate Firmware Information
1570 :
1571 0 : return CHIP_NO_ERROR;
1572 : }
1573 :
1574 : CHIP_ERROR
1575 0 : DeviceCommissioner::CheckForRevokedDACChain(const Credentials::DeviceAttestationVerifier::AttestationInfo & info)
1576 : {
1577 : MATTER_TRACE_SCOPE("CheckForRevokedDACChain", "DeviceCommissioner");
1578 0 : VerifyOrReturnError(mState == State::Initialized, CHIP_ERROR_INCORRECT_STATE);
1579 0 : VerifyOrReturnError(mDeviceAttestationVerifier != nullptr, CHIP_ERROR_INCORRECT_STATE);
1580 :
1581 0 : mDeviceAttestationVerifier->CheckForRevokedDACChain(info, &mDeviceAttestationInformationVerificationCallback);
1582 :
1583 0 : return CHIP_NO_ERROR;
1584 : }
1585 :
1586 0 : CHIP_ERROR DeviceCommissioner::ValidateCSR(DeviceProxy * proxy, const ByteSpan & NOCSRElements,
1587 : const ByteSpan & AttestationSignature, const ByteSpan & dac, const ByteSpan & csrNonce)
1588 : {
1589 : MATTER_TRACE_SCOPE("ValidateCSR", "DeviceCommissioner");
1590 0 : VerifyOrReturnError(mState == State::Initialized, CHIP_ERROR_INCORRECT_STATE);
1591 0 : VerifyOrReturnError(mDeviceAttestationVerifier != nullptr, CHIP_ERROR_INCORRECT_STATE);
1592 :
1593 0 : P256PublicKey dacPubkey;
1594 0 : ReturnErrorOnFailure(ExtractPubkeyFromX509Cert(dac, dacPubkey));
1595 :
1596 : // Retrieve attestation challenge
1597 : ByteSpan attestationChallenge =
1598 0 : proxy->GetSecureSession().Value()->AsSecureSession()->GetCryptoContext().GetAttestationChallenge();
1599 :
1600 : // The operational CA should also verify this on its end during NOC generation, if end-to-end attestation is desired.
1601 0 : return mDeviceAttestationVerifier->VerifyNodeOperationalCSRInformation(NOCSRElements, attestationChallenge,
1602 0 : AttestationSignature, dacPubkey, csrNonce);
1603 0 : }
1604 :
1605 0 : CHIP_ERROR DeviceCommissioner::SendOperationalCertificateSigningRequestCommand(DeviceProxy * device, const ByteSpan & csrNonce,
1606 : Optional<System::Clock::Timeout> timeout)
1607 : {
1608 : MATTER_TRACE_SCOPE("SendOperationalCertificateSigningRequestCommand", "DeviceCommissioner");
1609 0 : ChipLogDetail(Controller, "Sending CSR request to %p device", device);
1610 0 : VerifyOrReturnError(device != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
1611 :
1612 0 : OperationalCredentials::Commands::CSRRequest::Type request;
1613 0 : request.CSRNonce = csrNonce;
1614 :
1615 0 : ReturnErrorOnFailure(SendCommissioningCommand(device, request, OnOperationalCertificateSigningRequest, OnCSRFailureResponse,
1616 : kRootEndpointId, timeout));
1617 0 : ChipLogDetail(Controller, "Sent CSR request, waiting for the CSR");
1618 0 : return CHIP_NO_ERROR;
1619 : }
1620 :
1621 0 : void DeviceCommissioner::OnCSRFailureResponse(void * context, CHIP_ERROR error)
1622 : {
1623 : MATTER_TRACE_SCOPE("OnCSRFailureResponse", "DeviceCommissioner");
1624 0 : ChipLogProgress(Controller, "Device failed to receive the CSR request Response: %" CHIP_ERROR_FORMAT, error.Format());
1625 0 : DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
1626 0 : commissioner->CommissioningStageComplete(error);
1627 0 : }
1628 :
1629 0 : void DeviceCommissioner::OnOperationalCertificateSigningRequest(
1630 : void * context, const OperationalCredentials::Commands::CSRResponse::DecodableType & data)
1631 : {
1632 : MATTER_TRACE_SCOPE("OnOperationalCertificateSigningRequest", "DeviceCommissioner");
1633 0 : ChipLogProgress(Controller, "Received certificate signing request from the device");
1634 0 : DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
1635 :
1636 0 : CommissioningDelegate::CommissioningReport report;
1637 0 : report.Set<CSRResponse>(CSRResponse(data.NOCSRElements, data.attestationSignature));
1638 0 : commissioner->CommissioningStageComplete(CHIP_NO_ERROR, report);
1639 0 : }
1640 :
1641 0 : void DeviceCommissioner::OnDeviceNOCChainGeneration(void * context, CHIP_ERROR status, const ByteSpan & noc, const ByteSpan & icac,
1642 : const ByteSpan & rcac, Optional<IdentityProtectionKeySpan> ipk,
1643 : Optional<NodeId> adminSubject)
1644 : {
1645 : MATTER_TRACE_SCOPE("OnDeviceNOCChainGeneration", "DeviceCommissioner");
1646 0 : DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
1647 :
1648 : // The placeholder IPK is not satisfactory, but is there to fill the NocChain struct on error. It will still fail.
1649 0 : const uint8_t placeHolderIpk[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1650 : 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1651 0 : if (status == CHIP_NO_ERROR && !ipk.HasValue())
1652 : {
1653 0 : ChipLogError(Controller, "Did not have an IPK from the OperationalCredentialsIssuer! Cannot commission.");
1654 0 : status = CHIP_ERROR_INVALID_ARGUMENT;
1655 : }
1656 :
1657 0 : ChipLogProgress(Controller, "Received callback from the CA for NOC Chain generation. Status: %" CHIP_ERROR_FORMAT,
1658 : status.Format());
1659 0 : if (status == CHIP_NO_ERROR && commissioner->mState != State::Initialized)
1660 : {
1661 0 : status = CHIP_ERROR_INCORRECT_STATE;
1662 : }
1663 0 : if (status != CHIP_NO_ERROR)
1664 : {
1665 0 : ChipLogError(Controller, "Failed in generating device's operational credentials. Error: %" CHIP_ERROR_FORMAT,
1666 : status.Format());
1667 : }
1668 :
1669 : // TODO - Verify that the generated root cert matches with commissioner's root cert
1670 0 : CommissioningDelegate::CommissioningReport report;
1671 0 : report.Set<NocChain>(NocChain(noc, icac, rcac, ipk.HasValue() ? ipk.Value() : IdentityProtectionKeySpan(placeHolderIpk),
1672 0 : adminSubject.HasValue() ? adminSubject.Value() : commissioner->GetNodeId()));
1673 0 : commissioner->CommissioningStageComplete(status, report);
1674 0 : }
1675 :
1676 0 : CHIP_ERROR DeviceCommissioner::IssueNOCChain(const ByteSpan & NOCSRElements, NodeId nodeId,
1677 : chip::Callback::Callback<OnNOCChainGeneration> * callback)
1678 : {
1679 : MATTER_TRACE_SCOPE("IssueNOCChain", "DeviceCommissioner");
1680 0 : VerifyOrReturnError(mState == State::Initialized, CHIP_ERROR_INCORRECT_STATE);
1681 :
1682 0 : ChipLogProgress(Controller, "Getting certificate chain for the device on fabric idx %u", static_cast<unsigned>(mFabricIndex));
1683 :
1684 0 : mOperationalCredentialsDelegate->SetNodeIdForNextNOCRequest(nodeId);
1685 :
1686 0 : if (mFabricIndex != kUndefinedFabricIndex)
1687 : {
1688 0 : mOperationalCredentialsDelegate->SetFabricIdForNextNOCRequest(GetFabricId());
1689 : }
1690 :
1691 : // Note: we don't have attestationSignature, attestationChallenge, DAC, PAI so we are just providing an empty ByteSpan
1692 : // for those arguments.
1693 0 : return mOperationalCredentialsDelegate->GenerateNOCChain(NOCSRElements, ByteSpan(), ByteSpan(), ByteSpan(), ByteSpan(),
1694 0 : ByteSpan(), callback);
1695 : }
1696 :
1697 0 : CHIP_ERROR DeviceCommissioner::ProcessCSR(DeviceProxy * proxy, const ByteSpan & NOCSRElements,
1698 : const ByteSpan & AttestationSignature, const ByteSpan & dac, const ByteSpan & pai,
1699 : const ByteSpan & csrNonce)
1700 : {
1701 : MATTER_TRACE_SCOPE("ProcessOpCSR", "DeviceCommissioner");
1702 0 : VerifyOrReturnError(mState == State::Initialized, CHIP_ERROR_INCORRECT_STATE);
1703 :
1704 0 : ChipLogProgress(Controller, "Getting certificate chain for the device from the issuer");
1705 :
1706 0 : P256PublicKey dacPubkey;
1707 0 : ReturnErrorOnFailure(ExtractPubkeyFromX509Cert(dac, dacPubkey));
1708 :
1709 : // Retrieve attestation challenge
1710 : ByteSpan attestationChallenge =
1711 0 : proxy->GetSecureSession().Value()->AsSecureSession()->GetCryptoContext().GetAttestationChallenge();
1712 :
1713 0 : mOperationalCredentialsDelegate->SetNodeIdForNextNOCRequest(proxy->GetDeviceId());
1714 :
1715 0 : if (mFabricIndex != kUndefinedFabricIndex)
1716 : {
1717 0 : mOperationalCredentialsDelegate->SetFabricIdForNextNOCRequest(GetFabricId());
1718 : }
1719 :
1720 0 : return mOperationalCredentialsDelegate->GenerateNOCChain(NOCSRElements, csrNonce, AttestationSignature, attestationChallenge,
1721 0 : dac, pai, &mDeviceNOCChainCallback);
1722 0 : }
1723 :
1724 0 : CHIP_ERROR DeviceCommissioner::SendOperationalCertificate(DeviceProxy * device, const ByteSpan & nocCertBuf,
1725 : const Optional<ByteSpan> & icaCertBuf,
1726 : const IdentityProtectionKeySpan ipk, const NodeId adminSubject,
1727 : Optional<System::Clock::Timeout> timeout)
1728 : {
1729 : MATTER_TRACE_SCOPE("SendOperationalCertificate", "DeviceCommissioner");
1730 :
1731 0 : VerifyOrReturnError(device != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
1732 :
1733 0 : OperationalCredentials::Commands::AddNOC::Type request;
1734 0 : request.NOCValue = nocCertBuf;
1735 0 : request.ICACValue = icaCertBuf;
1736 0 : request.IPKValue = ipk;
1737 0 : request.caseAdminSubject = adminSubject;
1738 0 : request.adminVendorId = mVendorId;
1739 :
1740 0 : ReturnErrorOnFailure(SendCommissioningCommand(device, request, OnOperationalCertificateAddResponse, OnAddNOCFailureResponse,
1741 : kRootEndpointId, timeout));
1742 :
1743 0 : ChipLogProgress(Controller, "Sent operational certificate to the device");
1744 :
1745 0 : return CHIP_NO_ERROR;
1746 : }
1747 :
1748 0 : CHIP_ERROR DeviceCommissioner::ConvertFromOperationalCertStatus(OperationalCredentials::NodeOperationalCertStatusEnum err)
1749 : {
1750 : using OperationalCredentials::NodeOperationalCertStatusEnum;
1751 0 : switch (err)
1752 : {
1753 0 : case NodeOperationalCertStatusEnum::kOk:
1754 0 : return CHIP_NO_ERROR;
1755 0 : case NodeOperationalCertStatusEnum::kInvalidPublicKey:
1756 0 : return CHIP_ERROR_INVALID_PUBLIC_KEY;
1757 0 : case NodeOperationalCertStatusEnum::kInvalidNodeOpId:
1758 0 : return CHIP_ERROR_WRONG_NODE_ID;
1759 0 : case NodeOperationalCertStatusEnum::kInvalidNOC:
1760 0 : return CHIP_ERROR_UNSUPPORTED_CERT_FORMAT;
1761 0 : case NodeOperationalCertStatusEnum::kMissingCsr:
1762 0 : return CHIP_ERROR_INCORRECT_STATE;
1763 0 : case NodeOperationalCertStatusEnum::kTableFull:
1764 0 : return CHIP_ERROR_NO_MEMORY;
1765 0 : case NodeOperationalCertStatusEnum::kInvalidAdminSubject:
1766 0 : return CHIP_ERROR_INVALID_ADMIN_SUBJECT;
1767 0 : case NodeOperationalCertStatusEnum::kFabricConflict:
1768 0 : return CHIP_ERROR_FABRIC_EXISTS;
1769 0 : case NodeOperationalCertStatusEnum::kLabelConflict:
1770 0 : return CHIP_ERROR_INVALID_ARGUMENT;
1771 0 : case NodeOperationalCertStatusEnum::kInvalidFabricIndex:
1772 0 : return CHIP_ERROR_INVALID_FABRIC_INDEX;
1773 0 : case NodeOperationalCertStatusEnum::kUnknownEnumValue:
1774 : // Is this a reasonable value?
1775 0 : return CHIP_ERROR_CERT_LOAD_FAILED;
1776 : }
1777 :
1778 0 : return CHIP_ERROR_CERT_LOAD_FAILED;
1779 : }
1780 :
1781 0 : void DeviceCommissioner::OnAddNOCFailureResponse(void * context, CHIP_ERROR error)
1782 : {
1783 : MATTER_TRACE_SCOPE("OnAddNOCFailureResponse", "DeviceCommissioner");
1784 0 : ChipLogProgress(Controller, "Device failed to receive the operational certificate Response: %" CHIP_ERROR_FORMAT,
1785 : error.Format());
1786 0 : DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
1787 0 : commissioner->CommissioningStageComplete(error);
1788 0 : }
1789 :
1790 0 : void DeviceCommissioner::OnOperationalCertificateAddResponse(
1791 : void * context, const OperationalCredentials::Commands::NOCResponse::DecodableType & data)
1792 : {
1793 : MATTER_TRACE_SCOPE("OnOperationalCertificateAddResponse", "DeviceCommissioner");
1794 0 : ChipLogProgress(Controller, "Device returned status %d on receiving the NOC", to_underlying(data.statusCode));
1795 0 : DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
1796 :
1797 0 : CHIP_ERROR err = CHIP_NO_ERROR;
1798 :
1799 0 : VerifyOrExit(commissioner->mState == State::Initialized, err = CHIP_ERROR_INCORRECT_STATE);
1800 :
1801 0 : VerifyOrExit(commissioner->mDeviceBeingCommissioned != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
1802 :
1803 0 : err = ConvertFromOperationalCertStatus(data.statusCode);
1804 0 : SuccessOrExit(err);
1805 :
1806 0 : err = commissioner->OnOperationalCredentialsProvisioningCompletion(commissioner->mDeviceBeingCommissioned);
1807 :
1808 0 : exit:
1809 0 : if (err != CHIP_NO_ERROR)
1810 : {
1811 0 : ChipLogProgress(Controller, "Add NOC failed with error: %" CHIP_ERROR_FORMAT, err.Format());
1812 0 : commissioner->CommissioningStageComplete(err);
1813 : }
1814 0 : }
1815 :
1816 0 : CHIP_ERROR DeviceCommissioner::SendTrustedRootCertificate(DeviceProxy * device, const ByteSpan & rcac,
1817 : Optional<System::Clock::Timeout> timeout)
1818 : {
1819 : MATTER_TRACE_SCOPE("SendTrustedRootCertificate", "DeviceCommissioner");
1820 0 : VerifyOrReturnError(device != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
1821 :
1822 0 : ChipLogProgress(Controller, "Sending root certificate to the device");
1823 :
1824 0 : OperationalCredentials::Commands::AddTrustedRootCertificate::Type request;
1825 0 : request.rootCACertificate = rcac;
1826 0 : ReturnErrorOnFailure(
1827 : SendCommissioningCommand(device, request, OnRootCertSuccessResponse, OnRootCertFailureResponse, kRootEndpointId, timeout));
1828 :
1829 0 : ChipLogProgress(Controller, "Sent root certificate to the device");
1830 :
1831 0 : return CHIP_NO_ERROR;
1832 : }
1833 :
1834 0 : void DeviceCommissioner::OnRootCertSuccessResponse(void * context, const chip::app::DataModel::NullObjectType &)
1835 : {
1836 : MATTER_TRACE_SCOPE("OnRootCertSuccessResponse", "DeviceCommissioner");
1837 0 : ChipLogProgress(Controller, "Device confirmed that it has received the root certificate");
1838 0 : DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
1839 0 : commissioner->CommissioningStageComplete(CHIP_NO_ERROR);
1840 0 : }
1841 :
1842 0 : void DeviceCommissioner::OnRootCertFailureResponse(void * context, CHIP_ERROR error)
1843 : {
1844 : MATTER_TRACE_SCOPE("OnRootCertFailureResponse", "DeviceCommissioner");
1845 0 : ChipLogProgress(Controller, "Device failed to receive the root certificate Response: %" CHIP_ERROR_FORMAT, error.Format());
1846 0 : DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
1847 0 : commissioner->CommissioningStageComplete(error);
1848 0 : }
1849 :
1850 0 : CHIP_ERROR DeviceCommissioner::OnOperationalCredentialsProvisioningCompletion(DeviceProxy * device)
1851 : {
1852 : MATTER_TRACE_SCOPE("OnOperationalCredentialsProvisioningCompletion", "DeviceCommissioner");
1853 0 : ChipLogProgress(Controller, "Operational credentials provisioned on device %p", device);
1854 0 : VerifyOrReturnError(device != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
1855 :
1856 0 : if (mPairingDelegate != nullptr)
1857 : {
1858 0 : mPairingDelegate->OnStatusUpdate(DevicePairingDelegate::SecurePairingSuccess);
1859 : }
1860 0 : CommissioningStageComplete(CHIP_NO_ERROR);
1861 :
1862 0 : return CHIP_NO_ERROR;
1863 : }
1864 :
1865 : #if CONFIG_NETWORK_LAYER_BLE
1866 : #if CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE
1867 : void DeviceCommissioner::ConnectBleTransportToSelf()
1868 : {
1869 : Transport::BLEBase & transport = std::get<Transport::BLE<1>>(mSystemState->TransportMgr()->GetTransport().GetTransports());
1870 : if (!transport.IsBleLayerTransportSetToSelf())
1871 : {
1872 : transport.SetBleLayerTransportToSelf();
1873 : }
1874 : }
1875 : #endif // CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE
1876 :
1877 0 : void DeviceCommissioner::CloseBleConnection()
1878 : {
1879 : // It is fine since we can only commission one device at the same time.
1880 : // We should be able to distinguish different BLE connections if we want
1881 : // to commission multiple devices at the same time over BLE.
1882 0 : mSystemState->BleLayer()->CloseAllBleConnections();
1883 0 : }
1884 : #endif
1885 :
1886 0 : CHIP_ERROR DeviceCommissioner::DiscoverCommissionableNodes(Dnssd::DiscoveryFilter filter)
1887 : {
1888 0 : ReturnErrorOnFailure(SetUpNodeDiscovery());
1889 0 : return mDNSResolver.DiscoverCommissionableNodes(filter);
1890 : }
1891 :
1892 0 : CHIP_ERROR DeviceCommissioner::StopCommissionableDiscovery()
1893 : {
1894 0 : return mDNSResolver.StopDiscovery();
1895 : }
1896 :
1897 0 : const Dnssd::CommissionNodeData * DeviceCommissioner::GetDiscoveredDevice(int idx)
1898 : {
1899 0 : return GetDiscoveredNode(idx);
1900 : }
1901 :
1902 : #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY // make this commissioner discoverable
1903 :
1904 : CHIP_ERROR DeviceCommissioner::SetUdcListenPort(uint16_t listenPort)
1905 : {
1906 : if (mState == State::Initialized)
1907 : {
1908 : return CHIP_ERROR_INCORRECT_STATE;
1909 : }
1910 :
1911 : mUdcListenPort = listenPort;
1912 : return CHIP_NO_ERROR;
1913 : }
1914 :
1915 : void DeviceCommissioner::FindCommissionableNode(char * instanceName)
1916 : {
1917 : Dnssd::DiscoveryFilter filter(Dnssd::DiscoveryFilterType::kInstanceName, instanceName);
1918 : DiscoverCommissionableNodes(filter);
1919 : }
1920 :
1921 : #endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY
1922 :
1923 0 : void DeviceCommissioner::OnNodeDiscovered(const chip::Dnssd::DiscoveredNodeData & nodeData)
1924 : {
1925 : #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY
1926 : if (mUdcServer != nullptr)
1927 : {
1928 : mUdcServer->OnCommissionableNodeFound(nodeData);
1929 : }
1930 : #endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY
1931 0 : AbstractDnssdDiscoveryController::OnNodeDiscovered(nodeData);
1932 0 : mSetUpCodePairer.NotifyCommissionableDeviceDiscovered(nodeData);
1933 0 : }
1934 :
1935 0 : void DeviceCommissioner::OnBasicSuccess(void * context, const chip::app::DataModel::NullObjectType &)
1936 : {
1937 0 : DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
1938 0 : commissioner->CommissioningStageComplete(CHIP_NO_ERROR);
1939 0 : }
1940 :
1941 0 : void DeviceCommissioner::OnBasicFailure(void * context, CHIP_ERROR error)
1942 : {
1943 0 : ChipLogProgress(Controller, "Received failure response: %" CHIP_ERROR_FORMAT, error.Format());
1944 0 : DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
1945 0 : commissioner->CommissioningStageComplete(error);
1946 0 : }
1947 :
1948 0 : static GeneralCommissioning::Commands::ArmFailSafe::Type DisarmFailsafeRequest()
1949 : {
1950 0 : GeneralCommissioning::Commands::ArmFailSafe::Type request;
1951 0 : request.expiryLengthSeconds = 0; // Expire immediately.
1952 0 : request.breadcrumb = 0;
1953 0 : return request;
1954 : }
1955 :
1956 0 : static void MarkForEviction(const Optional<SessionHandle> & session)
1957 : {
1958 0 : if (session.HasValue())
1959 : {
1960 0 : session.Value()->AsSecureSession()->MarkForEviction();
1961 : }
1962 0 : }
1963 :
1964 0 : void DeviceCommissioner::CleanupCommissioning(DeviceProxy * proxy, NodeId nodeId, const CompletionStatus & completionStatus)
1965 : {
1966 : // At this point, proxy == mDeviceBeingCommissioned, nodeId == mDeviceBeingCommissioned->GetDeviceId()
1967 :
1968 0 : mCommissioningCompletionStatus = completionStatus;
1969 :
1970 0 : if (completionStatus.err == CHIP_NO_ERROR)
1971 : {
1972 : // CommissioningStageComplete uses mDeviceBeingCommissioned, which can
1973 : // be commissionee if we are cleaning up before we've gone operational. Normally
1974 : // that would not happen in this non-error case, _except_ if we were told to skip sending
1975 : // CommissioningComplete: in that case we do not have an operational DeviceProxy, so
1976 : // we're using our CommissioneeDeviceProxy to do a successful cleanup.
1977 : //
1978 : // This means we have to call CommissioningStageComplete() before we destroy commissionee.
1979 : //
1980 : // This should be safe, because CommissioningStageComplete() does not call CleanupCommissioning
1981 : // when called in the cleanup stage (which is where we are), and StopPairing does not directly release
1982 : // mDeviceBeingCommissioned.
1983 0 : CommissioningStageComplete(CHIP_NO_ERROR);
1984 :
1985 0 : CommissioneeDeviceProxy * commissionee = FindCommissioneeDevice(nodeId);
1986 0 : if (commissionee != nullptr)
1987 : {
1988 0 : ReleaseCommissioneeDevice(commissionee);
1989 : }
1990 : // Send the callbacks, we're done.
1991 0 : SendCommissioningCompleteCallbacks(nodeId, mCommissioningCompletionStatus);
1992 : }
1993 0 : else if (completionStatus.err == CHIP_ERROR_CANCELLED)
1994 : {
1995 : // If we're cleaning up because cancellation has been requested via StopPairing(), expire the failsafe
1996 : // in the background and reset our state synchronously, so a new commissioning attempt can be started.
1997 0 : CommissioneeDeviceProxy * commissionee = FindCommissioneeDevice(nodeId);
1998 0 : SessionHolder session((commissionee == proxy) ? commissionee->DetachSecureSession().Value()
1999 0 : : proxy->GetSecureSession().Value());
2000 :
2001 0 : auto request = DisarmFailsafeRequest();
2002 0 : auto onSuccessCb = [session](const app::ConcreteCommandPath & aPath, const app::StatusIB & aStatus,
2003 : const decltype(request)::ResponseType & responseData) {
2004 0 : ChipLogProgress(Controller, "Failsafe disarmed");
2005 0 : MarkForEviction(session.Get());
2006 0 : };
2007 0 : auto onFailureCb = [session](CHIP_ERROR aError) {
2008 0 : ChipLogProgress(Controller, "Ignoring failure to disarm failsafe: %" CHIP_ERROR_FORMAT, aError.Format());
2009 0 : MarkForEviction(session.Get());
2010 0 : };
2011 :
2012 0 : ChipLogProgress(Controller, "Disarming failsafe on device %p in background", proxy);
2013 0 : CHIP_ERROR err = InvokeCommandRequest(proxy->GetExchangeManager(), session.Get().Value(), kRootEndpointId, request,
2014 : onSuccessCb, onFailureCb);
2015 0 : if (err != CHIP_NO_ERROR)
2016 : {
2017 0 : ChipLogError(Controller, "Failed to send command to disarm fail-safe: %" CHIP_ERROR_FORMAT, err.Format());
2018 : }
2019 :
2020 0 : CleanupDoneAfterError();
2021 0 : }
2022 0 : else if (completionStatus.failedStage.HasValue() && completionStatus.failedStage.Value() >= kWiFiNetworkSetup)
2023 : {
2024 : // If we were already doing network setup, we need to retain the pase session and start again from network setup stage.
2025 : // We do not need to reset the failsafe here because we want to keep everything on the device up to this point, so just
2026 : // send the completion callbacks (see "Commissioning Flows Error Handling" in the spec).
2027 0 : CommissioningStageComplete(CHIP_NO_ERROR);
2028 0 : SendCommissioningCompleteCallbacks(nodeId, mCommissioningCompletionStatus);
2029 : }
2030 : else
2031 : {
2032 : // If we've failed somewhere in the early stages (or we don't have a failedStage specified), we need to start from the
2033 : // beginning. However, because some of the commands can only be sent once per arm-failsafe, we also need to force a reset on
2034 : // the failsafe so we can start fresh on the next attempt.
2035 0 : ChipLogProgress(Controller, "Disarming failsafe on device %p", proxy);
2036 0 : auto request = DisarmFailsafeRequest();
2037 0 : CHIP_ERROR err = SendCommissioningCommand(proxy, request, OnDisarmFailsafe, OnDisarmFailsafeFailure, kRootEndpointId);
2038 0 : if (err != CHIP_NO_ERROR)
2039 : {
2040 : // We won't get any async callbacks here, so just pretend like the command errored out async.
2041 0 : ChipLogError(Controller, "Failed to send command to disarm fail-safe: %" CHIP_ERROR_FORMAT, err.Format());
2042 0 : CleanupDoneAfterError();
2043 : }
2044 : }
2045 0 : }
2046 :
2047 0 : void DeviceCommissioner::OnDisarmFailsafe(void * context,
2048 : const GeneralCommissioning::Commands::ArmFailSafeResponse::DecodableType & data)
2049 : {
2050 0 : ChipLogProgress(Controller, "Failsafe disarmed");
2051 0 : DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
2052 0 : commissioner->CleanupDoneAfterError();
2053 0 : }
2054 :
2055 0 : void DeviceCommissioner::OnDisarmFailsafeFailure(void * context, CHIP_ERROR error)
2056 : {
2057 0 : ChipLogProgress(Controller, "Ignoring failure to disarm failsafe: %" CHIP_ERROR_FORMAT, error.Format());
2058 0 : DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
2059 0 : commissioner->CleanupDoneAfterError();
2060 0 : }
2061 :
2062 0 : void DeviceCommissioner::CleanupDoneAfterError()
2063 : {
2064 : // If someone nulled out our mDeviceBeingCommissioned, there's nothing else
2065 : // to do here.
2066 0 : VerifyOrReturn(mDeviceBeingCommissioned != nullptr);
2067 :
2068 0 : NodeId nodeId = mDeviceBeingCommissioned->GetDeviceId();
2069 :
2070 : // Signal completion - this will reset mDeviceBeingCommissioned.
2071 0 : CommissioningStageComplete(CHIP_NO_ERROR);
2072 :
2073 : // At this point, we also want to close off the pase session so we need to re-establish
2074 0 : CommissioneeDeviceProxy * commissionee = FindCommissioneeDevice(nodeId);
2075 :
2076 : // If we've disarmed the failsafe, it's because we're starting again, so kill the pase connection.
2077 0 : if (commissionee != nullptr)
2078 : {
2079 0 : ReleaseCommissioneeDevice(commissionee);
2080 : }
2081 :
2082 : // Invoke callbacks last, after we have cleared up all state.
2083 0 : SendCommissioningCompleteCallbacks(nodeId, mCommissioningCompletionStatus);
2084 : }
2085 :
2086 0 : void DeviceCommissioner::SendCommissioningCompleteCallbacks(NodeId nodeId, const CompletionStatus & completionStatus)
2087 : {
2088 : MATTER_LOG_METRIC_END(kMetricDeviceCommissionerCommission, completionStatus.err);
2089 :
2090 0 : ChipLogProgress(Controller, "Commissioning complete for node ID 0x" ChipLogFormatX64 ": %s", ChipLogValueX64(nodeId),
2091 : (completionStatus.err == CHIP_NO_ERROR ? "success" : completionStatus.err.AsString()));
2092 0 : mCommissioningStage = CommissioningStage::kSecurePairing;
2093 :
2094 0 : if (mPairingDelegate == nullptr)
2095 : {
2096 0 : return;
2097 : }
2098 :
2099 0 : mPairingDelegate->OnCommissioningComplete(nodeId, completionStatus.err);
2100 :
2101 0 : PeerId peerId(GetCompressedFabricId(), nodeId);
2102 0 : if (completionStatus.err == CHIP_NO_ERROR)
2103 : {
2104 0 : mPairingDelegate->OnCommissioningSuccess(peerId);
2105 : }
2106 : else
2107 : {
2108 : // TODO: We should propogate detailed error information (commissioningError, networkCommissioningStatus) from
2109 : // completionStatus.
2110 0 : mPairingDelegate->OnCommissioningFailure(peerId, completionStatus.err, completionStatus.failedStage.ValueOr(kError),
2111 0 : completionStatus.attestationResult);
2112 : }
2113 : }
2114 :
2115 0 : void DeviceCommissioner::CommissioningStageComplete(CHIP_ERROR err, CommissioningDelegate::CommissioningReport report)
2116 : {
2117 : // Once this stage is complete, reset mDeviceBeingCommissioned - this will be reset when the delegate calls the next step.
2118 : MATTER_TRACE_SCOPE("CommissioningStageComplete", "DeviceCommissioner");
2119 : MATTER_LOG_METRIC_END(MetricKeyForCommissioningStage(mCommissioningStage), err);
2120 0 : VerifyOrDie(mDeviceBeingCommissioned);
2121 :
2122 0 : NodeId nodeId = mDeviceBeingCommissioned->GetDeviceId();
2123 0 : DeviceProxy * proxy = mDeviceBeingCommissioned;
2124 0 : mDeviceBeingCommissioned = nullptr;
2125 0 : mInvokeCancelFn = nullptr;
2126 0 : mWriteCancelFn = nullptr;
2127 :
2128 0 : if (mPairingDelegate != nullptr)
2129 : {
2130 0 : mPairingDelegate->OnCommissioningStatusUpdate(PeerId(GetCompressedFabricId(), nodeId), mCommissioningStage, err);
2131 : }
2132 :
2133 0 : if (mCommissioningDelegate == nullptr)
2134 : {
2135 0 : return;
2136 : }
2137 0 : report.stageCompleted = mCommissioningStage;
2138 0 : CHIP_ERROR status = mCommissioningDelegate->CommissioningStepFinished(err, report);
2139 0 : if (status != CHIP_NO_ERROR && mCommissioningStage != CommissioningStage::kCleanup)
2140 : {
2141 : // Commissioning delegate will only return error if it failed to perform the appropriate commissioning step.
2142 : // In this case, we should complete the commissioning for it.
2143 0 : CompletionStatus completionStatus;
2144 0 : completionStatus.err = status;
2145 0 : completionStatus.failedStage = MakeOptional(report.stageCompleted);
2146 0 : mCommissioningStage = CommissioningStage::kCleanup;
2147 0 : mDeviceBeingCommissioned = proxy;
2148 0 : CleanupCommissioning(proxy, nodeId, completionStatus);
2149 : }
2150 : }
2151 :
2152 0 : void DeviceCommissioner::OnDeviceConnectedFn(void * context, Messaging::ExchangeManager & exchangeMgr,
2153 : const SessionHandle & sessionHandle)
2154 : {
2155 : // CASE session established.
2156 : MATTER_LOG_METRIC_END(kMetricDeviceCommissioningOperationalSetup, CHIP_NO_ERROR);
2157 0 : DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
2158 0 : VerifyOrDie(commissioner->mCommissioningStage == CommissioningStage::kFindOperationalForStayActive ||
2159 : commissioner->mCommissioningStage == CommissioningStage::kFindOperationalForCommissioningComplete);
2160 0 : VerifyOrDie(commissioner->mDeviceBeingCommissioned->GetDeviceId() == sessionHandle->GetPeer().GetNodeId());
2161 0 : commissioner->CancelCASECallbacks(); // ensure all CASE callbacks are unregistered
2162 :
2163 0 : CommissioningDelegate::CommissioningReport report;
2164 0 : report.Set<OperationalNodeFoundData>(OperationalNodeFoundData(OperationalDeviceProxy(&exchangeMgr, sessionHandle)));
2165 0 : commissioner->CommissioningStageComplete(CHIP_NO_ERROR, report);
2166 0 : }
2167 :
2168 0 : void DeviceCommissioner::OnDeviceConnectionFailureFn(void * context, const ScopedNodeId & peerId, CHIP_ERROR error)
2169 : {
2170 : // CASE session establishment failed.
2171 : MATTER_LOG_METRIC_END(kMetricDeviceCommissioningOperationalSetup, error);
2172 0 : DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
2173 0 : VerifyOrDie(commissioner->mCommissioningStage == CommissioningStage::kFindOperationalForStayActive ||
2174 : commissioner->mCommissioningStage == CommissioningStage::kFindOperationalForCommissioningComplete);
2175 0 : VerifyOrDie(commissioner->mDeviceBeingCommissioned->GetDeviceId() == peerId.GetNodeId());
2176 0 : commissioner->CancelCASECallbacks(); // ensure all CASE callbacks are unregistered
2177 :
2178 0 : if (error != CHIP_NO_ERROR)
2179 : {
2180 0 : ChipLogProgress(Controller, "Device connection failed. Error %" CHIP_ERROR_FORMAT, error.Format());
2181 : }
2182 : else
2183 : {
2184 : // Ensure that commissioning stage advancement is done based on seeing an error.
2185 0 : ChipLogError(Controller, "Device connection failed without a valid error code.");
2186 0 : error = CHIP_ERROR_INTERNAL;
2187 : }
2188 0 : commissioner->CommissioningStageComplete(error);
2189 0 : }
2190 :
2191 : #if CHIP_DEVICE_CONFIG_ENABLE_AUTOMATIC_CASE_RETRIES
2192 : // No specific action to take on either success or failure here; we're just
2193 : // trying to bump the fail-safe, and if that fails it's not clear there's much
2194 : // we can to with that.
2195 0 : static void OnExtendFailsafeForCASERetryFailure(void * context, CHIP_ERROR error)
2196 : {
2197 0 : ChipLogError(Controller, "Failed to extend fail-safe for CASE retry: %" CHIP_ERROR_FORMAT, error.Format());
2198 0 : }
2199 : static void
2200 0 : OnExtendFailsafeForCASERetrySuccess(void * context,
2201 : const app::Clusters::GeneralCommissioning::Commands::ArmFailSafeResponse::DecodableType & data)
2202 : {
2203 0 : ChipLogProgress(Controller, "Status of extending fail-safe for CASE retry: %u", to_underlying(data.errorCode));
2204 0 : }
2205 :
2206 0 : void DeviceCommissioner::OnDeviceConnectionRetryFn(void * context, const ScopedNodeId & peerId, CHIP_ERROR error,
2207 : System::Clock::Seconds16 retryTimeout)
2208 : {
2209 0 : ChipLogError(Controller,
2210 : "Session establishment failed for " ChipLogFormatScopedNodeId ", error: %" CHIP_ERROR_FORMAT
2211 : ". Next retry expected to get a response to Sigma1 or fail within %d seconds",
2212 : ChipLogValueScopedNodeId(peerId), error.Format(), retryTimeout.count());
2213 :
2214 0 : auto self = static_cast<DeviceCommissioner *>(context);
2215 0 : VerifyOrDie(self->GetCommissioningStage() == CommissioningStage::kFindOperationalForStayActive ||
2216 : self->GetCommissioningStage() == CommissioningStage::kFindOperationalForCommissioningComplete);
2217 0 : VerifyOrDie(self->mDeviceBeingCommissioned->GetDeviceId() == peerId.GetNodeId());
2218 :
2219 : // We need to do the fail-safe arming over the PASE session.
2220 0 : auto * commissioneeDevice = self->FindCommissioneeDevice(peerId.GetNodeId());
2221 0 : if (!commissioneeDevice)
2222 : {
2223 : // Commissioning canceled, presumably. Just ignore the notification,
2224 : // not much we can do here.
2225 0 : return;
2226 : }
2227 :
2228 : // Extend by the default failsafe timeout plus our retry timeout, so we can
2229 : // be sure the fail-safe will not expire before we try the next time, if
2230 : // there will be a next time.
2231 : //
2232 : // TODO: Make it possible for our clients to control the exact timeout here?
2233 : uint16_t failsafeTimeout;
2234 0 : if (UINT16_MAX - retryTimeout.count() < kDefaultFailsafeTimeout)
2235 : {
2236 0 : failsafeTimeout = UINT16_MAX;
2237 : }
2238 : else
2239 : {
2240 0 : failsafeTimeout = static_cast<uint16_t>(retryTimeout.count() + kDefaultFailsafeTimeout);
2241 : }
2242 :
2243 : // A false return is fine; we don't want to make the fail-safe shorter here.
2244 0 : self->ExtendArmFailSafeInternal(commissioneeDevice, self->GetCommissioningStage(), failsafeTimeout,
2245 0 : MakeOptional(kMinimumCommissioningStepTimeout), OnExtendFailsafeForCASERetrySuccess,
2246 : OnExtendFailsafeForCASERetryFailure, /* fireAndForget = */ true);
2247 : }
2248 : #endif // CHIP_DEVICE_CONFIG_ENABLE_AUTOMATIC_CASE_RETRIES
2249 :
2250 : // ClusterStateCache::Callback / ReadClient::Callback
2251 0 : void DeviceCommissioner::OnDone(app::ReadClient * readClient)
2252 : {
2253 0 : VerifyOrDie(readClient != nullptr && readClient == mReadClient.get());
2254 0 : mReadClient.reset();
2255 0 : switch (mCommissioningStage)
2256 : {
2257 0 : case CommissioningStage::kReadCommissioningInfo:
2258 0 : ContinueReadingCommissioningInfo(mCommissioningDelegate->GetCommissioningParameters());
2259 0 : break;
2260 0 : default:
2261 0 : VerifyOrDie(false);
2262 : break;
2263 : }
2264 0 : }
2265 :
2266 : namespace {
2267 : // Helper for grouping attribute paths into read interactions in ContinueReadingCommissioningInfo()
2268 : // below. The logic generates a sequence of calls to AddAttributePath(), stopping when the capacity
2269 : // of the builder is exceeded. When creating subsequent read requests, the same sequence of calls
2270 : // is generated again, but the builder will skip however many attributes were already read in
2271 : // previous requests. This makes it easy to have logic that conditionally reads attributes, without
2272 : // needing to write manual code to work out where subsequent reads need to resume -- the logic that
2273 : // decides which attributes to read simply needs to be repeatable / deterministic.
2274 : class ReadInteractionBuilder
2275 : {
2276 : static constexpr auto kCapacity = InteractionModelEngine::kMinSupportedPathsPerReadRequest;
2277 :
2278 : size_t mSkip = 0;
2279 : size_t mCount = 0;
2280 : app::AttributePathParams mPaths[kCapacity];
2281 :
2282 : public:
2283 0 : ReadInteractionBuilder(size_t skip = 0) : mSkip(skip) {}
2284 :
2285 0 : size_t size() { return std::min(mCount, kCapacity); }
2286 0 : bool exceeded() { return mCount > kCapacity; }
2287 0 : app::AttributePathParams * paths() { return mPaths; }
2288 :
2289 : // Adds an attribute path if within the current window.
2290 : // Returns false if the available space has been exceeded.
2291 : template <typename... Ts>
2292 0 : bool AddAttributePath(Ts &&... args)
2293 : {
2294 0 : if (mSkip > 0)
2295 : {
2296 0 : mSkip--;
2297 0 : return true;
2298 : }
2299 0 : if (mCount >= kCapacity)
2300 : {
2301 : // capacity exceeded
2302 0 : mCount = kCapacity + 1;
2303 0 : return false;
2304 : }
2305 0 : mPaths[mCount++] = app::AttributePathParams(std::forward<Ts>(args)...);
2306 0 : return true;
2307 : }
2308 : };
2309 : } // namespace
2310 :
2311 0 : void DeviceCommissioner::ContinueReadingCommissioningInfo(const CommissioningParameters & params)
2312 : {
2313 0 : VerifyOrDie(mCommissioningStage == CommissioningStage::kReadCommissioningInfo);
2314 :
2315 : // mReadCommissioningInfoProgress starts at 0 and counts the number of paths we have read.
2316 : // A marker value is used to indicate that there are no further attributes to read.
2317 : static constexpr auto kReadProgressNoFurtherAttributes = std::numeric_limits<decltype(mReadCommissioningInfoProgress)>::max();
2318 0 : if (mReadCommissioningInfoProgress == kReadProgressNoFurtherAttributes)
2319 : {
2320 0 : FinishReadingCommissioningInfo(params);
2321 0 : return;
2322 : }
2323 :
2324 : // We can ony read 9 paths per Read Interaction, since that is the minimum a server has to
2325 : // support per spec (see "Interaction Model Limits"), so we generally need to perform more
2326 : // that one interaction. To build the list of attributes for each interaction, we use a
2327 : // builder that skips adding paths that we already handled in a previous interaction, and
2328 : // returns false if the current request is exhausted. This construction avoids allocating
2329 : // memory to hold the complete list of attributes to read up front; however the logic to
2330 : // determine the attributes to include must be deterministic since it runs multiple times.
2331 : // The use of an immediately-invoked lambda is convenient for control flow.
2332 0 : ReadInteractionBuilder builder(mReadCommissioningInfoProgress);
2333 0 : [&]() -> void {
2334 : // General Commissioning
2335 0 : VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::GeneralCommissioning::Id,
2336 : Clusters::GeneralCommissioning::Attributes::SupportsConcurrentConnection::Id));
2337 0 : VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::GeneralCommissioning::Id,
2338 : Clusters::GeneralCommissioning::Attributes::Breadcrumb::Id));
2339 0 : VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::GeneralCommissioning::Id,
2340 : Clusters::GeneralCommissioning::Attributes::BasicCommissioningInfo::Id));
2341 0 : VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::GeneralCommissioning::Id,
2342 : Clusters::GeneralCommissioning::Attributes::RegulatoryConfig::Id));
2343 0 : VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::GeneralCommissioning::Id,
2344 : Clusters::GeneralCommissioning::Attributes::LocationCapability::Id));
2345 0 : VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::GeneralCommissioning::Id,
2346 : Clusters::GeneralCommissioning::Attributes::IsCommissioningWithoutPower::Id));
2347 :
2348 : // Basic Information: VID and PID for device attestation purposes
2349 0 : VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::BasicInformation::Id,
2350 : Clusters::BasicInformation::Attributes::VendorID::Id));
2351 0 : VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::BasicInformation::Id,
2352 : Clusters::BasicInformation::Attributes::ProductID::Id));
2353 :
2354 : // Time Synchronization: all attributes
2355 0 : VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::TimeSynchronization::Id));
2356 :
2357 : // Network Commissioning (all endpoints): Read the feature map and connect time
2358 : // TODO: Expose a flag that disables network setup so we don't need to read this
2359 0 : VerifyOrReturn(builder.AddAttributePath(Clusters::NetworkCommissioning::Id,
2360 : Clusters::NetworkCommissioning::Attributes::FeatureMap::Id));
2361 0 : VerifyOrReturn(builder.AddAttributePath(Clusters::NetworkCommissioning::Id,
2362 : Clusters::NetworkCommissioning::Attributes::ConnectMaxTimeSeconds::Id));
2363 :
2364 : // If we were asked to do network scans, also read ScanMaxTimeSeconds,
2365 : // so we know how long to wait for those.
2366 0 : if (params.GetAttemptWiFiNetworkScan().ValueOr(false) || params.GetAttemptThreadNetworkScan().ValueOr(false))
2367 : {
2368 0 : VerifyOrReturn(builder.AddAttributePath(Clusters::NetworkCommissioning::Id,
2369 : Clusters::NetworkCommissioning::Attributes::ScanMaxTimeSeconds::Id));
2370 : }
2371 :
2372 : // OperationalCredentials: existing fabrics, if necessary
2373 0 : if (params.GetCheckForMatchingFabric())
2374 : {
2375 0 : VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::OperationalCredentials::Id,
2376 : Clusters::OperationalCredentials::Attributes::Fabrics::Id));
2377 : }
2378 :
2379 : // ICD Management
2380 0 : if (params.GetICDRegistrationStrategy() != ICDRegistrationStrategy::kIgnore)
2381 : {
2382 0 : VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::IcdManagement::Id,
2383 : Clusters::IcdManagement::Attributes::FeatureMap::Id));
2384 : }
2385 0 : VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::IcdManagement::Id,
2386 : Clusters::IcdManagement::Attributes::UserActiveModeTriggerHint::Id));
2387 0 : VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::IcdManagement::Id,
2388 : Clusters::IcdManagement::Attributes::UserActiveModeTriggerInstruction::Id));
2389 0 : VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::IcdManagement::Id,
2390 : Clusters::IcdManagement::Attributes::IdleModeDuration::Id));
2391 0 : VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::IcdManagement::Id,
2392 : Clusters::IcdManagement::Attributes::ActiveModeDuration::Id));
2393 0 : VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::IcdManagement::Id,
2394 : Clusters::IcdManagement::Attributes::ActiveModeThreshold::Id));
2395 :
2396 : // Extra paths requested via CommissioningParameters
2397 0 : for (auto const & path : params.GetExtraReadPaths())
2398 : {
2399 0 : VerifyOrReturn(builder.AddAttributePath(path));
2400 : }
2401 0 : }();
2402 :
2403 0 : VerifyOrDie(builder.size() > 0); // our logic is broken if there is nothing to read
2404 0 : if (builder.exceeded())
2405 : {
2406 : // Keep track of the number of attributes we have read already so we can resume from there.
2407 0 : auto progress = mReadCommissioningInfoProgress + builder.size();
2408 0 : VerifyOrDie(progress < kReadProgressNoFurtherAttributes);
2409 0 : mReadCommissioningInfoProgress = static_cast<decltype(mReadCommissioningInfoProgress)>(progress);
2410 : }
2411 : else
2412 : {
2413 0 : mReadCommissioningInfoProgress = kReadProgressNoFurtherAttributes;
2414 : }
2415 :
2416 0 : SendCommissioningReadRequest(mDeviceBeingCommissioned, mCommissioningStepTimeout, builder.paths(), builder.size());
2417 : }
2418 :
2419 : namespace {
2420 0 : void AccumulateErrors(CHIP_ERROR & acc, CHIP_ERROR err)
2421 : {
2422 0 : if (acc == CHIP_NO_ERROR && err != CHIP_NO_ERROR)
2423 : {
2424 0 : acc = err;
2425 : }
2426 0 : }
2427 : } // namespace
2428 :
2429 0 : void DeviceCommissioner::FinishReadingCommissioningInfo(const CommissioningParameters & params)
2430 : {
2431 : // We want to parse as much information as possible, even if we eventually end
2432 : // up returning an error (e.g. because some mandatory information was missing).
2433 0 : CHIP_ERROR err = CHIP_NO_ERROR;
2434 0 : ReadCommissioningInfo info;
2435 0 : info.attributes = mAttributeCache.get();
2436 0 : AccumulateErrors(err, ParseGeneralCommissioningInfo(info));
2437 0 : AccumulateErrors(err, ParseBasicInformation(info));
2438 0 : AccumulateErrors(err, ParseNetworkCommissioningInfo(info));
2439 0 : AccumulateErrors(err, ParseTimeSyncInfo(info));
2440 0 : AccumulateErrors(err, ParseFabrics(info));
2441 0 : AccumulateErrors(err, ParseICDInfo(info));
2442 0 : AccumulateErrors(err, ParseExtraCommissioningInfo(info, params));
2443 :
2444 0 : if (mPairingDelegate != nullptr && err == CHIP_NO_ERROR)
2445 : {
2446 0 : mPairingDelegate->OnReadCommissioningInfo(info);
2447 : }
2448 :
2449 0 : CommissioningDelegate::CommissioningReport report;
2450 0 : report.Set<ReadCommissioningInfo>(info);
2451 0 : CommissioningStageComplete(err, report);
2452 :
2453 : // Only release the attribute cache once `info` is no longer needed.
2454 0 : mAttributeCache.reset();
2455 0 : }
2456 :
2457 0 : CHIP_ERROR DeviceCommissioner::ParseGeneralCommissioningInfo(ReadCommissioningInfo & info)
2458 : {
2459 : using namespace GeneralCommissioning::Attributes;
2460 0 : CHIP_ERROR return_err = CHIP_NO_ERROR;
2461 : CHIP_ERROR err;
2462 :
2463 0 : BasicCommissioningInfo::TypeInfo::DecodableType basicInfo;
2464 0 : err = mAttributeCache->Get<BasicCommissioningInfo::TypeInfo>(kRootEndpointId, basicInfo);
2465 0 : if (err == CHIP_NO_ERROR)
2466 : {
2467 0 : info.general.recommendedFailsafe = basicInfo.failSafeExpiryLengthSeconds;
2468 : }
2469 : else
2470 : {
2471 0 : ChipLogError(Controller, "Failed to read BasicCommissioningInfo: %" CHIP_ERROR_FORMAT, err.Format());
2472 0 : return_err = err;
2473 : }
2474 :
2475 0 : err = mAttributeCache->Get<RegulatoryConfig::TypeInfo>(kRootEndpointId, info.general.currentRegulatoryLocation);
2476 0 : if (err != CHIP_NO_ERROR)
2477 : {
2478 0 : ChipLogError(Controller, "Failed to read RegulatoryConfig: %" CHIP_ERROR_FORMAT, err.Format());
2479 0 : return_err = err;
2480 : }
2481 :
2482 0 : err = mAttributeCache->Get<LocationCapability::TypeInfo>(kRootEndpointId, info.general.locationCapability);
2483 0 : if (err != CHIP_NO_ERROR)
2484 : {
2485 0 : ChipLogError(Controller, "Failed to read LocationCapability: %" CHIP_ERROR_FORMAT, err.Format());
2486 0 : return_err = err;
2487 : }
2488 :
2489 0 : err = mAttributeCache->Get<Breadcrumb::TypeInfo>(kRootEndpointId, info.general.breadcrumb);
2490 0 : if (err != CHIP_NO_ERROR)
2491 : {
2492 0 : ChipLogError(Controller, "Failed to read Breadcrumb: %" CHIP_ERROR_FORMAT, err.Format());
2493 0 : return_err = err;
2494 : }
2495 :
2496 0 : err = mAttributeCache->Get<SupportsConcurrentConnection::TypeInfo>(kRootEndpointId, info.supportsConcurrentConnection);
2497 0 : if (err != CHIP_NO_ERROR)
2498 : {
2499 0 : ChipLogError(Controller, "Ignoring failure to read SupportsConcurrentConnection: %" CHIP_ERROR_FORMAT, err.Format());
2500 0 : info.supportsConcurrentConnection = true; // default to true (concurrent), not a fatal error
2501 : }
2502 :
2503 0 : err = mAttributeCache->Get<IsCommissioningWithoutPower::TypeInfo>(kRootEndpointId, info.general.isCommissioningWithoutPower);
2504 0 : if (err != CHIP_NO_ERROR)
2505 : {
2506 0 : ChipLogError(Controller, "Ignoring failure to read IsCommissioningWithoutPower: %" CHIP_ERROR_FORMAT, err.Format());
2507 0 : info.general.isCommissioningWithoutPower = false; // default to false, not a fatal error
2508 : }
2509 :
2510 0 : return return_err;
2511 : }
2512 :
2513 0 : CHIP_ERROR DeviceCommissioner::ParseBasicInformation(ReadCommissioningInfo & info)
2514 : {
2515 : using namespace BasicInformation::Attributes;
2516 0 : CHIP_ERROR return_err = CHIP_NO_ERROR;
2517 : CHIP_ERROR err;
2518 :
2519 0 : err = mAttributeCache->Get<VendorID::TypeInfo>(kRootEndpointId, info.basic.vendorId);
2520 0 : if (err != CHIP_NO_ERROR)
2521 : {
2522 0 : ChipLogError(Controller, "Failed to read VendorID: %" CHIP_ERROR_FORMAT, err.Format());
2523 0 : return_err = err;
2524 : }
2525 :
2526 0 : err = mAttributeCache->Get<ProductID::TypeInfo>(kRootEndpointId, info.basic.productId);
2527 0 : if (err != CHIP_NO_ERROR)
2528 : {
2529 0 : ChipLogError(Controller, "Failed to read ProductID: %" CHIP_ERROR_FORMAT, err.Format());
2530 0 : return_err = err;
2531 : }
2532 :
2533 0 : return return_err;
2534 : }
2535 :
2536 0 : CHIP_ERROR DeviceCommissioner::ParseNetworkCommissioningInfo(ReadCommissioningInfo & info)
2537 : {
2538 : using namespace NetworkCommissioning::Attributes;
2539 0 : CHIP_ERROR return_err = CHIP_NO_ERROR;
2540 : CHIP_ERROR err;
2541 :
2542 : // Set the network cluster endpoints first so we can match up the connection
2543 : // times. Note that here we don't know what endpoints the network
2544 : // commissioning clusters might be on.
2545 0 : err = mAttributeCache->ForEachAttribute(NetworkCommissioning::Id, [this, &info](const ConcreteAttributePath & path) {
2546 0 : VerifyOrReturnError(path.mAttributeId == FeatureMap::Id, CHIP_NO_ERROR);
2547 0 : BitFlags<NetworkCommissioning::Feature> features;
2548 0 : if (mAttributeCache->Get<FeatureMap::TypeInfo>(path, *features.RawStorage()) == CHIP_NO_ERROR)
2549 : {
2550 0 : if (features.Has(NetworkCommissioning::Feature::kWiFiNetworkInterface))
2551 : {
2552 0 : ChipLogProgress(Controller, "NetworkCommissioning Features: has WiFi. endpointid = %u", path.mEndpointId);
2553 0 : info.network.wifi.endpoint = path.mEndpointId;
2554 : }
2555 0 : else if (features.Has(NetworkCommissioning::Feature::kThreadNetworkInterface))
2556 : {
2557 0 : ChipLogProgress(Controller, "NetworkCommissioning Features: has Thread. endpointid = %u", path.mEndpointId);
2558 0 : info.network.thread.endpoint = path.mEndpointId;
2559 : }
2560 0 : else if (features.Has(NetworkCommissioning::Feature::kEthernetNetworkInterface))
2561 : {
2562 0 : ChipLogProgress(Controller, "NetworkCommissioning Features: has Ethernet. endpointid = %u", path.mEndpointId);
2563 0 : info.network.eth.endpoint = path.mEndpointId;
2564 : }
2565 : }
2566 0 : return CHIP_NO_ERROR;
2567 : });
2568 0 : AccumulateErrors(return_err, err);
2569 :
2570 0 : if (info.network.thread.endpoint != kInvalidEndpointId)
2571 : {
2572 0 : err = ParseNetworkCommissioningTimeouts(info.network.thread, "Thread");
2573 0 : AccumulateErrors(return_err, err);
2574 : }
2575 :
2576 0 : if (info.network.wifi.endpoint != kInvalidEndpointId)
2577 : {
2578 0 : err = ParseNetworkCommissioningTimeouts(info.network.wifi, "Wi-Fi");
2579 0 : AccumulateErrors(return_err, err);
2580 : }
2581 :
2582 0 : if (return_err != CHIP_NO_ERROR)
2583 : {
2584 0 : ChipLogError(Controller, "Failed to parse Network Commissioning information: %" CHIP_ERROR_FORMAT, return_err.Format());
2585 : }
2586 0 : return return_err;
2587 : }
2588 :
2589 0 : CHIP_ERROR DeviceCommissioner::ParseNetworkCommissioningTimeouts(NetworkClusterInfo & networkInfo, const char * networkType)
2590 : {
2591 : using namespace NetworkCommissioning::Attributes;
2592 :
2593 0 : CHIP_ERROR err = mAttributeCache->Get<ConnectMaxTimeSeconds::TypeInfo>(networkInfo.endpoint, networkInfo.minConnectionTime);
2594 0 : if (err != CHIP_NO_ERROR)
2595 : {
2596 0 : ChipLogError(Controller, "Failed to read %s ConnectMaxTimeSeconds (endpoint %u): %" CHIP_ERROR_FORMAT, networkType,
2597 : networkInfo.endpoint, err.Format());
2598 0 : return err;
2599 : }
2600 :
2601 0 : err = mAttributeCache->Get<ScanMaxTimeSeconds::TypeInfo>(networkInfo.endpoint, networkInfo.maxScanTime);
2602 0 : if (err != CHIP_NO_ERROR)
2603 : {
2604 : // We don't always read this attribute, and we read it as a wildcard, so
2605 : // don't treat it as an error simply because it's missing.
2606 0 : if (err != CHIP_ERROR_KEY_NOT_FOUND)
2607 : {
2608 0 : ChipLogError(Controller, "Failed to read %s ScanMaxTimeSeconds (endpoint: %u): %" CHIP_ERROR_FORMAT, networkType,
2609 : networkInfo.endpoint, err.Format());
2610 0 : return err;
2611 : }
2612 :
2613 : // Just flag as "we don't know".
2614 0 : networkInfo.maxScanTime = 0;
2615 : }
2616 :
2617 0 : return CHIP_NO_ERROR;
2618 : }
2619 :
2620 0 : CHIP_ERROR DeviceCommissioner::ParseTimeSyncInfo(ReadCommissioningInfo & info)
2621 : {
2622 : using namespace TimeSynchronization::Attributes;
2623 : CHIP_ERROR err;
2624 :
2625 : // If we fail to get the feature map, there's no viable time cluster, don't set anything.
2626 0 : BitFlags<TimeSynchronization::Feature> featureMap;
2627 0 : err = mAttributeCache->Get<FeatureMap::TypeInfo>(kRootEndpointId, *featureMap.RawStorage());
2628 0 : if (err != CHIP_NO_ERROR)
2629 : {
2630 0 : info.requiresUTC = false;
2631 0 : info.requiresTimeZone = false;
2632 0 : info.requiresDefaultNTP = false;
2633 0 : info.requiresTrustedTimeSource = false;
2634 0 : return CHIP_NO_ERROR;
2635 : }
2636 0 : info.requiresUTC = true;
2637 0 : info.requiresTimeZone = featureMap.Has(TimeSynchronization::Feature::kTimeZone);
2638 0 : info.requiresDefaultNTP = featureMap.Has(TimeSynchronization::Feature::kNTPClient);
2639 0 : info.requiresTrustedTimeSource = featureMap.Has(TimeSynchronization::Feature::kTimeSyncClient);
2640 :
2641 0 : if (info.requiresTimeZone)
2642 : {
2643 0 : err = mAttributeCache->Get<TimeZoneListMaxSize::TypeInfo>(kRootEndpointId, info.maxTimeZoneSize);
2644 0 : if (err != CHIP_NO_ERROR)
2645 : {
2646 : // This information should be available, let's do our best with what we have, but we can't set
2647 : // the time zone without this information
2648 0 : info.requiresTimeZone = false;
2649 : }
2650 0 : err = mAttributeCache->Get<DSTOffsetListMaxSize::TypeInfo>(kRootEndpointId, info.maxDSTSize);
2651 0 : if (err != CHIP_NO_ERROR)
2652 : {
2653 0 : info.requiresTimeZone = false;
2654 : }
2655 : }
2656 0 : if (info.requiresDefaultNTP)
2657 : {
2658 0 : DefaultNTP::TypeInfo::DecodableType defaultNTP;
2659 0 : err = mAttributeCache->Get<DefaultNTP::TypeInfo>(kRootEndpointId, defaultNTP);
2660 0 : if (err == CHIP_NO_ERROR && (!defaultNTP.IsNull()) && (defaultNTP.Value().size() != 0))
2661 : {
2662 0 : info.requiresDefaultNTP = false;
2663 : }
2664 : }
2665 0 : if (info.requiresTrustedTimeSource)
2666 : {
2667 0 : TrustedTimeSource::TypeInfo::DecodableType trustedTimeSource;
2668 0 : err = mAttributeCache->Get<TrustedTimeSource::TypeInfo>(kRootEndpointId, trustedTimeSource);
2669 0 : if (err == CHIP_NO_ERROR && !trustedTimeSource.IsNull())
2670 : {
2671 0 : info.requiresTrustedTimeSource = false;
2672 : }
2673 : }
2674 :
2675 0 : return CHIP_NO_ERROR;
2676 : }
2677 :
2678 0 : CHIP_ERROR DeviceCommissioner::ParseFabrics(ReadCommissioningInfo & info)
2679 : {
2680 : using namespace OperationalCredentials::Attributes;
2681 : CHIP_ERROR err;
2682 0 : CHIP_ERROR return_err = CHIP_NO_ERROR;
2683 :
2684 : // We might not have requested a Fabrics attribute at all, so not having a
2685 : // value for it is not an error.
2686 0 : err = mAttributeCache->ForEachAttribute(OperationalCredentials::Id, [this, &info](const ConcreteAttributePath & path) {
2687 : using namespace chip::app::Clusters::OperationalCredentials::Attributes;
2688 : // this code is checking if the device is already on the commissioner's fabric.
2689 : // if a matching fabric is found, then remember the nodeId so that the commissioner
2690 : // can, if it decides to, cancel commissioning (before it fails in AddNoc) and know
2691 : // the device's nodeId on its fabric.
2692 0 : switch (path.mAttributeId)
2693 : {
2694 0 : case Fabrics::Id: {
2695 0 : Fabrics::TypeInfo::DecodableType fabrics;
2696 0 : ReturnErrorOnFailure(this->mAttributeCache->Get<Fabrics::TypeInfo>(path, fabrics));
2697 : // this is a best effort attempt to find a matching fabric, so no error checking on iter
2698 0 : auto iter = fabrics.begin();
2699 0 : while (iter.Next())
2700 : {
2701 0 : auto & fabricDescriptor = iter.GetValue();
2702 0 : ChipLogProgress(Controller,
2703 : "DeviceCommissioner::OnDone - fabric.vendorId=0x%04X fabric.fabricId=0x" ChipLogFormatX64
2704 : " fabric.nodeId=0x" ChipLogFormatX64,
2705 : fabricDescriptor.vendorID, ChipLogValueX64(fabricDescriptor.fabricID),
2706 : ChipLogValueX64(fabricDescriptor.nodeID));
2707 0 : if (GetFabricId() == fabricDescriptor.fabricID)
2708 : {
2709 0 : ChipLogProgress(Controller, "DeviceCommissioner::OnDone - found a matching fabric id");
2710 0 : chip::ByteSpan rootKeySpan = fabricDescriptor.rootPublicKey;
2711 0 : if (rootKeySpan.size() != Crypto::kP256_PublicKey_Length)
2712 : {
2713 0 : ChipLogError(Controller, "DeviceCommissioner::OnDone - fabric root key size mismatch %u != %u",
2714 : static_cast<unsigned>(rootKeySpan.size()),
2715 : static_cast<unsigned>(Crypto::kP256_PublicKey_Length));
2716 0 : continue;
2717 : }
2718 0 : P256PublicKeySpan rootPubKeySpan(rootKeySpan.data());
2719 0 : Crypto::P256PublicKey deviceRootPublicKey(rootPubKeySpan);
2720 :
2721 0 : Crypto::P256PublicKey commissionerRootPublicKey;
2722 0 : if (CHIP_NO_ERROR != GetRootPublicKey(commissionerRootPublicKey))
2723 : {
2724 0 : ChipLogError(Controller, "DeviceCommissioner::OnDone - error reading commissioner root public key");
2725 : }
2726 0 : else if (commissionerRootPublicKey.Matches(deviceRootPublicKey))
2727 : {
2728 0 : ChipLogProgress(Controller, "DeviceCommissioner::OnDone - fabric root keys match");
2729 0 : info.remoteNodeId = fabricDescriptor.nodeID;
2730 : }
2731 0 : }
2732 : }
2733 :
2734 0 : return CHIP_NO_ERROR;
2735 : }
2736 0 : default:
2737 0 : return CHIP_NO_ERROR;
2738 : }
2739 : });
2740 :
2741 0 : if (mPairingDelegate != nullptr)
2742 : {
2743 0 : mPairingDelegate->OnFabricCheck(info.remoteNodeId);
2744 : }
2745 :
2746 0 : return return_err;
2747 : }
2748 :
2749 0 : CHIP_ERROR DeviceCommissioner::ParseICDInfo(ReadCommissioningInfo & info)
2750 : {
2751 : using namespace IcdManagement::Attributes;
2752 : CHIP_ERROR err;
2753 :
2754 0 : bool hasUserActiveModeTrigger = false;
2755 0 : bool isICD = false;
2756 :
2757 0 : BitFlags<IcdManagement::Feature> featureMap;
2758 0 : err = mAttributeCache->Get<FeatureMap::TypeInfo>(kRootEndpointId, *featureMap.RawStorage());
2759 0 : if (err == CHIP_NO_ERROR)
2760 : {
2761 0 : info.icd.isLIT = featureMap.Has(IcdManagement::Feature::kLongIdleTimeSupport);
2762 0 : info.icd.checkInProtocolSupport = featureMap.Has(IcdManagement::Feature::kCheckInProtocolSupport);
2763 0 : hasUserActiveModeTrigger = featureMap.Has(IcdManagement::Feature::kUserActiveModeTrigger);
2764 0 : isICD = true;
2765 : }
2766 0 : else if (err == CHIP_ERROR_KEY_NOT_FOUND)
2767 : {
2768 : // This key is optional so not an error
2769 0 : info.icd.isLIT = false;
2770 0 : err = CHIP_NO_ERROR;
2771 : }
2772 0 : else if (err == CHIP_ERROR_IM_STATUS_CODE_RECEIVED)
2773 : {
2774 0 : app::StatusIB statusIB;
2775 0 : err = mAttributeCache->GetStatus(app::ConcreteAttributePath(kRootEndpointId, IcdManagement::Id, FeatureMap::Id), statusIB);
2776 0 : if (err == CHIP_NO_ERROR)
2777 : {
2778 0 : if (statusIB.mStatus == Protocols::InteractionModel::Status::UnsupportedCluster)
2779 : {
2780 0 : info.icd.isLIT = false;
2781 : }
2782 : else
2783 : {
2784 0 : err = statusIB.ToChipError();
2785 : }
2786 : }
2787 : }
2788 :
2789 0 : ReturnErrorOnFailure(err);
2790 :
2791 0 : info.icd.userActiveModeTriggerHint.ClearAll();
2792 0 : info.icd.userActiveModeTriggerInstruction = CharSpan();
2793 :
2794 0 : if (hasUserActiveModeTrigger)
2795 : {
2796 : // Intentionally ignore errors since they are not mandatory.
2797 0 : bool activeModeTriggerInstructionRequired = false;
2798 :
2799 0 : err = mAttributeCache->Get<UserActiveModeTriggerHint::TypeInfo>(kRootEndpointId, info.icd.userActiveModeTriggerHint);
2800 0 : if (err != CHIP_NO_ERROR)
2801 : {
2802 0 : ChipLogError(Controller, "IcdManagement.UserActiveModeTriggerHint expected, but failed to read.");
2803 0 : return err;
2804 : }
2805 :
2806 : using IcdManagement::UserActiveModeTriggerBitmap;
2807 0 : activeModeTriggerInstructionRequired = info.icd.userActiveModeTriggerHint.HasAny(
2808 0 : UserActiveModeTriggerBitmap::kCustomInstruction, UserActiveModeTriggerBitmap::kActuateSensorSeconds,
2809 0 : UserActiveModeTriggerBitmap::kActuateSensorTimes, UserActiveModeTriggerBitmap::kActuateSensorLightsBlink,
2810 0 : UserActiveModeTriggerBitmap::kResetButtonLightsBlink, UserActiveModeTriggerBitmap::kResetButtonSeconds,
2811 0 : UserActiveModeTriggerBitmap::kResetButtonTimes, UserActiveModeTriggerBitmap::kSetupButtonSeconds,
2812 0 : UserActiveModeTriggerBitmap::kSetupButtonTimes, UserActiveModeTriggerBitmap::kSetupButtonTimes,
2813 0 : UserActiveModeTriggerBitmap::kAppDefinedButton);
2814 :
2815 0 : if (activeModeTriggerInstructionRequired)
2816 : {
2817 0 : err = mAttributeCache->Get<UserActiveModeTriggerInstruction::TypeInfo>(kRootEndpointId,
2818 0 : info.icd.userActiveModeTriggerInstruction);
2819 0 : if (err != CHIP_NO_ERROR)
2820 : {
2821 0 : ChipLogError(Controller,
2822 : "IcdManagement.UserActiveModeTriggerInstruction expected for given active mode trigger hint, but "
2823 : "failed to read.");
2824 0 : return err;
2825 : }
2826 : }
2827 : }
2828 :
2829 0 : if (!isICD)
2830 : {
2831 0 : info.icd.idleModeDuration = 0;
2832 0 : info.icd.activeModeDuration = 0;
2833 0 : info.icd.activeModeThreshold = 0;
2834 0 : return CHIP_NO_ERROR;
2835 : }
2836 :
2837 0 : err = mAttributeCache->Get<IdleModeDuration::TypeInfo>(kRootEndpointId, info.icd.idleModeDuration);
2838 0 : if (err != CHIP_NO_ERROR)
2839 : {
2840 0 : ChipLogError(Controller, "IcdManagement.IdleModeDuration expected, but failed to read: %" CHIP_ERROR_FORMAT, err.Format());
2841 0 : return err;
2842 : }
2843 :
2844 0 : err = mAttributeCache->Get<ActiveModeDuration::TypeInfo>(kRootEndpointId, info.icd.activeModeDuration);
2845 0 : if (err != CHIP_NO_ERROR)
2846 : {
2847 0 : ChipLogError(Controller, "IcdManagement.ActiveModeDuration expected, but failed to read: %" CHIP_ERROR_FORMAT,
2848 : err.Format());
2849 0 : return err;
2850 : }
2851 :
2852 0 : err = mAttributeCache->Get<ActiveModeThreshold::TypeInfo>(kRootEndpointId, info.icd.activeModeThreshold);
2853 0 : if (err != CHIP_NO_ERROR)
2854 : {
2855 0 : ChipLogError(Controller, "IcdManagement.ActiveModeThreshold expected, but failed to read: %" CHIP_ERROR_FORMAT,
2856 : err.Format());
2857 : }
2858 :
2859 0 : return err;
2860 : }
2861 :
2862 0 : void DeviceCommissioner::OnArmFailSafe(void * context,
2863 : const GeneralCommissioning::Commands::ArmFailSafeResponse::DecodableType & data)
2864 : {
2865 0 : CommissioningDelegate::CommissioningReport report;
2866 0 : CHIP_ERROR err = CHIP_NO_ERROR;
2867 :
2868 0 : ChipLogProgress(Controller, "Received ArmFailSafe response errorCode=%u", to_underlying(data.errorCode));
2869 0 : if (data.errorCode != GeneralCommissioning::CommissioningErrorEnum::kOk)
2870 : {
2871 0 : err = CHIP_ERROR_INTERNAL;
2872 0 : report.Set<CommissioningErrorInfo>(data.errorCode);
2873 : }
2874 :
2875 0 : DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
2876 0 : commissioner->CommissioningStageComplete(err, report);
2877 0 : }
2878 :
2879 0 : void DeviceCommissioner::OnSetRegulatoryConfigResponse(
2880 : void * context, const GeneralCommissioning::Commands::SetRegulatoryConfigResponse::DecodableType & data)
2881 : {
2882 0 : CommissioningDelegate::CommissioningReport report;
2883 0 : CHIP_ERROR err = CHIP_NO_ERROR;
2884 :
2885 0 : ChipLogProgress(Controller, "Received SetRegulatoryConfig response errorCode=%u", to_underlying(data.errorCode));
2886 0 : if (data.errorCode != GeneralCommissioning::CommissioningErrorEnum::kOk)
2887 : {
2888 0 : err = CHIP_ERROR_INTERNAL;
2889 0 : report.Set<CommissioningErrorInfo>(data.errorCode);
2890 : }
2891 0 : DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
2892 0 : commissioner->CommissioningStageComplete(err, report);
2893 0 : }
2894 :
2895 0 : void DeviceCommissioner::OnSetTCAcknowledgementsResponse(
2896 : void * context, const GeneralCommissioning::Commands::SetTCAcknowledgementsResponse::DecodableType & data)
2897 : {
2898 0 : CommissioningDelegate::CommissioningReport report;
2899 0 : CHIP_ERROR err = CHIP_NO_ERROR;
2900 :
2901 0 : ChipLogProgress(Controller, "Received SetTCAcknowledgements response errorCode=%u", to_underlying(data.errorCode));
2902 0 : if (data.errorCode != GeneralCommissioning::CommissioningErrorEnum::kOk)
2903 : {
2904 0 : err = CHIP_ERROR_INTERNAL;
2905 0 : report.Set<CommissioningErrorInfo>(data.errorCode);
2906 : }
2907 0 : DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
2908 0 : commissioner->CommissioningStageComplete(err, report);
2909 0 : }
2910 :
2911 0 : void DeviceCommissioner::OnSetTimeZoneResponse(void * context,
2912 : const TimeSynchronization::Commands::SetTimeZoneResponse::DecodableType & data)
2913 : {
2914 0 : CommissioningDelegate::CommissioningReport report;
2915 0 : CHIP_ERROR err = CHIP_NO_ERROR;
2916 0 : DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
2917 : TimeZoneResponseInfo info;
2918 0 : info.requiresDSTOffsets = data.DSTOffsetRequired;
2919 0 : report.Set<TimeZoneResponseInfo>(info);
2920 0 : commissioner->CommissioningStageComplete(err, report);
2921 0 : }
2922 :
2923 0 : void DeviceCommissioner::OnSetUTCError(void * context, CHIP_ERROR error)
2924 : {
2925 : // For SetUTCTime, we don't actually care if the commissionee didn't want out time, that's its choice
2926 0 : DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
2927 0 : commissioner->CommissioningStageComplete(CHIP_NO_ERROR);
2928 0 : }
2929 :
2930 0 : void DeviceCommissioner::OnScanNetworksFailure(void * context, CHIP_ERROR error)
2931 : {
2932 0 : ChipLogProgress(Controller, "Received ScanNetworks failure response %" CHIP_ERROR_FORMAT, error.Format());
2933 :
2934 0 : DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
2935 :
2936 : // advance to the kNeedsNetworkCreds waiting step
2937 : // clear error so that we don't abort the commissioning when ScanNetworks fails
2938 0 : commissioner->CommissioningStageComplete(CHIP_NO_ERROR);
2939 :
2940 0 : if (commissioner->GetPairingDelegate() != nullptr)
2941 : {
2942 0 : commissioner->GetPairingDelegate()->OnScanNetworksFailure(error);
2943 : }
2944 0 : }
2945 :
2946 0 : void DeviceCommissioner::OnScanNetworksResponse(void * context,
2947 : const NetworkCommissioning::Commands::ScanNetworksResponse::DecodableType & data)
2948 : {
2949 0 : CommissioningDelegate::CommissioningReport report;
2950 :
2951 0 : ChipLogProgress(Controller, "Received ScanNetwork response, networkingStatus=%u debugText=%s",
2952 : to_underlying(data.networkingStatus),
2953 : (data.debugText.HasValue() ? std::string(data.debugText.Value().data(), data.debugText.Value().size()).c_str()
2954 : : "none provided"));
2955 0 : DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
2956 :
2957 : // advance to the kNeedsNetworkCreds waiting step
2958 0 : commissioner->CommissioningStageComplete(CHIP_NO_ERROR);
2959 :
2960 0 : if (commissioner->GetPairingDelegate() != nullptr)
2961 : {
2962 0 : commissioner->GetPairingDelegate()->OnScanNetworksSuccess(data);
2963 : }
2964 0 : }
2965 :
2966 0 : CHIP_ERROR DeviceCommissioner::NetworkCredentialsReady()
2967 : {
2968 0 : VerifyOrReturnError(mCommissioningStage == CommissioningStage::kNeedsNetworkCreds, CHIP_ERROR_INCORRECT_STATE);
2969 :
2970 : // need to advance to next step
2971 0 : CommissioningStageComplete(CHIP_NO_ERROR);
2972 :
2973 0 : return CHIP_NO_ERROR;
2974 : }
2975 :
2976 0 : CHIP_ERROR DeviceCommissioner::ICDRegistrationInfoReady()
2977 : {
2978 0 : VerifyOrReturnError(mCommissioningStage == CommissioningStage::kICDGetRegistrationInfo, CHIP_ERROR_INCORRECT_STATE);
2979 :
2980 : // need to advance to next step
2981 0 : CommissioningStageComplete(CHIP_NO_ERROR);
2982 :
2983 0 : return CHIP_NO_ERROR;
2984 : }
2985 :
2986 0 : void DeviceCommissioner::OnNetworkConfigResponse(void * context,
2987 : const NetworkCommissioning::Commands::NetworkConfigResponse::DecodableType & data)
2988 : {
2989 0 : CommissioningDelegate::CommissioningReport report;
2990 0 : CHIP_ERROR err = CHIP_NO_ERROR;
2991 :
2992 0 : ChipLogProgress(Controller, "Received NetworkConfig response, networkingStatus=%u", to_underlying(data.networkingStatus));
2993 0 : if (data.networkingStatus != NetworkCommissioning::NetworkCommissioningStatusEnum::kSuccess)
2994 : {
2995 0 : err = CHIP_ERROR_INTERNAL;
2996 0 : report.Set<NetworkCommissioningStatusInfo>(data.networkingStatus);
2997 : }
2998 0 : DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
2999 0 : commissioner->CommissioningStageComplete(err, report);
3000 0 : }
3001 :
3002 0 : void DeviceCommissioner::OnConnectNetworkResponse(
3003 : void * context, const NetworkCommissioning::Commands::ConnectNetworkResponse::DecodableType & data)
3004 : {
3005 0 : CommissioningDelegate::CommissioningReport report;
3006 0 : CHIP_ERROR err = CHIP_NO_ERROR;
3007 :
3008 0 : ChipLogProgress(Controller, "Received ConnectNetwork response, networkingStatus=%u", to_underlying(data.networkingStatus));
3009 0 : if (data.networkingStatus != NetworkCommissioning::NetworkCommissioningStatusEnum::kSuccess)
3010 : {
3011 0 : err = CHIP_ERROR_INTERNAL;
3012 0 : report.Set<NetworkCommissioningStatusInfo>(data.networkingStatus);
3013 : }
3014 0 : DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
3015 0 : commissioner->CommissioningStageComplete(err, report);
3016 0 : }
3017 :
3018 0 : void DeviceCommissioner::OnCommissioningCompleteResponse(
3019 : void * context, const GeneralCommissioning::Commands::CommissioningCompleteResponse::DecodableType & data)
3020 : {
3021 0 : CommissioningDelegate::CommissioningReport report;
3022 0 : CHIP_ERROR err = CHIP_NO_ERROR;
3023 :
3024 0 : ChipLogProgress(Controller, "Received CommissioningComplete response, errorCode=%u", to_underlying(data.errorCode));
3025 0 : if (data.errorCode != GeneralCommissioning::CommissioningErrorEnum::kOk)
3026 : {
3027 0 : err = CHIP_ERROR_INTERNAL;
3028 0 : report.Set<CommissioningErrorInfo>(data.errorCode);
3029 : }
3030 0 : DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
3031 0 : commissioner->CommissioningStageComplete(err, report);
3032 0 : }
3033 :
3034 : template <typename RequestObjectT>
3035 : CHIP_ERROR
3036 0 : DeviceCommissioner::SendCommissioningCommand(DeviceProxy * device, const RequestObjectT & request,
3037 : CommandResponseSuccessCallback<typename RequestObjectT::ResponseType> successCb,
3038 : CommandResponseFailureCallback failureCb, EndpointId endpoint,
3039 : Optional<System::Clock::Timeout> timeout, bool fireAndForget)
3040 :
3041 : {
3042 : // Default behavior is to make sequential, cancellable calls tracked via mInvokeCancelFn.
3043 : // Fire-and-forget calls are not cancellable and don't receive `this` as context in callbacks.
3044 0 : VerifyOrDie(fireAndForget || !mInvokeCancelFn); // we don't make parallel (cancellable) calls
3045 :
3046 0 : void * context = (!fireAndForget) ? this : nullptr;
3047 0 : auto onSuccessCb = [context, successCb](const app::ConcreteCommandPath & aPath, const app::StatusIB & aStatus,
3048 : const typename RequestObjectT::ResponseType & responseData) {
3049 0 : successCb(context, responseData);
3050 : };
3051 0 : auto onFailureCb = [context, failureCb](CHIP_ERROR aError) { failureCb(context, aError); };
3052 :
3053 0 : return InvokeCommandRequest(device->GetExchangeManager(), device->GetSecureSession().Value(), endpoint, request, onSuccessCb,
3054 0 : onFailureCb, NullOptional, timeout, (!fireAndForget) ? &mInvokeCancelFn : nullptr);
3055 : }
3056 :
3057 : template <typename AttrType>
3058 : CHIP_ERROR DeviceCommissioner::SendCommissioningWriteRequest(DeviceProxy * device, EndpointId endpoint, ClusterId cluster,
3059 : AttributeId attribute, const AttrType & requestData,
3060 : WriteResponseSuccessCallback successCb,
3061 : WriteResponseFailureCallback failureCb)
3062 : {
3063 : VerifyOrDie(!mWriteCancelFn); // we don't make parallel (cancellable) calls
3064 : auto onSuccessCb = [this, successCb](const app::ConcreteAttributePath & aPath) { successCb(this); };
3065 : auto onFailureCb = [this, failureCb](const app::ConcreteAttributePath * aPath, CHIP_ERROR aError) { failureCb(this, aError); };
3066 : return WriteAttribute(device->GetSecureSession().Value(), endpoint, cluster, attribute, requestData, onSuccessCb, onFailureCb,
3067 : /* aTimedWriteTimeoutMs = */ NullOptional, /* onDoneCb = */ nullptr, /* aDataVersion = */ NullOptional,
3068 : /* outCancelFn = */ &mWriteCancelFn);
3069 : }
3070 :
3071 0 : void DeviceCommissioner::SendCommissioningReadRequest(DeviceProxy * proxy, Optional<System::Clock::Timeout> timeout,
3072 : app::AttributePathParams * readPaths, size_t readPathsSize)
3073 : {
3074 0 : VerifyOrDie(!mReadClient); // we don't perform parallel reads
3075 :
3076 0 : app::InteractionModelEngine * engine = app::InteractionModelEngine::GetInstance();
3077 0 : app::ReadPrepareParams readParams(proxy->GetSecureSession().Value());
3078 0 : readParams.mIsFabricFiltered = false;
3079 0 : if (timeout.HasValue())
3080 : {
3081 0 : readParams.mTimeout = timeout.Value();
3082 : }
3083 0 : readParams.mpAttributePathParamsList = readPaths;
3084 0 : readParams.mAttributePathParamsListSize = readPathsSize;
3085 :
3086 : // Take ownership of the attribute cache, so it can be released if SendRequest fails.
3087 0 : auto attributeCache = std::move(mAttributeCache);
3088 : auto readClient = chip::Platform::MakeUnique<app::ReadClient>(
3089 0 : engine, proxy->GetExchangeManager(), attributeCache->GetBufferedCallback(), app::ReadClient::InteractionType::Read);
3090 0 : CHIP_ERROR err = readClient->SendRequest(readParams);
3091 0 : if (err != CHIP_NO_ERROR)
3092 : {
3093 0 : ChipLogError(Controller, "Failed to send read request: %" CHIP_ERROR_FORMAT, err.Format());
3094 0 : CommissioningStageComplete(err);
3095 0 : return;
3096 : }
3097 0 : mAttributeCache = std::move(attributeCache);
3098 0 : mReadClient = std::move(readClient);
3099 0 : }
3100 :
3101 0 : void DeviceCommissioner::PerformCommissioningStep(DeviceProxy * proxy, CommissioningStage step, CommissioningParameters & params,
3102 : CommissioningDelegate * delegate, EndpointId endpoint,
3103 : Optional<System::Clock::Timeout> timeout)
3104 :
3105 : {
3106 : MATTER_LOG_METRIC(kMetricDeviceCommissionerCommissionStage, step);
3107 : MATTER_LOG_METRIC_BEGIN(MetricKeyForCommissioningStage(step));
3108 :
3109 0 : if (params.GetCompletionStatus().err == CHIP_NO_ERROR)
3110 : {
3111 0 : ChipLogProgress(Controller, "Performing next commissioning step '%s'", StageToString(step));
3112 : }
3113 : else
3114 : {
3115 0 : ChipLogProgress(Controller, "Performing next commissioning step '%s' with completion status = '%s'", StageToString(step),
3116 : params.GetCompletionStatus().err.AsString());
3117 : }
3118 :
3119 0 : if (mPairingDelegate)
3120 : {
3121 0 : mPairingDelegate->OnCommissioningStageStart(PeerId(GetCompressedFabricId(), proxy->GetDeviceId()), step);
3122 : }
3123 :
3124 0 : mCommissioningStepTimeout = timeout;
3125 0 : mCommissioningStage = step;
3126 0 : mCommissioningDelegate = delegate;
3127 0 : mDeviceBeingCommissioned = proxy;
3128 :
3129 : // TODO: Extend timeouts to the DAC and Opcert requests.
3130 : // TODO(cecille): We probably want something better than this for breadcrumbs.
3131 0 : uint64_t breadcrumb = static_cast<uint64_t>(step);
3132 :
3133 0 : switch (step)
3134 : {
3135 0 : case CommissioningStage::kArmFailsafe: {
3136 0 : VerifyOrDie(endpoint == kRootEndpointId);
3137 : // Make sure the fail-safe value we set here actually ends up being used
3138 : // no matter what.
3139 0 : proxy->SetFailSafeExpirationTimestamp(System::Clock::kZero);
3140 0 : VerifyOrDie(ExtendArmFailSafeInternal(proxy, step, params.GetFailsafeTimerSeconds().ValueOr(kDefaultFailsafeTimeout),
3141 : timeout, OnArmFailSafe, OnBasicFailure, /* fireAndForget = */ false));
3142 : }
3143 0 : break;
3144 0 : case CommissioningStage::kReadCommissioningInfo: {
3145 0 : VerifyOrDie(endpoint == kRootEndpointId);
3146 0 : ChipLogProgress(Controller, "Sending read requests for commissioning information");
3147 :
3148 : // Allocate a ClusterStateCache to collect the data from our read requests.
3149 : // The cache will be released in:
3150 : // - SendCommissioningReadRequest when failing to send a read request.
3151 : // - FinishReadingCommissioningInfo when the ReadCommissioningInfo stage is completed.
3152 : // - CancelCommissioningInteractions
3153 0 : mAttributeCache = Platform::MakeUnique<app::ClusterStateCache>(*this);
3154 :
3155 : // Generally we need to make more than one read request, because as per spec a server only
3156 : // supports a limited number of paths per Read Interaction. Because the actual number of
3157 : // interactions we end up performing is dynamic, we track all of them within a single
3158 : // commissioning stage.
3159 0 : mReadCommissioningInfoProgress = 0;
3160 0 : ContinueReadingCommissioningInfo(params); // Note: assume params == delegate.GetCommissioningParameters()
3161 0 : break;
3162 : }
3163 0 : case CommissioningStage::kConfigureUTCTime: {
3164 0 : TimeSynchronization::Commands::SetUTCTime::Type request;
3165 0 : uint64_t kChipEpochUsSinceUnixEpoch = static_cast<uint64_t>(kChipEpochSecondsSinceUnixEpoch) * chip::kMicrosecondsPerSecond;
3166 : System::Clock::Microseconds64 utcTime;
3167 0 : if (System::SystemClock().GetClock_RealTime(utcTime) != CHIP_NO_ERROR || utcTime.count() <= kChipEpochUsSinceUnixEpoch)
3168 : {
3169 : // We have no time to give, but that's OK, just complete this stage
3170 0 : CommissioningStageComplete(CHIP_NO_ERROR);
3171 0 : return;
3172 : }
3173 :
3174 0 : request.UTCTime = utcTime.count() - kChipEpochUsSinceUnixEpoch;
3175 : // For now, we assume a seconds granularity
3176 0 : request.granularity = TimeSynchronization::GranularityEnum::kSecondsGranularity;
3177 0 : CHIP_ERROR err = SendCommissioningCommand(proxy, request, OnBasicSuccess, OnSetUTCError, endpoint, timeout);
3178 0 : if (err != CHIP_NO_ERROR)
3179 : {
3180 : // We won't get any async callbacks here, so just complete our stage.
3181 0 : ChipLogError(Controller, "Failed to send SetUTCTime command: %" CHIP_ERROR_FORMAT, err.Format());
3182 0 : CommissioningStageComplete(err);
3183 0 : return;
3184 : }
3185 0 : break;
3186 : }
3187 0 : case CommissioningStage::kConfigureTimeZone: {
3188 0 : if (!params.GetTimeZone().HasValue())
3189 : {
3190 0 : ChipLogError(Controller, "ConfigureTimeZone stage called with no time zone data");
3191 0 : CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
3192 0 : return;
3193 : }
3194 0 : TimeSynchronization::Commands::SetTimeZone::Type request;
3195 0 : request.timeZone = params.GetTimeZone().Value();
3196 0 : CHIP_ERROR err = SendCommissioningCommand(proxy, request, OnSetTimeZoneResponse, OnBasicFailure, endpoint, timeout);
3197 0 : if (err != CHIP_NO_ERROR)
3198 : {
3199 : // We won't get any async callbacks here, so just complete our stage.
3200 0 : ChipLogError(Controller, "Failed to send SetTimeZone command: %" CHIP_ERROR_FORMAT, err.Format());
3201 0 : CommissioningStageComplete(err);
3202 0 : return;
3203 : }
3204 0 : break;
3205 : }
3206 0 : case CommissioningStage::kConfigureDSTOffset: {
3207 0 : if (!params.GetDSTOffsets().HasValue())
3208 : {
3209 0 : ChipLogError(Controller, "ConfigureDSTOffset stage called with no DST data");
3210 0 : CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
3211 0 : return;
3212 : }
3213 0 : TimeSynchronization::Commands::SetDSTOffset::Type request;
3214 0 : request.DSTOffset = params.GetDSTOffsets().Value();
3215 0 : CHIP_ERROR err = SendCommissioningCommand(proxy, request, OnBasicSuccess, OnBasicFailure, endpoint, timeout);
3216 0 : if (err != CHIP_NO_ERROR)
3217 : {
3218 : // We won't get any async callbacks here, so just complete our stage.
3219 0 : ChipLogError(Controller, "Failed to send SetDSTOffset command: %" CHIP_ERROR_FORMAT, err.Format());
3220 0 : CommissioningStageComplete(err);
3221 0 : return;
3222 : }
3223 0 : break;
3224 : }
3225 0 : case CommissioningStage::kConfigureDefaultNTP: {
3226 0 : if (!params.GetDefaultNTP().HasValue())
3227 : {
3228 0 : ChipLogError(Controller, "ConfigureDefaultNTP stage called with no default NTP data");
3229 0 : CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
3230 0 : return;
3231 : }
3232 0 : TimeSynchronization::Commands::SetDefaultNTP::Type request;
3233 0 : request.defaultNTP = params.GetDefaultNTP().Value();
3234 0 : CHIP_ERROR err = SendCommissioningCommand(proxy, request, OnBasicSuccess, OnBasicFailure, endpoint, timeout);
3235 0 : if (err != CHIP_NO_ERROR)
3236 : {
3237 : // We won't get any async callbacks here, so just complete our stage.
3238 0 : ChipLogError(Controller, "Failed to send SetDefaultNTP command: %" CHIP_ERROR_FORMAT, err.Format());
3239 0 : CommissioningStageComplete(err);
3240 0 : return;
3241 : }
3242 0 : break;
3243 : }
3244 0 : case CommissioningStage::kScanNetworks: {
3245 0 : NetworkCommissioning::Commands::ScanNetworks::Type request;
3246 0 : if (params.GetWiFiCredentials().HasValue())
3247 : {
3248 0 : request.ssid.Emplace(params.GetWiFiCredentials().Value().ssid);
3249 : }
3250 0 : request.breadcrumb.Emplace(breadcrumb);
3251 0 : CHIP_ERROR err = SendCommissioningCommand(proxy, request, OnScanNetworksResponse, OnScanNetworksFailure, endpoint, timeout);
3252 0 : if (err != CHIP_NO_ERROR)
3253 : {
3254 : // We won't get any async callbacks here, so just complete our stage.
3255 0 : ChipLogError(Controller, "Failed to send ScanNetworks command: %" CHIP_ERROR_FORMAT, err.Format());
3256 0 : CommissioningStageComplete(err);
3257 0 : return;
3258 : }
3259 0 : break;
3260 : }
3261 0 : case CommissioningStage::kNeedsNetworkCreds: {
3262 : // Nothing to do.
3263 : //
3264 : // Either we did a scan and the OnScanNetworksSuccess and OnScanNetworksFailure
3265 : // callbacks will tell the DevicePairingDelegate that network credentials are
3266 : // needed, or we asked the DevicePairingDelegate for network credentials
3267 : // explicitly, and are waiting for it to get back to us.
3268 0 : break;
3269 : }
3270 0 : case CommissioningStage::kConfigRegulatory: {
3271 : // TODO(cecille): Worthwhile to keep this around as part of the class?
3272 : // TODO(cecille): Where is the country config actually set?
3273 0 : ChipLogProgress(Controller, "Setting Regulatory Config");
3274 : auto capability =
3275 0 : params.GetLocationCapability().ValueOr(app::Clusters::GeneralCommissioning::RegulatoryLocationTypeEnum::kOutdoor);
3276 : app::Clusters::GeneralCommissioning::RegulatoryLocationTypeEnum regulatoryConfig;
3277 : // Value is only switchable on the devices with indoor/outdoor capability
3278 0 : if (capability == app::Clusters::GeneralCommissioning::RegulatoryLocationTypeEnum::kIndoorOutdoor)
3279 : {
3280 : // If the device supports indoor and outdoor configs, use the setting from the commissioner, otherwise fall back to
3281 : // the current device setting then to outdoor (most restrictive)
3282 0 : if (params.GetDeviceRegulatoryLocation().HasValue())
3283 : {
3284 0 : regulatoryConfig = params.GetDeviceRegulatoryLocation().Value();
3285 0 : ChipLogProgress(Controller, "Setting regulatory config to %u from commissioner override",
3286 : static_cast<uint8_t>(regulatoryConfig));
3287 : }
3288 0 : else if (params.GetDefaultRegulatoryLocation().HasValue())
3289 : {
3290 0 : regulatoryConfig = params.GetDefaultRegulatoryLocation().Value();
3291 0 : ChipLogProgress(Controller, "No regulatory config supplied by controller, leaving as device default (%u)",
3292 : static_cast<uint8_t>(regulatoryConfig));
3293 : }
3294 : else
3295 : {
3296 0 : regulatoryConfig = app::Clusters::GeneralCommissioning::RegulatoryLocationTypeEnum::kOutdoor;
3297 0 : ChipLogProgress(Controller, "No overrride or device regulatory config supplied, setting to outdoor");
3298 : }
3299 : }
3300 : else
3301 : {
3302 0 : ChipLogProgress(Controller, "Device does not support configurable regulatory location");
3303 0 : regulatoryConfig = capability;
3304 : }
3305 :
3306 0 : CharSpan countryCode;
3307 0 : const auto & providedCountryCode = params.GetCountryCode();
3308 0 : if (providedCountryCode.HasValue())
3309 : {
3310 0 : countryCode = providedCountryCode.Value();
3311 : }
3312 : else
3313 : {
3314 : // Default to "XX", for lack of anything better.
3315 0 : countryCode = "XX"_span;
3316 : }
3317 :
3318 0 : GeneralCommissioning::Commands::SetRegulatoryConfig::Type request;
3319 0 : request.newRegulatoryConfig = regulatoryConfig;
3320 0 : request.countryCode = countryCode;
3321 0 : request.breadcrumb = breadcrumb;
3322 0 : CHIP_ERROR err = SendCommissioningCommand(proxy, request, OnSetRegulatoryConfigResponse, OnBasicFailure, endpoint, timeout);
3323 0 : if (err != CHIP_NO_ERROR)
3324 : {
3325 : // We won't get any async callbacks here, so just complete our stage.
3326 0 : ChipLogError(Controller, "Failed to send SetRegulatoryConfig command: %" CHIP_ERROR_FORMAT, err.Format());
3327 0 : CommissioningStageComplete(err);
3328 0 : return;
3329 : }
3330 : }
3331 0 : break;
3332 0 : case CommissioningStage::kConfigureTCAcknowledgments: {
3333 0 : ChipLogProgress(Controller, "Setting Terms and Conditions");
3334 :
3335 0 : if (!params.GetTermsAndConditionsAcknowledgement().HasValue())
3336 : {
3337 0 : ChipLogProgress(Controller, "Setting Terms and Conditions: Skipped");
3338 0 : CommissioningStageComplete(CHIP_NO_ERROR);
3339 0 : return;
3340 : }
3341 :
3342 0 : GeneralCommissioning::Commands::SetTCAcknowledgements::Type request;
3343 0 : TermsAndConditionsAcknowledgement termsAndConditionsAcknowledgement = params.GetTermsAndConditionsAcknowledgement().Value();
3344 0 : request.TCUserResponse = termsAndConditionsAcknowledgement.acceptedTermsAndConditions;
3345 0 : request.TCVersion = termsAndConditionsAcknowledgement.acceptedTermsAndConditionsVersion;
3346 :
3347 0 : ChipLogProgress(Controller, "Setting Terms and Conditions: %hu, %hu", request.TCUserResponse, request.TCVersion);
3348 : CHIP_ERROR err =
3349 0 : SendCommissioningCommand(proxy, request, OnSetTCAcknowledgementsResponse, OnBasicFailure, endpoint, timeout);
3350 0 : if (err != CHIP_NO_ERROR)
3351 : {
3352 0 : ChipLogError(Controller, "Failed to send SetTCAcknowledgements command: %" CHIP_ERROR_FORMAT, err.Format());
3353 0 : CommissioningStageComplete(err);
3354 0 : return;
3355 : }
3356 0 : break;
3357 : }
3358 0 : case CommissioningStage::kSendPAICertificateRequest: {
3359 0 : ChipLogProgress(Controller, "Sending request for PAI certificate");
3360 0 : CHIP_ERROR err = SendCertificateChainRequestCommand(proxy, CertificateType::kPAI, timeout);
3361 0 : if (err != CHIP_NO_ERROR)
3362 : {
3363 : // We won't get any async callbacks here, so just complete our stage.
3364 0 : ChipLogError(Controller, "Failed to send CertificateChainRequest command to get PAI: %" CHIP_ERROR_FORMAT,
3365 : err.Format());
3366 0 : CommissioningStageComplete(err);
3367 0 : return;
3368 : }
3369 0 : break;
3370 : }
3371 0 : case CommissioningStage::kSendDACCertificateRequest: {
3372 0 : ChipLogProgress(Controller, "Sending request for DAC certificate");
3373 0 : CHIP_ERROR err = SendCertificateChainRequestCommand(proxy, CertificateType::kDAC, timeout);
3374 0 : if (err != CHIP_NO_ERROR)
3375 : {
3376 : // We won't get any async callbacks here, so just complete our stage.
3377 0 : ChipLogError(Controller, "Failed to send CertificateChainRequest command to get DAC: %" CHIP_ERROR_FORMAT,
3378 : err.Format());
3379 0 : CommissioningStageComplete(err);
3380 0 : return;
3381 : }
3382 0 : break;
3383 : }
3384 0 : case CommissioningStage::kSendAttestationRequest: {
3385 0 : ChipLogProgress(Controller, "Sending Attestation Request to the device.");
3386 0 : if (!params.GetAttestationNonce().HasValue())
3387 : {
3388 0 : ChipLogError(Controller, "No attestation nonce found");
3389 0 : CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
3390 0 : return;
3391 : }
3392 0 : CHIP_ERROR err = SendAttestationRequestCommand(proxy, params.GetAttestationNonce().Value(), timeout);
3393 0 : if (err != CHIP_NO_ERROR)
3394 : {
3395 : // We won't get any async callbacks here, so just complete our stage.
3396 0 : ChipLogError(Controller, "Failed to send AttestationRequest command: %" CHIP_ERROR_FORMAT, err.Format());
3397 0 : CommissioningStageComplete(err);
3398 0 : return;
3399 : }
3400 0 : break;
3401 : }
3402 0 : case CommissioningStage::kAttestationVerification: {
3403 0 : ChipLogProgress(Controller, "Verifying Device Attestation information received from the device");
3404 0 : if (IsAttestationInformationMissing(params))
3405 : {
3406 0 : ChipLogError(Controller, "Missing attestation information");
3407 0 : CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
3408 0 : return;
3409 : }
3410 :
3411 : DeviceAttestationVerifier::AttestationInfo info(
3412 0 : params.GetAttestationElements().Value(),
3413 0 : proxy->GetSecureSession().Value()->AsSecureSession()->GetCryptoContext().GetAttestationChallenge(),
3414 0 : params.GetAttestationSignature().Value(), params.GetPAI().Value(), params.GetDAC().Value(),
3415 0 : params.GetAttestationNonce().Value(), params.GetRemoteVendorId().Value(), params.GetRemoteProductId().Value());
3416 :
3417 0 : CHIP_ERROR err = ValidateAttestationInfo(info);
3418 0 : if (err != CHIP_NO_ERROR)
3419 : {
3420 0 : ChipLogError(Controller, "Error validating attestation information: %" CHIP_ERROR_FORMAT, err.Format());
3421 0 : CommissioningStageComplete(CHIP_ERROR_FAILED_DEVICE_ATTESTATION);
3422 0 : return;
3423 : }
3424 : }
3425 0 : break;
3426 0 : case CommissioningStage::kAttestationRevocationCheck: {
3427 0 : ChipLogProgress(Controller, "Verifying the device's DAC chain revocation status");
3428 0 : if (IsAttestationInformationMissing(params))
3429 : {
3430 0 : ChipLogError(Controller, "Missing attestation information");
3431 0 : CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
3432 0 : return;
3433 : }
3434 :
3435 : DeviceAttestationVerifier::AttestationInfo info(
3436 0 : params.GetAttestationElements().Value(),
3437 0 : proxy->GetSecureSession().Value()->AsSecureSession()->GetCryptoContext().GetAttestationChallenge(),
3438 0 : params.GetAttestationSignature().Value(), params.GetPAI().Value(), params.GetDAC().Value(),
3439 0 : params.GetAttestationNonce().Value(), params.GetRemoteVendorId().Value(), params.GetRemoteProductId().Value());
3440 :
3441 0 : CHIP_ERROR err = CheckForRevokedDACChain(info);
3442 :
3443 0 : if (err != CHIP_NO_ERROR)
3444 : {
3445 0 : ChipLogError(Controller, "Error validating device's DAC chain revocation status: %" CHIP_ERROR_FORMAT, err.Format());
3446 0 : CommissioningStageComplete(CHIP_ERROR_FAILED_DEVICE_ATTESTATION);
3447 0 : return;
3448 : }
3449 : }
3450 0 : break;
3451 0 : case CommissioningStage::kJCMTrustVerification: {
3452 0 : CHIP_ERROR err = StartJCMTrustVerification();
3453 0 : if (err != CHIP_NO_ERROR)
3454 : {
3455 0 : ChipLogError(Controller, "Failed to start JCM Trust Verification: %" CHIP_ERROR_FORMAT, err.Format());
3456 0 : CommissioningStageComplete(err);
3457 0 : return;
3458 : }
3459 0 : break;
3460 : }
3461 :
3462 0 : case CommissioningStage::kSendOpCertSigningRequest: {
3463 0 : if (!params.GetCSRNonce().HasValue())
3464 : {
3465 0 : ChipLogError(Controller, "No CSR nonce found");
3466 0 : CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
3467 0 : return;
3468 : }
3469 0 : CHIP_ERROR err = SendOperationalCertificateSigningRequestCommand(proxy, params.GetCSRNonce().Value(), timeout);
3470 0 : if (err != CHIP_NO_ERROR)
3471 : {
3472 : // We won't get any async callbacks here, so just complete our stage.
3473 0 : ChipLogError(Controller, "Failed to send CSR request: %" CHIP_ERROR_FORMAT, err.Format());
3474 0 : CommissioningStageComplete(err);
3475 0 : return;
3476 : }
3477 0 : break;
3478 : }
3479 0 : case CommissioningStage::kValidateCSR: {
3480 0 : if (!params.GetNOCChainGenerationParameters().HasValue() || !params.GetDAC().HasValue() || !params.GetCSRNonce().HasValue())
3481 : {
3482 0 : ChipLogError(Controller, "Unable to validate CSR");
3483 0 : return CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
3484 : }
3485 : // This is non-blocking, so send the callback immediately.
3486 0 : CHIP_ERROR err = ValidateCSR(proxy, params.GetNOCChainGenerationParameters().Value().nocsrElements,
3487 0 : params.GetNOCChainGenerationParameters().Value().signature, params.GetDAC().Value(),
3488 0 : params.GetCSRNonce().Value());
3489 0 : if (err != CHIP_NO_ERROR)
3490 : {
3491 0 : ChipLogError(Controller, "Failed to validate CSR: %" CHIP_ERROR_FORMAT, err.Format());
3492 : }
3493 0 : CommissioningStageComplete(err);
3494 0 : return;
3495 : }
3496 : break;
3497 0 : case CommissioningStage::kGenerateNOCChain: {
3498 0 : if (!params.GetNOCChainGenerationParameters().HasValue() || !params.GetDAC().HasValue() || !params.GetPAI().HasValue() ||
3499 0 : !params.GetCSRNonce().HasValue())
3500 : {
3501 0 : ChipLogError(Controller, "Unable to generate NOC chain parameters");
3502 0 : return CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
3503 : }
3504 0 : CHIP_ERROR err = ProcessCSR(proxy, params.GetNOCChainGenerationParameters().Value().nocsrElements,
3505 0 : params.GetNOCChainGenerationParameters().Value().signature, params.GetDAC().Value(),
3506 0 : params.GetPAI().Value(), params.GetCSRNonce().Value());
3507 0 : if (err != CHIP_NO_ERROR)
3508 : {
3509 0 : ChipLogError(Controller, "Failed to process Operational Certificate Signing Request (CSR): %" CHIP_ERROR_FORMAT,
3510 : err.Format());
3511 0 : CommissioningStageComplete(err);
3512 0 : return;
3513 : }
3514 : }
3515 0 : break;
3516 0 : case CommissioningStage::kSendTrustedRootCert: {
3517 0 : if (!params.GetRootCert().HasValue() || !params.GetNoc().HasValue())
3518 : {
3519 0 : ChipLogError(Controller, "No trusted root cert or NOC specified");
3520 0 : CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
3521 0 : return;
3522 : }
3523 0 : CHIP_ERROR err = SendTrustedRootCertificate(proxy, params.GetRootCert().Value(), timeout);
3524 0 : if (err != CHIP_NO_ERROR)
3525 : {
3526 0 : ChipLogError(Controller, "Error sending trusted root certificate: %" CHIP_ERROR_FORMAT, err.Format());
3527 0 : CommissioningStageComplete(err);
3528 0 : return;
3529 : }
3530 :
3531 0 : err = proxy->SetPeerId(params.GetRootCert().Value(), params.GetNoc().Value());
3532 0 : if (err != CHIP_NO_ERROR)
3533 : {
3534 0 : ChipLogError(Controller, "Error setting peer id: %" CHIP_ERROR_FORMAT, err.Format());
3535 0 : CommissioningStageComplete(err);
3536 0 : return;
3537 : }
3538 0 : if (!IsOperationalNodeId(proxy->GetDeviceId()))
3539 : {
3540 0 : ChipLogError(Controller, "Given node ID is not an operational node ID");
3541 0 : CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
3542 0 : return;
3543 : }
3544 : }
3545 0 : break;
3546 0 : case CommissioningStage::kSendNOC: {
3547 0 : if (!params.GetNoc().HasValue() || !params.GetIpk().HasValue() || !params.GetAdminSubject().HasValue())
3548 : {
3549 0 : ChipLogError(Controller, "AddNOC contents not specified");
3550 0 : CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
3551 0 : return;
3552 : }
3553 0 : CHIP_ERROR err = SendOperationalCertificate(proxy, params.GetNoc().Value(), params.GetIcac(), params.GetIpk().Value(),
3554 0 : params.GetAdminSubject().Value(), timeout);
3555 0 : if (err != CHIP_NO_ERROR)
3556 : {
3557 : // We won't get any async callbacks here, so just complete our stage.
3558 0 : ChipLogError(Controller, "Error installing operational certificate with AddNOC: %" CHIP_ERROR_FORMAT, err.Format());
3559 0 : CommissioningStageComplete(err);
3560 0 : return;
3561 : }
3562 0 : break;
3563 : }
3564 0 : case CommissioningStage::kConfigureTrustedTimeSource: {
3565 0 : if (!params.GetTrustedTimeSource().HasValue())
3566 : {
3567 0 : ChipLogError(Controller, "ConfigureTrustedTimeSource stage called with no trusted time source data!");
3568 0 : CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
3569 0 : return;
3570 : }
3571 0 : TimeSynchronization::Commands::SetTrustedTimeSource::Type request;
3572 0 : request.trustedTimeSource = params.GetTrustedTimeSource().Value();
3573 0 : CHIP_ERROR err = SendCommissioningCommand(proxy, request, OnBasicSuccess, OnBasicFailure, endpoint, timeout);
3574 0 : if (err != CHIP_NO_ERROR)
3575 : {
3576 : // We won't get any async callbacks here, so just complete our stage.
3577 0 : ChipLogError(Controller, "Failed to send SendTrustedTimeSource command: %" CHIP_ERROR_FORMAT, err.Format());
3578 0 : CommissioningStageComplete(err);
3579 0 : return;
3580 : }
3581 0 : break;
3582 : }
3583 0 : case CommissioningStage::kRequestWiFiCredentials: {
3584 0 : if (!mPairingDelegate)
3585 : {
3586 0 : ChipLogError(Controller, "Unable to request Wi-Fi credentials: no delegate available");
3587 0 : CommissioningStageComplete(CHIP_ERROR_INCORRECT_STATE);
3588 0 : return;
3589 : }
3590 :
3591 0 : CHIP_ERROR err = mPairingDelegate->WiFiCredentialsNeeded(endpoint);
3592 0 : CommissioningStageComplete(err);
3593 0 : return;
3594 : }
3595 0 : case CommissioningStage::kRequestThreadCredentials: {
3596 0 : if (!mPairingDelegate)
3597 : {
3598 0 : ChipLogError(Controller, "Unable to request Thread credentials: no delegate available");
3599 0 : CommissioningStageComplete(CHIP_ERROR_INCORRECT_STATE);
3600 0 : return;
3601 : }
3602 :
3603 0 : CHIP_ERROR err = mPairingDelegate->ThreadCredentialsNeeded(endpoint);
3604 0 : CommissioningStageComplete(err);
3605 0 : return;
3606 : }
3607 0 : case CommissioningStage::kWiFiNetworkSetup: {
3608 0 : if (!params.GetWiFiCredentials().HasValue())
3609 : {
3610 0 : ChipLogError(Controller, "No wifi credentials specified");
3611 0 : CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
3612 0 : return;
3613 : }
3614 :
3615 0 : NetworkCommissioning::Commands::AddOrUpdateWiFiNetwork::Type request;
3616 0 : request.ssid = params.GetWiFiCredentials().Value().ssid;
3617 0 : request.credentials = params.GetWiFiCredentials().Value().credentials;
3618 0 : request.breadcrumb.Emplace(breadcrumb);
3619 0 : CHIP_ERROR err = SendCommissioningCommand(proxy, request, OnNetworkConfigResponse, OnBasicFailure, endpoint, timeout);
3620 0 : if (err != CHIP_NO_ERROR)
3621 : {
3622 : // We won't get any async callbacks here, so just complete our stage.
3623 0 : ChipLogError(Controller, "Failed to send AddOrUpdateWiFiNetwork command: %" CHIP_ERROR_FORMAT, err.Format());
3624 0 : CommissioningStageComplete(err);
3625 0 : return;
3626 : }
3627 : }
3628 0 : break;
3629 0 : case CommissioningStage::kThreadNetworkSetup: {
3630 0 : if (!params.GetThreadOperationalDataset().HasValue())
3631 : {
3632 0 : ChipLogError(Controller, "No thread credentials specified");
3633 0 : CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
3634 0 : return;
3635 : }
3636 0 : NetworkCommissioning::Commands::AddOrUpdateThreadNetwork::Type request;
3637 0 : request.operationalDataset = params.GetThreadOperationalDataset().Value();
3638 0 : request.breadcrumb.Emplace(breadcrumb);
3639 0 : CHIP_ERROR err = SendCommissioningCommand(proxy, request, OnNetworkConfigResponse, OnBasicFailure, endpoint, timeout);
3640 0 : if (err != CHIP_NO_ERROR)
3641 : {
3642 : // We won't get any async callbacks here, so just complete our stage.
3643 0 : ChipLogError(Controller, "Failed to send AddOrUpdateThreadNetwork command: %" CHIP_ERROR_FORMAT, err.Format());
3644 0 : CommissioningStageComplete(err);
3645 0 : return;
3646 : }
3647 : }
3648 0 : break;
3649 0 : case CommissioningStage::kFailsafeBeforeWiFiEnable:
3650 : FALLTHROUGH;
3651 : case CommissioningStage::kFailsafeBeforeThreadEnable:
3652 : // Before we try to do network enablement, make sure that our fail-safe
3653 : // is set far enough out that we can later try to do operational
3654 : // discovery without it timing out.
3655 0 : ExtendFailsafeBeforeNetworkEnable(proxy, params, step);
3656 0 : break;
3657 0 : case CommissioningStage::kWiFiNetworkEnable: {
3658 0 : if (!params.GetWiFiCredentials().HasValue())
3659 : {
3660 0 : ChipLogError(Controller, "No wifi credentials specified");
3661 0 : CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
3662 0 : return;
3663 : }
3664 0 : NetworkCommissioning::Commands::ConnectNetwork::Type request;
3665 0 : request.networkID = params.GetWiFiCredentials().Value().ssid;
3666 0 : request.breadcrumb.Emplace(breadcrumb);
3667 :
3668 0 : CHIP_ERROR err = CHIP_NO_ERROR;
3669 0 : ChipLogProgress(Controller, "SendCommand kWiFiNetworkEnable, supportsConcurrentConnection=%s",
3670 : params.GetSupportsConcurrentConnection().HasValue()
3671 : ? (params.GetSupportsConcurrentConnection().Value() ? "true" : "false")
3672 : : "missing");
3673 0 : err = SendCommissioningCommand(proxy, request, OnConnectNetworkResponse, OnBasicFailure, endpoint, timeout);
3674 :
3675 0 : if (err != CHIP_NO_ERROR)
3676 : {
3677 : // We won't get any async callbacks here, so just complete our stage.
3678 0 : ChipLogError(Controller, "Failed to send WiFi ConnectNetwork command: %" CHIP_ERROR_FORMAT, err.Format());
3679 0 : CommissioningStageComplete(err);
3680 0 : return;
3681 : }
3682 : }
3683 0 : break;
3684 0 : case CommissioningStage::kThreadNetworkEnable: {
3685 0 : ByteSpan extendedPanId;
3686 0 : chip::Thread::OperationalDataset operationalDataset;
3687 0 : if (!params.GetThreadOperationalDataset().HasValue() ||
3688 0 : operationalDataset.Init(params.GetThreadOperationalDataset().Value()) != CHIP_NO_ERROR ||
3689 0 : operationalDataset.GetExtendedPanIdAsByteSpan(extendedPanId) != CHIP_NO_ERROR)
3690 : {
3691 0 : ChipLogError(Controller, "Invalid Thread operational dataset configured at commissioner!");
3692 0 : CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
3693 0 : return;
3694 : }
3695 0 : NetworkCommissioning::Commands::ConnectNetwork::Type request;
3696 0 : request.networkID = extendedPanId;
3697 0 : request.breadcrumb.Emplace(breadcrumb);
3698 0 : CHIP_ERROR err = SendCommissioningCommand(proxy, request, OnConnectNetworkResponse, OnBasicFailure, endpoint, timeout);
3699 0 : if (err != CHIP_NO_ERROR)
3700 : {
3701 : // We won't get any async callbacks here, so just complete our stage.
3702 0 : ChipLogError(Controller, "Failed to send Thread ConnectNetwork command: %" CHIP_ERROR_FORMAT, err.Format());
3703 0 : CommissioningStageComplete(err);
3704 0 : return;
3705 : }
3706 : }
3707 0 : break;
3708 0 : case CommissioningStage::kICDGetRegistrationInfo: {
3709 0 : GetPairingDelegate()->OnICDRegistrationInfoRequired();
3710 0 : return;
3711 : }
3712 : break;
3713 0 : case CommissioningStage::kICDRegistration: {
3714 0 : IcdManagement::Commands::RegisterClient::Type request;
3715 :
3716 0 : if (!(params.GetICDCheckInNodeId().HasValue() && params.GetICDMonitoredSubject().HasValue() &&
3717 0 : params.GetICDSymmetricKey().HasValue()))
3718 : {
3719 0 : ChipLogError(Controller, "No ICD Registration information provided!");
3720 0 : CommissioningStageComplete(CHIP_ERROR_INCORRECT_STATE);
3721 0 : return;
3722 : }
3723 :
3724 0 : request.checkInNodeID = params.GetICDCheckInNodeId().Value();
3725 0 : request.monitoredSubject = params.GetICDMonitoredSubject().Value();
3726 0 : request.key = params.GetICDSymmetricKey().Value();
3727 :
3728 : CHIP_ERROR err =
3729 0 : SendCommissioningCommand(proxy, request, OnICDManagementRegisterClientResponse, OnBasicFailure, endpoint, timeout);
3730 0 : if (err != CHIP_NO_ERROR)
3731 : {
3732 : // We won't get any async callbacks here, so just complete our stage.
3733 0 : ChipLogError(Controller, "Failed to send IcdManagement.RegisterClient command: %" CHIP_ERROR_FORMAT, err.Format());
3734 0 : CommissioningStageComplete(err);
3735 0 : return;
3736 : }
3737 : }
3738 0 : break;
3739 0 : case CommissioningStage::kEvictPreviousCaseSessions: {
3740 0 : auto scopedPeerId = GetPeerScopedId(proxy->GetDeviceId());
3741 :
3742 : // If we ever had a commissioned device with this node ID before, we may
3743 : // have stale sessions to it. Make sure we don't re-use any of those,
3744 : // because clearly they are not related to this new device we are
3745 : // commissioning. We only care about sessions we might reuse, so just
3746 : // clearing the ones associated with our fabric index is good enough and
3747 : // we don't need to worry about ExpireAllSessionsOnLogicalFabric.
3748 0 : mSystemState->SessionMgr()->ExpireAllSessions(scopedPeerId);
3749 0 : CommissioningStageComplete(CHIP_NO_ERROR);
3750 0 : return;
3751 : }
3752 0 : case CommissioningStage::kFindOperationalForStayActive:
3753 : case CommissioningStage::kFindOperationalForCommissioningComplete: {
3754 : // If there is an error, CommissioningStageComplete will be called from OnDeviceConnectionFailureFn.
3755 0 : auto scopedPeerId = GetPeerScopedId(proxy->GetDeviceId());
3756 : MATTER_LOG_METRIC_BEGIN(kMetricDeviceCommissioningOperationalSetup);
3757 0 : mSystemState->CASESessionMgr()->FindOrEstablishSession(scopedPeerId, &mOnDeviceConnectedCallback,
3758 : &mOnDeviceConnectionFailureCallback
3759 : #if CHIP_DEVICE_CONFIG_ENABLE_AUTOMATIC_CASE_RETRIES
3760 : ,
3761 : /* attemptCount = */ 3, &mOnDeviceConnectionRetryCallback
3762 : #endif // CHIP_DEVICE_CONFIG_ENABLE_AUTOMATIC_CASE_RETRIES
3763 : );
3764 : }
3765 0 : break;
3766 0 : case CommissioningStage::kPrimaryOperationalNetworkFailed: {
3767 : // nothing to do. This stage indicates that the primary operational network failed and the network config should be
3768 : // removed later.
3769 0 : break;
3770 : }
3771 0 : case CommissioningStage::kRemoveWiFiNetworkConfig: {
3772 0 : NetworkCommissioning::Commands::RemoveNetwork::Type request;
3773 0 : request.networkID = params.GetWiFiCredentials().Value().ssid;
3774 0 : request.breadcrumb.Emplace(breadcrumb);
3775 0 : CHIP_ERROR err = SendCommissioningCommand(proxy, request, OnNetworkConfigResponse, OnBasicFailure, endpoint, timeout);
3776 0 : if (err != CHIP_NO_ERROR)
3777 : {
3778 : // We won't get any async callbacks here, so just complete our stage.
3779 0 : ChipLogError(Controller, "Failed to send RemoveNetwork command: %" CHIP_ERROR_FORMAT, err.Format());
3780 0 : CommissioningStageComplete(err);
3781 0 : return;
3782 : }
3783 0 : break;
3784 : }
3785 0 : case CommissioningStage::kRemoveThreadNetworkConfig: {
3786 0 : ByteSpan extendedPanId;
3787 0 : chip::Thread::OperationalDataset operationalDataset;
3788 0 : if (!params.GetThreadOperationalDataset().HasValue() ||
3789 0 : operationalDataset.Init(params.GetThreadOperationalDataset().Value()) != CHIP_NO_ERROR ||
3790 0 : operationalDataset.GetExtendedPanIdAsByteSpan(extendedPanId) != CHIP_NO_ERROR)
3791 : {
3792 0 : ChipLogError(Controller, "Invalid Thread operational dataset configured at commissioner!");
3793 0 : CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
3794 0 : return;
3795 : }
3796 0 : NetworkCommissioning::Commands::RemoveNetwork::Type request;
3797 0 : request.networkID = extendedPanId;
3798 0 : request.breadcrumb.Emplace(breadcrumb);
3799 0 : CHIP_ERROR err = SendCommissioningCommand(proxy, request, OnNetworkConfigResponse, OnBasicFailure, endpoint, timeout);
3800 0 : if (err != CHIP_NO_ERROR)
3801 : {
3802 : // We won't get any async callbacks here, so just complete our stage.
3803 0 : ChipLogError(Controller, "Failed to send RemoveNetwork command: %" CHIP_ERROR_FORMAT, err.Format());
3804 0 : CommissioningStageComplete(err);
3805 0 : return;
3806 : }
3807 0 : break;
3808 : }
3809 0 : case CommissioningStage::kICDSendStayActive: {
3810 0 : if (!(params.GetICDStayActiveDurationMsec().HasValue()))
3811 : {
3812 0 : ChipLogProgress(Controller, "Skipping kICDSendStayActive");
3813 0 : CommissioningStageComplete(CHIP_NO_ERROR);
3814 0 : return;
3815 : }
3816 :
3817 : // StayActive Command happens over CASE Connection
3818 0 : IcdManagement::Commands::StayActiveRequest::Type request;
3819 0 : request.stayActiveDuration = params.GetICDStayActiveDurationMsec().Value();
3820 0 : ChipLogError(Controller, "Send ICD StayActive with Duration %u", request.stayActiveDuration);
3821 : CHIP_ERROR err =
3822 0 : SendCommissioningCommand(proxy, request, OnICDManagementStayActiveResponse, OnBasicFailure, endpoint, timeout);
3823 0 : if (err != CHIP_NO_ERROR)
3824 : {
3825 : // We won't get any async callbacks here, so just complete our stage.
3826 0 : ChipLogError(Controller, "Failed to send IcdManagement.StayActive command: %" CHIP_ERROR_FORMAT, err.Format());
3827 0 : CommissioningStageComplete(err);
3828 0 : return;
3829 : }
3830 : }
3831 0 : break;
3832 0 : case CommissioningStage::kSendComplete: {
3833 : // CommissioningComplete command happens over the CASE connection.
3834 : GeneralCommissioning::Commands::CommissioningComplete::Type request;
3835 : CHIP_ERROR err =
3836 0 : SendCommissioningCommand(proxy, request, OnCommissioningCompleteResponse, OnBasicFailure, endpoint, timeout);
3837 0 : if (err != CHIP_NO_ERROR)
3838 : {
3839 : // We won't get any async callbacks here, so just complete our stage.
3840 0 : ChipLogError(Controller, "Failed to send CommissioningComplete command: %" CHIP_ERROR_FORMAT, err.Format());
3841 0 : CommissioningStageComplete(err);
3842 0 : return;
3843 : }
3844 : }
3845 0 : break;
3846 : #if CHIP_DEVICE_CONFIG_ENABLE_NFC_BASED_COMMISSIONING
3847 : case CommissioningStage::kUnpoweredPhaseComplete:
3848 : ChipLogProgress(Controller, "Completed unpowered commissioning phase, marking commissioning as complete");
3849 : CommissioningStageComplete(CHIP_NO_ERROR);
3850 : break;
3851 : #endif
3852 0 : case CommissioningStage::kCleanup:
3853 0 : CleanupCommissioning(proxy, proxy->GetDeviceId(), params.GetCompletionStatus());
3854 0 : break;
3855 0 : case CommissioningStage::kError:
3856 0 : mCommissioningStage = CommissioningStage::kSecurePairing;
3857 0 : break;
3858 0 : case CommissioningStage::kSecurePairing:
3859 0 : break;
3860 : }
3861 : }
3862 :
3863 0 : void DeviceCommissioner::ExtendFailsafeBeforeNetworkEnable(DeviceProxy * device, CommissioningParameters & params,
3864 : CommissioningStage step)
3865 : {
3866 0 : auto * commissioneeDevice = FindCommissioneeDevice(device->GetDeviceId());
3867 0 : if (device != commissioneeDevice)
3868 : {
3869 : // Not a commissionee device; just return.
3870 0 : ChipLogError(Controller, "Trying to extend fail-safe for an unknown commissionee with device id " ChipLogFormatX64,
3871 : ChipLogValueX64(device->GetDeviceId()));
3872 0 : CommissioningStageComplete(CHIP_ERROR_INCORRECT_STATE, CommissioningDelegate::CommissioningReport());
3873 0 : return;
3874 : }
3875 :
3876 : // Try to make sure we have at least enough time for our expected
3877 : // commissioning bits plus the MRP retries for a Sigma1.
3878 0 : uint16_t failSafeTimeoutSecs = params.GetFailsafeTimerSeconds().ValueOr(kDefaultFailsafeTimeout);
3879 0 : auto sigma1Timeout = CASESession::ComputeSigma1ResponseTimeout(commissioneeDevice->GetPairing().GetRemoteMRPConfig());
3880 0 : uint16_t sigma1TimeoutSecs = std::chrono::duration_cast<System::Clock::Seconds16>(sigma1Timeout).count();
3881 0 : if (UINT16_MAX - failSafeTimeoutSecs < sigma1TimeoutSecs)
3882 : {
3883 0 : failSafeTimeoutSecs = UINT16_MAX;
3884 : }
3885 : else
3886 : {
3887 0 : failSafeTimeoutSecs = static_cast<uint16_t>(failSafeTimeoutSecs + sigma1TimeoutSecs);
3888 : }
3889 :
3890 0 : if (!ExtendArmFailSafeInternal(commissioneeDevice, step, failSafeTimeoutSecs, MakeOptional(kMinimumCommissioningStepTimeout),
3891 : OnArmFailSafe, OnBasicFailure, /* fireAndForget = */ false))
3892 : {
3893 : // A false return is fine; we don't want to make the fail-safe shorter here.
3894 0 : CommissioningStageComplete(CHIP_NO_ERROR, CommissioningDelegate::CommissioningReport());
3895 : }
3896 : }
3897 :
3898 0 : bool DeviceCommissioner::IsAttestationInformationMissing(const CommissioningParameters & params)
3899 : {
3900 0 : if (!params.GetAttestationElements().HasValue() || !params.GetAttestationSignature().HasValue() ||
3901 0 : !params.GetAttestationNonce().HasValue() || !params.GetDAC().HasValue() || !params.GetPAI().HasValue() ||
3902 0 : !params.GetRemoteVendorId().HasValue() || !params.GetRemoteProductId().HasValue())
3903 : {
3904 0 : return true;
3905 : }
3906 :
3907 0 : return false;
3908 : }
3909 :
3910 0 : CHIP_ERROR DeviceController::GetCompressedFabricIdBytes(MutableByteSpan & outBytes) const
3911 : {
3912 0 : const auto * fabricInfo = GetFabricInfo();
3913 0 : VerifyOrReturnError(fabricInfo != nullptr, CHIP_ERROR_INVALID_FABRIC_INDEX);
3914 0 : return fabricInfo->GetCompressedFabricIdBytes(outBytes);
3915 : }
3916 :
3917 0 : CHIP_ERROR DeviceController::GetRootPublicKey(Crypto::P256PublicKey & outRootPublicKey) const
3918 : {
3919 0 : const auto * fabricTable = GetFabricTable();
3920 0 : VerifyOrReturnError(fabricTable != nullptr, CHIP_ERROR_INCORRECT_STATE);
3921 0 : return fabricTable->FetchRootPubkey(mFabricIndex, outRootPublicKey);
3922 : }
3923 :
3924 0 : bool DeviceCommissioner::HasValidCommissioningMode(const Dnssd::CommissionNodeData & nodeData)
3925 : {
3926 0 : if (nodeData.commissioningMode == to_underlying(Dnssd::CommissioningMode::kDisabled))
3927 : {
3928 0 : ChipLogProgress(Controller, "Discovered device does not have an open commissioning window.");
3929 0 : return false;
3930 : }
3931 0 : return true;
3932 : }
3933 :
3934 : } // namespace Controller
3935 : } // namespace chip
|