forked from project-chip/connectedhomeip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCHIPDeviceController.cpp
3507 lines (3089 loc) · 154 KB
/
CHIPDeviceController.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
*
* Copyright (c) 2020-2022 Project CHIP Authors
* Copyright (c) 2013-2017 Nest Labs, Inc.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file
* Implementation of CHIP Device Controller, a common class
* that implements discovery, pairing and provisioning of CHIP
* devices.
*
*/
// module header, comes first
#include <controller/CHIPDeviceController.h>
#include <app-common/zap-generated/ids/Attributes.h>
#include <app-common/zap-generated/ids/Clusters.h>
#include <app/InteractionModelEngine.h>
#include <app/OperationalSessionSetup.h>
#include <app/server/Dnssd.h>
#include <controller/CurrentFabricRemover.h>
#include <controller/InvokeInteraction.h>
#include <credentials/CHIPCert.h>
#include <credentials/DeviceAttestationCredsProvider.h>
#include <crypto/CHIPCryptoPAL.h>
#include <lib/core/CHIPCore.h>
#include <lib/core/CHIPEncoding.h>
#include <lib/core/CHIPSafeCasts.h>
#include <lib/core/ErrorStr.h>
#include <lib/core/NodeId.h>
#include <lib/support/Base64.h>
#include <lib/support/CHIPArgParser.hpp>
#include <lib/support/CHIPMem.h>
#include <lib/support/CodeUtils.h>
#include <lib/support/PersistentStorageMacros.h>
#include <lib/support/SafeInt.h>
#include <lib/support/ScopedBuffer.h>
#include <lib/support/ThreadOperationalDataset.h>
#include <lib/support/TimeUtils.h>
#include <lib/support/logging/CHIPLogging.h>
#include <messaging/ExchangeContext.h>
#include <platform/LockTracker.h>
#include <protocols/secure_channel/MessageCounterManager.h>
#include <setup_payload/QRCodeSetupPayloadParser.h>
#include <tracing/macros.h>
#if CONFIG_NETWORK_LAYER_BLE
#include <ble/Ble.h>
#include <transport/raw/BLE.h>
#endif
#include <errno.h>
#include <inttypes.h>
#include <memory>
#include <stdint.h>
#include <stdlib.h>
#include <string>
#include <time.h>
using namespace chip::Inet;
using namespace chip::System;
using namespace chip::Transport;
using namespace chip::Credentials;
using namespace chip::app::Clusters;
using namespace chip::Crypto;
namespace chip {
namespace Controller {
using namespace chip::Encoding;
#if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY
using namespace chip::Protocols::UserDirectedCommissioning;
#endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY
DeviceController::DeviceController()
{
mState = State::NotInitialized;
}
CHIP_ERROR DeviceController::Init(ControllerInitParams params)
{
assertChipStackLockedByCurrentThread();
VerifyOrReturnError(mState == State::NotInitialized, CHIP_ERROR_INCORRECT_STATE);
VerifyOrReturnError(params.systemState != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrReturnError(params.systemState->SystemLayer() != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrReturnError(params.systemState->UDPEndPointManager() != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
#if CONFIG_NETWORK_LAYER_BLE
VerifyOrReturnError(params.systemState->BleLayer() != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
#endif
VerifyOrReturnError(params.systemState->TransportMgr() != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
ReturnErrorOnFailure(mDNSResolver.Init(params.systemState->UDPEndPointManager()));
mDNSResolver.SetDiscoveryDelegate(this);
RegisterDeviceDiscoveryDelegate(params.deviceDiscoveryDelegate);
mVendorId = params.controllerVendorId;
if (params.operationalKeypair != nullptr || !params.controllerNOC.empty() || !params.controllerRCAC.empty())
{
ReturnErrorOnFailure(InitControllerNOCChain(params));
}
else if (params.fabricIndex.HasValue())
{
VerifyOrReturnError(params.systemState->Fabrics()->FabricCount() > 0, CHIP_ERROR_INVALID_ARGUMENT);
if (params.systemState->Fabrics()->FindFabricWithIndex(params.fabricIndex.Value()) != nullptr)
{
mFabricIndex = params.fabricIndex.Value();
}
else
{
ChipLogError(Controller, "There is no fabric corresponding to the given fabricIndex");
return CHIP_ERROR_INVALID_ARGUMENT;
}
}
mSystemState = params.systemState->Retain();
mState = State::Initialized;
mRemoveFromFabricTableOnShutdown = params.removeFromFabricTableOnShutdown;
mDeleteFromFabricTableOnShutdown = params.deleteFromFabricTableOnShutdown;
if (GetFabricIndex() != kUndefinedFabricIndex)
{
ChipLogProgress(Controller,
"Joined the fabric at index %d. Fabric ID is 0x" ChipLogFormatX64
" (Compressed Fabric ID: " ChipLogFormatX64 ")",
GetFabricIndex(), ChipLogValueX64(GetFabricId()), ChipLogValueX64(GetCompressedFabricId()));
}
return CHIP_NO_ERROR;
}
CHIP_ERROR DeviceController::InitControllerNOCChain(const ControllerInitParams & params)
{
FabricInfo newFabric;
constexpr uint32_t chipCertAllocatedLen = kMaxCHIPCertLength;
chip::Platform::ScopedMemoryBuffer<uint8_t> rcacBuf;
chip::Platform::ScopedMemoryBuffer<uint8_t> icacBuf;
chip::Platform::ScopedMemoryBuffer<uint8_t> nocBuf;
Credentials::P256PublicKeySpan rootPublicKeySpan;
FabricId fabricId;
NodeId nodeId;
bool hasExternallyOwnedKeypair = false;
Crypto::P256Keypair * externalOperationalKeypair = nullptr;
VendorId newFabricVendorId = params.controllerVendorId;
// There are three possibilities here in terms of what happens with our
// operational key:
// 1) We have an externally owned operational keypair.
// 2) We have an operational keypair that the fabric table should clone via
// serialize/deserialize.
// 3) We have no keypair at all, and the fabric table has been initialized
// with a key store.
if (params.operationalKeypair != nullptr)
{
hasExternallyOwnedKeypair = params.hasExternallyOwnedOperationalKeypair;
externalOperationalKeypair = params.operationalKeypair;
}
ReturnErrorCodeIf(!rcacBuf.Alloc(chipCertAllocatedLen), CHIP_ERROR_NO_MEMORY);
ReturnErrorCodeIf(!icacBuf.Alloc(chipCertAllocatedLen), CHIP_ERROR_NO_MEMORY);
ReturnErrorCodeIf(!nocBuf.Alloc(chipCertAllocatedLen), CHIP_ERROR_NO_MEMORY);
MutableByteSpan rcacSpan(rcacBuf.Get(), chipCertAllocatedLen);
ReturnErrorOnFailure(ConvertX509CertToChipCert(params.controllerRCAC, rcacSpan));
ReturnErrorOnFailure(Credentials::ExtractPublicKeyFromChipCert(rcacSpan, rootPublicKeySpan));
Crypto::P256PublicKey rootPublicKey{ rootPublicKeySpan };
MutableByteSpan icacSpan;
if (params.controllerICAC.empty())
{
ChipLogProgress(Controller, "Intermediate CA is not needed");
}
else
{
icacSpan = MutableByteSpan(icacBuf.Get(), chipCertAllocatedLen);
ReturnErrorOnFailure(ConvertX509CertToChipCert(params.controllerICAC, icacSpan));
}
MutableByteSpan nocSpan = MutableByteSpan(nocBuf.Get(), chipCertAllocatedLen);
ReturnErrorOnFailure(ConvertX509CertToChipCert(params.controllerNOC, nocSpan));
ReturnErrorOnFailure(ExtractNodeIdFabricIdFromOpCert(nocSpan, &nodeId, &fabricId));
auto * fabricTable = params.systemState->Fabrics();
const FabricInfo * fabricInfo = nullptr;
//
// When multiple controllers are permitted on the same fabric, we need to find fabrics with
// nodeId as an extra discriminant since we can have multiple FabricInfo objects that all
// collide on the same fabric. Not doing so may result in a match with an existing FabricInfo
// instance that matches the fabric in the provided NOC but is associated with a different NodeId
// that is already in use by another active controller instance. That will effectively cause it
// to change its identity inadvertently, which is not acceptable.
//
// TODO: Figure out how to clean up unreclaimed FabricInfos restored from persistent
// storage that are not in use by active DeviceController instances. Also, figure out
// how to reclaim FabricInfo slots when a DeviceController instance is deleted.
//
if (params.permitMultiControllerFabrics)
{
fabricInfo = fabricTable->FindIdentity(rootPublicKey, fabricId, nodeId);
}
else
{
fabricInfo = fabricTable->FindFabric(rootPublicKey, fabricId);
}
bool fabricFoundInTable = (fabricInfo != nullptr);
FabricIndex fabricIndex = fabricFoundInTable ? fabricInfo->GetFabricIndex() : kUndefinedFabricIndex;
CHIP_ERROR err = CHIP_NO_ERROR;
auto advertiseOperational =
params.enableServerInteractions ? FabricTable::AdvertiseIdentity::Yes : FabricTable::AdvertiseIdentity::No;
//
// We permit colliding fabrics when multiple controllers are present on the same logical fabric
// since each controller is associated with a unique FabricInfo 'identity' object and consequently,
// a unique FabricIndex.
//
// This sets a flag that will be cleared automatically when the fabric is committed/reverted later
// in this function.
//
if (params.permitMultiControllerFabrics)
{
fabricTable->PermitCollidingFabrics();
}
// We have 4 cases to handle legacy usage of direct operational key injection
if (externalOperationalKeypair)
{
// Cases 1 and 2: Injected operational keys
// CASE 1: Fabric update with injected key
if (fabricFoundInTable)
{
err = fabricTable->UpdatePendingFabricWithProvidedOpKey(fabricIndex, nocSpan, icacSpan, externalOperationalKeypair,
hasExternallyOwnedKeypair, advertiseOperational);
}
else
// CASE 2: New fabric with injected key
{
err = fabricTable->AddNewPendingTrustedRootCert(rcacSpan);
if (err == CHIP_NO_ERROR)
{
err = fabricTable->AddNewPendingFabricWithProvidedOpKey(nocSpan, icacSpan, newFabricVendorId,
externalOperationalKeypair, hasExternallyOwnedKeypair,
&fabricIndex, advertiseOperational);
}
}
}
else
{
// Cases 3 and 4: OperationalKeystore has the keys
// CASE 3: Fabric update with operational keystore
if (fabricFoundInTable)
{
VerifyOrReturnError(fabricTable->HasOperationalKeyForFabric(fabricIndex), CHIP_ERROR_KEY_NOT_FOUND);
err = fabricTable->UpdatePendingFabricWithOperationalKeystore(fabricIndex, nocSpan, icacSpan, advertiseOperational);
}
else
// CASE 4: New fabric with operational keystore
{
err = fabricTable->AddNewPendingTrustedRootCert(rcacSpan);
if (err == CHIP_NO_ERROR)
{
err = fabricTable->AddNewPendingFabricWithOperationalKeystore(nocSpan, icacSpan, newFabricVendorId, &fabricIndex,
advertiseOperational);
}
if (err == CHIP_NO_ERROR)
{
// Now that we know our planned fabric index, verify that the
// keystore has a key for it.
if (!fabricTable->HasOperationalKeyForFabric(fabricIndex))
{
err = CHIP_ERROR_KEY_NOT_FOUND;
}
}
}
}
// Commit after setup, error-out on failure.
if (err == CHIP_NO_ERROR)
{
// No need to revert on error: CommitPendingFabricData reverts internally on *any* error.
err = fabricTable->CommitPendingFabricData();
}
else
{
fabricTable->RevertPendingFabricData();
}
ReturnErrorOnFailure(err);
VerifyOrReturnError(fabricIndex != kUndefinedFabricIndex, CHIP_ERROR_INTERNAL);
mFabricIndex = fabricIndex;
mAdvertiseIdentity = advertiseOperational;
return CHIP_NO_ERROR;
}
CHIP_ERROR DeviceController::UpdateControllerNOCChain(const ByteSpan & noc, const ByteSpan & icac,
Crypto::P256Keypair * operationalKeypair,
bool operationalKeypairExternalOwned)
{
VerifyOrReturnError(mFabricIndex != kUndefinedFabricIndex, CHIP_ERROR_INTERNAL);
VerifyOrReturnError(mSystemState != nullptr, CHIP_ERROR_INTERNAL);
FabricTable * fabricTable = mSystemState->Fabrics();
CHIP_ERROR err = CHIP_NO_ERROR;
FabricId fabricId;
NodeId nodeId;
CATValues oldCats;
CATValues newCats;
ReturnErrorOnFailure(ExtractNodeIdFabricIdFromOpCert(noc, &nodeId, &fabricId));
ReturnErrorOnFailure(fabricTable->FetchCATs(mFabricIndex, oldCats));
ReturnErrorOnFailure(ExtractCATsFromOpCert(noc, newCats));
bool needCloseSession = true;
if (GetFabricInfo()->GetNodeId() == nodeId && oldCats == newCats)
{
needCloseSession = false;
}
if (operationalKeypair != nullptr)
{
err = fabricTable->UpdatePendingFabricWithProvidedOpKey(mFabricIndex, noc, icac, operationalKeypair,
operationalKeypairExternalOwned, mAdvertiseIdentity);
}
else
{
VerifyOrReturnError(fabricTable->HasOperationalKeyForFabric(mFabricIndex), CHIP_ERROR_KEY_NOT_FOUND);
err = fabricTable->UpdatePendingFabricWithOperationalKeystore(mFabricIndex, noc, icac, mAdvertiseIdentity);
}
if (err == CHIP_NO_ERROR)
{
err = fabricTable->CommitPendingFabricData();
}
else
{
fabricTable->RevertPendingFabricData();
}
ReturnErrorOnFailure(err);
if (needCloseSession)
{
// If the node id or CATs have changed, our existing CASE sessions are no longer valid,
// because the other side will think anything coming over those sessions comes from our
// old node ID, and the new CATs might not satisfy the ACL requirements of the other side.
mSystemState->SessionMgr()->ExpireAllSessionsForFabric(mFabricIndex);
}
ChipLogProgress(Controller, "Controller NOC chain has updated");
return CHIP_NO_ERROR;
}
void DeviceController::Shutdown()
{
assertChipStackLockedByCurrentThread();
VerifyOrReturn(mState != State::NotInitialized);
// If our state is initialialized it means mSystemState is valid,
// and we can use it below before we release our reference to it.
ChipLogDetail(Controller, "Shutting down the controller");
mState = State::NotInitialized;
if (mFabricIndex != kUndefinedFabricIndex)
{
// Shut down any subscription clients for this fabric.
app::InteractionModelEngine::GetInstance()->ShutdownSubscriptions(mFabricIndex);
// Shut down any ongoing CASE session activity we have. We're going to
// assume that all sessions for our fabric belong to us here.
mSystemState->CASESessionMgr()->ReleaseSessionsForFabric(mFabricIndex);
// TODO: The CASE session manager does not shut down existing CASE
// sessions. It just shuts down any ongoing CASE session establishment
// we're in the middle of as initiator. Maybe it should shut down
// existing sessions too?
mSystemState->SessionMgr()->ExpireAllSessionsForFabric(mFabricIndex);
if (mDeleteFromFabricTableOnShutdown)
{
mSystemState->Fabrics()->Delete(mFabricIndex);
}
else if (mRemoveFromFabricTableOnShutdown)
{
mSystemState->Fabrics()->Forget(mFabricIndex);
}
}
mSystemState->Release();
mSystemState = nullptr;
mDNSResolver.Shutdown();
mDeviceDiscoveryDelegate = nullptr;
}
CHIP_ERROR DeviceController::GetPeerAddressAndPort(NodeId peerId, Inet::IPAddress & addr, uint16_t & port)
{
VerifyOrReturnError(mState == State::Initialized, CHIP_ERROR_INCORRECT_STATE);
Transport::PeerAddress peerAddr;
ReturnErrorOnFailure(mSystemState->CASESessionMgr()->GetPeerAddress(GetPeerScopedId(peerId), peerAddr));
addr = peerAddr.GetIPAddress();
port = peerAddr.GetPort();
return CHIP_NO_ERROR;
}
CHIP_ERROR DeviceController::GetPeerAddress(NodeId nodeId, Transport::PeerAddress & addr)
{
VerifyOrReturnError(mState == State::Initialized, CHIP_ERROR_INCORRECT_STATE);
ReturnErrorOnFailure(mSystemState->CASESessionMgr()->GetPeerAddress(GetPeerScopedId(nodeId), addr));
return CHIP_NO_ERROR;
}
CHIP_ERROR DeviceController::ComputePASEVerifier(uint32_t iterations, uint32_t setupPincode, const ByteSpan & salt,
Spake2pVerifier & outVerifier)
{
ReturnErrorOnFailure(PASESession::GeneratePASEVerifier(outVerifier, iterations, salt, /* useRandomPIN= */ false, setupPincode));
return CHIP_NO_ERROR;
}
ControllerDeviceInitParams DeviceController::GetControllerDeviceInitParams()
{
return ControllerDeviceInitParams{
.sessionManager = mSystemState->SessionMgr(),
.exchangeMgr = mSystemState->ExchangeMgr(),
};
}
DeviceCommissioner::DeviceCommissioner() :
mOnDeviceConnectedCallback(OnDeviceConnectedFn, this), mOnDeviceConnectionFailureCallback(OnDeviceConnectionFailureFn, this),
#if CHIP_DEVICE_CONFIG_ENABLE_AUTOMATIC_CASE_RETRIES
mOnDeviceConnectionRetryCallback(OnDeviceConnectionRetryFn, this),
#endif // CHIP_DEVICE_CONFIG_ENABLE_AUTOMATIC_CASE_RETRIES
mDeviceAttestationInformationVerificationCallback(OnDeviceAttestationInformationVerification, this),
mDeviceNOCChainCallback(OnDeviceNOCChainGeneration, this), mSetUpCodePairer(this)
{}
CHIP_ERROR DeviceCommissioner::Init(CommissionerInitParams params)
{
VerifyOrReturnError(params.operationalCredentialsDelegate != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
mOperationalCredentialsDelegate = params.operationalCredentialsDelegate;
ReturnErrorOnFailure(DeviceController::Init(params));
mPairingDelegate = params.pairingDelegate;
// Configure device attestation validation
mDeviceAttestationVerifier = params.deviceAttestationVerifier;
if (mDeviceAttestationVerifier == nullptr)
{
mDeviceAttestationVerifier = Credentials::GetDeviceAttestationVerifier();
if (mDeviceAttestationVerifier == nullptr)
{
ChipLogError(Controller,
"Missing DeviceAttestationVerifier configuration at DeviceCommissioner init and none set with "
"Credentials::SetDeviceAttestationVerifier()!");
return CHIP_ERROR_INVALID_ARGUMENT;
}
// We fell back on a default from singleton accessor.
ChipLogProgress(Controller,
"*** Missing DeviceAttestationVerifier configuration at DeviceCommissioner init: using global default, "
"consider passing one in CommissionerInitParams.");
}
if (params.defaultCommissioner != nullptr)
{
mDefaultCommissioner = params.defaultCommissioner;
}
else
{
mDefaultCommissioner = &mAutoCommissioner;
}
#if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY // make this commissioner discoverable
mUdcTransportMgr = chip::Platform::New<UdcTransportMgr>();
ReturnErrorOnFailure(mUdcTransportMgr->Init(Transport::UdpListenParameters(mSystemState->UDPEndPointManager())
.SetAddressType(Inet::IPAddressType::kIPv6)
.SetListenPort(static_cast<uint16_t>(mUdcListenPort))
#if INET_CONFIG_ENABLE_IPV4
,
Transport::UdpListenParameters(mSystemState->UDPEndPointManager())
.SetAddressType(Inet::IPAddressType::kIPv4)
.SetListenPort(static_cast<uint16_t>(mUdcListenPort))
#endif // INET_CONFIG_ENABLE_IPV4
));
mUdcServer = chip::Platform::New<UserDirectedCommissioningServer>();
mUdcTransportMgr->SetSessionManager(mUdcServer);
mUdcServer->SetTransportManager(mUdcTransportMgr);
mUdcServer->SetInstanceNameResolver(this);
#endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY
mSetUpCodePairer.SetSystemLayer(mSystemState->SystemLayer());
#if CONFIG_NETWORK_LAYER_BLE
mSetUpCodePairer.SetBleLayer(mSystemState->BleLayer());
#endif // CONFIG_NETWORK_LAYER_BLE
return CHIP_NO_ERROR;
}
void DeviceCommissioner::Shutdown()
{
VerifyOrReturn(mState != State::NotInitialized);
ChipLogDetail(Controller, "Shutting down the commissioner");
mSetUpCodePairer.StopPairing();
// Check to see if pairing in progress before shutting down
CommissioneeDeviceProxy * device = mDeviceInPASEEstablishment;
if (device != nullptr && device->IsSessionSetupInProgress())
{
ChipLogDetail(Controller, "Setup in progress, stopping setup before shutting down");
OnSessionEstablishmentError(CHIP_ERROR_CONNECTION_ABORTED);
}
CancelCommissioningInteractions();
#if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY // make this commissioner discoverable
if (mUdcTransportMgr != nullptr)
{
chip::Platform::Delete(mUdcTransportMgr);
mUdcTransportMgr = nullptr;
}
if (mUdcServer != nullptr)
{
mUdcServer->SetInstanceNameResolver(nullptr);
chip::Platform::Delete(mUdcServer);
mUdcServer = nullptr;
}
#endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY
// Release everything from the commissionee device pool here.
// Make sure to use ReleaseCommissioneeDevice so we don't keep dangling
// pointers to the device objects.
mCommissioneeDevicePool.ForEachActiveObject([this](auto * commissioneeDevice) {
ReleaseCommissioneeDevice(commissioneeDevice);
return Loop::Continue;
});
DeviceController::Shutdown();
}
CommissioneeDeviceProxy * DeviceCommissioner::FindCommissioneeDevice(NodeId id)
{
MATTER_TRACE_SCOPE("FindCommissioneeDevice", "DeviceCommissioner");
CommissioneeDeviceProxy * foundDevice = nullptr;
mCommissioneeDevicePool.ForEachActiveObject([&](auto * deviceProxy) {
if (deviceProxy->GetDeviceId() == id)
{
foundDevice = deviceProxy;
return Loop::Break;
}
return Loop::Continue;
});
return foundDevice;
}
CommissioneeDeviceProxy * DeviceCommissioner::FindCommissioneeDevice(const Transport::PeerAddress & peerAddress)
{
CommissioneeDeviceProxy * foundDevice = nullptr;
mCommissioneeDevicePool.ForEachActiveObject([&](auto * deviceProxy) {
if (deviceProxy->GetPeerAddress() == peerAddress)
{
foundDevice = deviceProxy;
return Loop::Break;
}
return Loop::Continue;
});
return foundDevice;
}
void DeviceCommissioner::ReleaseCommissioneeDevice(CommissioneeDeviceProxy * device)
{
#if CONFIG_NETWORK_LAYER_BLE
if (mSystemState->BleLayer() != nullptr && device->GetDeviceTransportType() == Transport::Type::kBle)
{
// We only support one BLE connection, so if this is BLE, close it
ChipLogProgress(Discovery, "Closing all BLE connections");
mSystemState->BleLayer()->CloseAllBleConnections();
}
#endif
// Make sure that there will be no dangling pointer
if (mDeviceInPASEEstablishment == device)
{
mDeviceInPASEEstablishment = nullptr;
}
if (mDeviceBeingCommissioned == device)
{
mDeviceBeingCommissioned = nullptr;
}
// Release the commissionee device after we have nulled out our pointers,
// because that can call back in to us with error notifications as the
// session is released.
mCommissioneeDevicePool.ReleaseObject(device);
}
CHIP_ERROR DeviceCommissioner::GetDeviceBeingCommissioned(NodeId deviceId, CommissioneeDeviceProxy ** out_device)
{
VerifyOrReturnError(out_device != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
CommissioneeDeviceProxy * device = FindCommissioneeDevice(deviceId);
VerifyOrReturnError(device != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
*out_device = device;
return CHIP_NO_ERROR;
}
CHIP_ERROR DeviceCommissioner::PairDevice(NodeId remoteDeviceId, const char * setUpCode, const CommissioningParameters & params,
DiscoveryType discoveryType, Optional<Dnssd::CommonResolutionData> resolutionData)
{
MATTER_TRACE_SCOPE("PairDevice", "DeviceCommissioner");
if (mDefaultCommissioner == nullptr)
{
ChipLogError(Controller, "No default commissioner is specified");
return CHIP_ERROR_INCORRECT_STATE;
}
ReturnErrorOnFailure(mDefaultCommissioner->SetCommissioningParameters(params));
return mSetUpCodePairer.PairDevice(remoteDeviceId, setUpCode, SetupCodePairerBehaviour::kCommission, discoveryType,
resolutionData);
}
CHIP_ERROR DeviceCommissioner::PairDevice(NodeId remoteDeviceId, const char * setUpCode, DiscoveryType discoveryType,
Optional<Dnssd::CommonResolutionData> resolutionData)
{
MATTER_TRACE_SCOPE("PairDevice", "DeviceCommissioner");
return mSetUpCodePairer.PairDevice(remoteDeviceId, setUpCode, SetupCodePairerBehaviour::kCommission, discoveryType,
resolutionData);
}
CHIP_ERROR DeviceCommissioner::PairDevice(NodeId remoteDeviceId, RendezvousParameters & params)
{
MATTER_TRACE_SCOPE("PairDevice", "DeviceCommissioner");
ReturnErrorOnFailure(EstablishPASEConnection(remoteDeviceId, params));
return Commission(remoteDeviceId);
}
CHIP_ERROR DeviceCommissioner::PairDevice(NodeId remoteDeviceId, RendezvousParameters & rendezvousParams,
CommissioningParameters & commissioningParams)
{
MATTER_TRACE_SCOPE("PairDevice", "DeviceCommissioner");
ReturnErrorOnFailure(EstablishPASEConnection(remoteDeviceId, rendezvousParams));
return Commission(remoteDeviceId, commissioningParams);
}
CHIP_ERROR DeviceCommissioner::EstablishPASEConnection(NodeId remoteDeviceId, const char * setUpCode, DiscoveryType discoveryType,
Optional<Dnssd::CommonResolutionData> resolutionData)
{
MATTER_TRACE_SCOPE("EstablishPASEConnection", "DeviceCommissioner");
return mSetUpCodePairer.PairDevice(remoteDeviceId, setUpCode, SetupCodePairerBehaviour::kPaseOnly, discoveryType,
resolutionData);
}
CHIP_ERROR DeviceCommissioner::EstablishPASEConnection(NodeId remoteDeviceId, RendezvousParameters & params)
{
MATTER_TRACE_SCOPE("EstablishPASEConnection", "DeviceCommissioner");
CHIP_ERROR err = CHIP_NO_ERROR;
CommissioneeDeviceProxy * device = nullptr;
CommissioneeDeviceProxy * current = nullptr;
Transport::PeerAddress peerAddress = Transport::PeerAddress::UDP(Inet::IPAddress::Any);
Messaging::ExchangeContext * exchangeCtxt = nullptr;
Optional<SessionHandle> session;
VerifyOrExit(mState == State::Initialized, err = CHIP_ERROR_INCORRECT_STATE);
VerifyOrExit(mDeviceInPASEEstablishment == nullptr, err = CHIP_ERROR_INCORRECT_STATE);
// TODO(#13940): We need to specify the peer address for BLE transport in bindings.
if (params.GetPeerAddress().GetTransportType() == Transport::Type::kBle ||
params.GetPeerAddress().GetTransportType() == Transport::Type::kUndefined)
{
#if CONFIG_NETWORK_LAYER_BLE
#if CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE
ConnectBleTransportToSelf();
#endif // CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE
if (!params.HasBleLayer())
{
params.SetPeerAddress(Transport::PeerAddress::BLE());
}
peerAddress = Transport::PeerAddress::BLE();
#endif // CONFIG_NETWORK_LAYER_BLE
}
else if (params.GetPeerAddress().GetTransportType() == Transport::Type::kTcp ||
params.GetPeerAddress().GetTransportType() == Transport::Type::kUdp)
{
peerAddress = Transport::PeerAddress::UDP(params.GetPeerAddress().GetIPAddress(), params.GetPeerAddress().GetPort(),
params.GetPeerAddress().GetInterface());
}
current = FindCommissioneeDevice(peerAddress);
if (current != nullptr)
{
if (current->GetDeviceId() == remoteDeviceId)
{
// We might be able to just reuse its connection if it has one or is
// working on one.
if (current->IsSecureConnected())
{
if (mPairingDelegate)
{
// We already have an open secure session to this device, call the callback immediately and early return.
mPairingDelegate->OnPairingComplete(CHIP_NO_ERROR);
}
return CHIP_NO_ERROR;
}
if (current->IsSessionSetupInProgress())
{
// We're not connected yet, but we're in the process of connecting. Pairing delegate will get a callback when
// connection completes
return CHIP_NO_ERROR;
}
}
// Either the consumer wants to assign a different device id to this
// peer address now (so we can't reuse the commissionee device we have
// already) or something has gone strange. Delete the old device, try
// again.
ChipLogError(Controller, "Found unconnected device, removing");
ReleaseCommissioneeDevice(current);
}
device = mCommissioneeDevicePool.CreateObject();
VerifyOrExit(device != nullptr, err = CHIP_ERROR_NO_MEMORY);
mDeviceInPASEEstablishment = device;
device->Init(GetControllerDeviceInitParams(), remoteDeviceId, peerAddress);
device->UpdateDeviceData(params.GetPeerAddress(), params.GetMRPConfig());
#if CONFIG_NETWORK_LAYER_BLE
if (params.GetPeerAddress().GetTransportType() == Transport::Type::kBle)
{
if (params.HasConnectionObject())
{
SuccessOrExit(err = mSystemState->BleLayer()->NewBleConnectionByObject(params.GetConnectionObject()));
}
else if (params.HasDiscoveredObject())
{
// The RendezvousParameters argument needs to be recovered if the search succeed, so save them
// for later.
mRendezvousParametersForDeviceDiscoveredOverBle = params;
SuccessOrExit(err = mSystemState->BleLayer()->NewBleConnectionByObject(params.GetDiscoveredObject(), this,
OnDiscoveredDeviceOverBleSuccess,
OnDiscoveredDeviceOverBleError));
ExitNow(CHIP_NO_ERROR);
}
else if (params.HasDiscriminator())
{
// The RendezvousParameters argument needs to be recovered if the search succeed, so save them
// for later.
mRendezvousParametersForDeviceDiscoveredOverBle = params;
SetupDiscriminator discriminator;
discriminator.SetLongValue(params.GetDiscriminator());
SuccessOrExit(err = mSystemState->BleLayer()->NewBleConnectionByDiscriminator(
discriminator, this, OnDiscoveredDeviceOverBleSuccess, OnDiscoveredDeviceOverBleError));
ExitNow(CHIP_NO_ERROR);
}
else
{
ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT);
}
}
#endif
session = mSystemState->SessionMgr()->CreateUnauthenticatedSession(params.GetPeerAddress(), params.GetMRPConfig());
VerifyOrExit(session.HasValue(), err = CHIP_ERROR_NO_MEMORY);
// Allocate the exchange immediately before calling PASESession::Pair.
//
// PASESession::Pair takes ownership of the exchange and will free it on
// error, but can only do this if it is actually called. Allocating the
// exchange context right before calling Pair ensures that if allocation
// succeeds, PASESession has taken ownership.
exchangeCtxt = mSystemState->ExchangeMgr()->NewContext(session.Value(), &device->GetPairing());
VerifyOrExit(exchangeCtxt != nullptr, err = CHIP_ERROR_INTERNAL);
err = device->GetPairing().Pair(*mSystemState->SessionMgr(), params.GetSetupPINCode(), GetLocalMRPConfig(), exchangeCtxt, this);
SuccessOrExit(err);
exit:
if (err != CHIP_NO_ERROR)
{
if (device != nullptr)
{
ReleaseCommissioneeDevice(device);
}
}
return err;
}
#if CONFIG_NETWORK_LAYER_BLE
void DeviceCommissioner::OnDiscoveredDeviceOverBleSuccess(void * appState, BLE_CONNECTION_OBJECT connObj)
{
auto self = static_cast<DeviceCommissioner *>(appState);
auto device = self->mDeviceInPASEEstablishment;
if (nullptr != device && device->GetDeviceTransportType() == Transport::Type::kBle)
{
auto remoteId = device->GetDeviceId();
auto params = self->mRendezvousParametersForDeviceDiscoveredOverBle;
params.SetConnectionObject(connObj);
self->mRendezvousParametersForDeviceDiscoveredOverBle = RendezvousParameters();
self->ReleaseCommissioneeDevice(device);
LogErrorOnFailure(self->EstablishPASEConnection(remoteId, params));
}
}
void DeviceCommissioner::OnDiscoveredDeviceOverBleError(void * appState, CHIP_ERROR err)
{
auto self = static_cast<DeviceCommissioner *>(appState);
auto device = self->mDeviceInPASEEstablishment;
if (nullptr != device && device->GetDeviceTransportType() == Transport::Type::kBle)
{
self->ReleaseCommissioneeDevice(device);
self->mRendezvousParametersForDeviceDiscoveredOverBle = RendezvousParameters();
// Callback is required when BLE discovery fails, otherwise the caller will always be in a suspended state
// A better way to handle it should define a new error code
if (self->mPairingDelegate != nullptr)
{
self->mPairingDelegate->OnPairingComplete(err);
}
}
}
#endif // CONFIG_NETWORK_LAYER_BLE
CHIP_ERROR DeviceCommissioner::Commission(NodeId remoteDeviceId, CommissioningParameters & params)
{
if (mDefaultCommissioner == nullptr)
{
ChipLogError(Controller, "No default commissioner is specified");
return CHIP_ERROR_INCORRECT_STATE;
}
ReturnErrorOnFailure(mDefaultCommissioner->SetCommissioningParameters(params));
return Commission(remoteDeviceId);
}
CHIP_ERROR DeviceCommissioner::Commission(NodeId remoteDeviceId)
{
MATTER_TRACE_SCOPE("Commission", "DeviceCommissioner");
if (mDefaultCommissioner == nullptr)
{
ChipLogError(Controller, "No default commissioner is specified");
return CHIP_ERROR_INCORRECT_STATE;
}
CommissioneeDeviceProxy * device = FindCommissioneeDevice(remoteDeviceId);
if (device == nullptr || (!device->IsSecureConnected() && !device->IsSessionSetupInProgress()))
{
ChipLogError(Controller, "Invalid device for commissioning " ChipLogFormatX64, ChipLogValueX64(remoteDeviceId));
return CHIP_ERROR_INCORRECT_STATE;
}
if (!device->IsSecureConnected() && device != mDeviceInPASEEstablishment)
{
// We should not end up in this state because we won't attempt to establish more than one connection at a time.
ChipLogError(Controller, "Device is not connected and not being paired " ChipLogFormatX64, ChipLogValueX64(remoteDeviceId));
return CHIP_ERROR_INCORRECT_STATE;
}
if (mCommissioningStage != CommissioningStage::kSecurePairing)
{
ChipLogError(Controller, "Commissioning already in progress (stage '%s') - not restarting",
StageToString(mCommissioningStage));
return CHIP_ERROR_INCORRECT_STATE;
}
ChipLogProgress(Controller, "Commission called for node ID 0x" ChipLogFormatX64, ChipLogValueX64(remoteDeviceId));
mDefaultCommissioner->SetOperationalCredentialsDelegate(mOperationalCredentialsDelegate);
if (device->IsSecureConnected())
{
mDefaultCommissioner->StartCommissioning(this, device);
}
else
{
mRunCommissioningAfterConnection = true;
}
return CHIP_NO_ERROR;
}
CHIP_ERROR
DeviceCommissioner::ContinueCommissioningAfterDeviceAttestation(DeviceProxy * device,
Credentials::AttestationVerificationResult attestationResult)
{
MATTER_TRACE_SCOPE("continueCommissioningDevice", "DeviceCommissioner");
if (mDefaultCommissioner == nullptr)
{
ChipLogError(Controller, "No default commissioner is specified");
return CHIP_ERROR_INCORRECT_STATE;
}
if (device == nullptr || device != mDeviceBeingCommissioned)
{
ChipLogError(Controller, "Invalid device for commissioning %p", device);
return CHIP_ERROR_INCORRECT_STATE;
}
CommissioneeDeviceProxy * commissioneeDevice = FindCommissioneeDevice(device->GetDeviceId());
if (commissioneeDevice == nullptr)
{
ChipLogError(Controller, "Couldn't find commissionee device");
return CHIP_ERROR_INCORRECT_STATE;
}
if (!commissioneeDevice->IsSecureConnected() || commissioneeDevice != mDeviceBeingCommissioned)
{
ChipLogError(Controller, "Invalid device for commissioning after attestation failure: 0x" ChipLogFormatX64,
ChipLogValueX64(commissioneeDevice->GetDeviceId()));
return CHIP_ERROR_INCORRECT_STATE;
}
if (mCommissioningStage != CommissioningStage::kAttestationRevocationCheck)
{
ChipLogError(Controller, "Commissioning is not attestation verification phase");
return CHIP_ERROR_INCORRECT_STATE;
}
ChipLogProgress(Controller, "Continuing commissioning after attestation failure for device ID 0x" ChipLogFormatX64,
ChipLogValueX64(commissioneeDevice->GetDeviceId()));
if (attestationResult != AttestationVerificationResult::kSuccess)
{
ChipLogError(Controller, "Client selected error: %u for failed 'Attestation Information' for device",
to_underlying(attestationResult));
CommissioningDelegate::CommissioningReport report;
report.Set<AttestationErrorInfo>(attestationResult);
CommissioningStageComplete(CHIP_ERROR_INTERNAL, report);
}
else
{
ChipLogProgress(Controller, "Overriding attestation failure per client and continuing commissioning");
CommissioningStageComplete(CHIP_NO_ERROR);
}
return CHIP_NO_ERROR;
}
CHIP_ERROR DeviceCommissioner::StopPairing(NodeId remoteDeviceId)
{
VerifyOrReturnError(mState == State::Initialized, CHIP_ERROR_INCORRECT_STATE);
VerifyOrReturnError(remoteDeviceId != kUndefinedNodeId, CHIP_ERROR_INVALID_ARGUMENT);
ChipLogProgress(Controller, "StopPairing called for node ID 0x" ChipLogFormatX64, ChipLogValueX64(remoteDeviceId));
// If we're still in the process of discovering the device, just stop the SetUpCodePairer
if (mSetUpCodePairer.StopPairing(remoteDeviceId))
{
mRunCommissioningAfterConnection = false;
return CHIP_NO_ERROR;
}
// Otherwise we might be pairing and / or commissioning it.
CommissioneeDeviceProxy * device = FindCommissioneeDevice(remoteDeviceId);
VerifyOrReturnError(device != nullptr, CHIP_ERROR_INVALID_DEVICE_DESCRIPTOR);
if (mDeviceBeingCommissioned == device)
{
CancelCommissioningInteractions();
CommissioningStageComplete(CHIP_ERROR_CANCELLED);
}
else
{