forked from project-chip/connectedhomeip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOpCredsBinding.cpp
476 lines (412 loc) · 19.9 KB
/
OpCredsBinding.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
/*
*
* Copyright (c) 2020-2022 Project CHIP Authors
* Copyright (c) 2019-2020 Google LLC.
* Copyright (c) 2013-2018 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.
*/
#include <type_traits>
#include "ChipDeviceController-ScriptDevicePairingDelegate.h"
#include "ChipDeviceController-StorageDelegate.h"
#include "controller/python/chip/interaction_model/Delegate.h"
#include <controller/CHIPDeviceController.h>
#include <controller/CHIPDeviceControllerFactory.h>
#include <controller/ExampleOperationalCredentialsIssuer.h>
#include <lib/support/BytesToHex.h>
#include <lib/support/CHIPMem.h>
#include <lib/support/CodeUtils.h>
#include <lib/support/DLLUtil.h>
#include <lib/support/ScopedBuffer.h>
#include <lib/support/TestGroupData.h>
#include <lib/support/logging/CHIPLogging.h>
#include <credentials/GroupDataProviderImpl.h>
#include <credentials/attestation_verifier/DefaultDeviceAttestationVerifier.h>
#include <credentials/attestation_verifier/DeviceAttestationVerifier.h>
#include <credentials/attestation_verifier/FileAttestationTrustStore.h>
using namespace chip;
static_assert(std::is_same<uint32_t, ChipError::StorageType>::value, "python assumes CHIP_ERROR maps to c_uint32");
using Py_GenerateNOCChainFunc = void (*)(void * pyContext, const char * csrElements, const char * attestationSignature,
const char * dac, const char * pai, const char * paa,
Controller::OnNOCChainGeneration onNocChainGenerationFunc);
using Py_SetNodeIdForNextNOCRequest = void (*)(void * pyContext, NodeId nodeId);
using Py_SetFabricIdForNextNOCRequest = void (*)(void * pyContext, FabricId fabricId);
namespace {
const chip::Credentials::AttestationTrustStore * GetTestFileAttestationTrustStore(const char * paaTrustStorePath)
{
static chip::Credentials::FileAttestationTrustStore attestationTrustStore{ paaTrustStorePath };
return &attestationTrustStore;
}
} // namespace
namespace chip {
namespace Controller {
namespace Python {
class OperationalCredentialsAdapter : public OperationalCredentialsDelegate
{
public:
OperationalCredentialsAdapter(uint32_t fabricCredentialsIndex) : mExampleOpCredsIssuer(fabricCredentialsIndex) {}
CHIP_ERROR Initialize(PersistentStorageDelegate & storageDelegate) { return mExampleOpCredsIssuer.Initialize(storageDelegate); }
CHIP_ERROR GenerateNOCChain(NodeId nodeId, FabricId fabricId, const CATValues & cats, const Crypto::P256PublicKey & pubKey,
MutableByteSpan & rcac, MutableByteSpan & icac, MutableByteSpan & noc)
{
return mExampleOpCredsIssuer.GenerateNOCChainAfterValidation(nodeId, fabricId, cats, pubKey, rcac, icac, noc);
}
void SetMaximallyLargeCertsUsed(bool enabled) { mExampleOpCredsIssuer.SetMaximallyLargeCertsUsed(enabled); }
private:
CHIP_ERROR GenerateNOCChain(const ByteSpan & csrElements, const ByteSpan & csrNonce, const ByteSpan & attestationSignature,
const ByteSpan & attestationChallenge, const ByteSpan & DAC, const ByteSpan & PAI,
Callback::Callback<OnNOCChainGeneration> * onCompletion) override
{
return mExampleOpCredsIssuer.GenerateNOCChain(csrElements, csrNonce, attestationSignature, attestationChallenge, DAC, PAI,
onCompletion);
}
void SetNodeIdForNextNOCRequest(NodeId nodeId) override { mExampleOpCredsIssuer.SetNodeIdForNextNOCRequest(nodeId); }
void SetFabricIdForNextNOCRequest(FabricId fabricId) override { mExampleOpCredsIssuer.SetFabricIdForNextNOCRequest(fabricId); }
ExampleOperationalCredentialsIssuer mExampleOpCredsIssuer;
};
} // namespace Python
} // namespace Controller
} // namespace chip
extern chip::Credentials::GroupDataProviderImpl sGroupDataProvider;
extern chip::Controller::ScriptDevicePairingDelegate sPairingDelegate;
class TestCommissioner : public chip::Controller::AutoCommissioner
{
public:
TestCommissioner() { Reset(); }
~TestCommissioner() {}
CHIP_ERROR SetCommissioningParameters(const chip::Controller::CommissioningParameters & params) override
{
mIsWifi = false;
mIsThread = false;
if (params.GetWiFiCredentials().HasValue())
{
mIsWifi = true;
}
else if (params.GetThreadOperationalDataset().HasValue())
{
mIsThread = true;
}
return chip::Controller::AutoCommissioner::SetCommissioningParameters(params);
}
CHIP_ERROR CommissioningStepFinished(CHIP_ERROR err,
chip::Controller::CommissioningDelegate::CommissioningReport report) override
{
mTestCommissionerUsed = true;
if (mFailOnReportAfterStage == report.stageCompleted)
{
return CHIP_ERROR_INTERNAL;
}
if (mSimulateFailureOnStage == report.stageCompleted)
{
// Pretend we received an error from the device during this stage
err = CHIP_ERROR_INTERNAL;
}
return chip::Controller::AutoCommissioner::CommissioningStepFinished(err, report);
}
// This will cause the COMMISSIONER to fail after the given stage. Setting this to kSecurePairing will cause the
// StartCommissioning call to fail.
bool SimulateFailAfter(chip::Controller::CommissioningStage stage)
{
ChipLogProgress(Controller, "setting simulate fail after stage %s", chip::Controller::StageToString(stage));
if (!ValidStage(stage) && stage != chip::Controller::CommissioningStage::kError)
{
return false;
}
mSimulateFailureOnStage = stage;
return true;
}
bool SimulateFailOnReport(chip::Controller::CommissioningStage stage)
{
if (!ValidStage(stage) && stage != chip::Controller::CommissioningStage::kError)
{
return false;
}
mFailOnReportAfterStage = stage;
return true;
}
bool CheckCallbacks()
{
bool successFailureOk;
bool updatesOk;
if (mFailOnReportAfterStage != chip::Controller::CommissioningStage::kError)
{
successFailureOk = mReceivedCommissioningFailureStage == mFailOnReportAfterStage && !mReceivedCommissioningSuccess;
updatesOk = StatusUpdatesOk(mFailOnReportAfterStage);
}
else if (mSimulateFailureOnStage != chip::Controller::CommissioningStage::kError)
{
successFailureOk = mReceivedCommissioningFailureStage == mSimulateFailureOnStage && !mReceivedCommissioningSuccess;
updatesOk = StatusUpdatesOk(mSimulateFailureOnStage);
}
else
{
successFailureOk = mReceivedCommissioningSuccess;
updatesOk = StatusUpdatesOk(chip::Controller::CommissioningStage::kError);
}
ChipLogProgress(Controller, "Checking callbacks: success failure ok? %d updates ok? %d", successFailureOk, updatesOk);
return successFailureOk && updatesOk;
}
bool CheckPaseConnection(NodeId nodeId)
{
bool paseShouldBeOpen = false;
if (chip::to_underlying(mFailOnReportAfterStage) >=
chip::to_underlying(chip::Controller::CommissioningStage::kWiFiNetworkSetup) ||
chip::to_underlying(mSimulateFailureOnStage) >=
chip::to_underlying(chip::Controller::CommissioningStage::kWiFiNetworkSetup))
{
// Pase should be open still
paseShouldBeOpen = true;
}
CommissioneeDeviceProxy * proxy;
bool paseIsOpen =
(chip::Controller::AutoCommissioner::GetCommissioner()->GetDeviceBeingCommissioned(nodeId, &proxy) == CHIP_NO_ERROR);
ChipLogProgress(Controller, "Checking pase connection state: Should be open? %d is open? %d", paseShouldBeOpen, paseIsOpen);
return paseShouldBeOpen == paseIsOpen;
}
void Reset()
{
mTestCommissionerUsed = false;
mReceivedCommissioningSuccess = false;
mReceivedCommissioningFailureStage = chip::Controller::CommissioningStage::kError;
for (size_t i = 0; i < kNumCommissioningStages; ++i)
{
mReceivedStageSuccess[i] = false;
mReceivedStageFailure[i] = false;
}
mSimulateFailureOnStage = chip::Controller::CommissioningStage::kError;
mFailOnReportAfterStage = chip::Controller::CommissioningStage::kError;
}
bool GetTestCommissionerUsed() { return mTestCommissionerUsed; }
void OnCommissioningSuccess(chip::PeerId peerId) { mReceivedCommissioningSuccess = true; }
void OnCommissioningFailure(chip::PeerId peerId, CHIP_ERROR error, chip::Controller::CommissioningStage stageFailed,
chip::Optional<chip::Credentials::AttestationVerificationResult> additionalErrorInfo)
{
mReceivedCommissioningFailureStage = stageFailed;
}
void OnCommissioningStatusUpdate(chip::PeerId peerId, chip::Controller::CommissioningStage stageCompleted, CHIP_ERROR error)
{
if (error == CHIP_NO_ERROR)
{
mReceivedStageSuccess[chip::to_underlying(stageCompleted)] = true;
}
else
{
mReceivedStageFailure[chip::to_underlying(stageCompleted)] = true;
}
}
private:
static constexpr uint8_t kNumCommissioningStages = chip::to_underlying(chip::Controller::CommissioningStage::kCleanup) + 1;
chip::Controller::CommissioningStage mSimulateFailureOnStage = chip::Controller::CommissioningStage::kError;
chip::Controller::CommissioningStage mFailOnReportAfterStage = chip::Controller::CommissioningStage::kError;
bool mTestCommissionerUsed = false;
bool mReceivedCommissioningSuccess = false;
chip::Controller::CommissioningStage mReceivedCommissioningFailureStage = chip::Controller::CommissioningStage::kError;
bool mReceivedStageSuccess[kNumCommissioningStages];
bool mReceivedStageFailure[kNumCommissioningStages];
bool mIsWifi = false;
bool mIsThread = false;
bool ValidStage(chip::Controller::CommissioningStage stage)
{
if (!mIsWifi &&
(stage == chip::Controller::CommissioningStage::kWiFiNetworkEnable ||
stage == chip::Controller::CommissioningStage::kWiFiNetworkSetup))
{
return false;
}
if (!mIsThread &&
(stage == chip::Controller::CommissioningStage::kThreadNetworkEnable ||
stage == chip::Controller::CommissioningStage::kThreadNetworkSetup))
{
return false;
}
if (stage == chip::Controller::CommissioningStage::kError || stage == chip::Controller::CommissioningStage::kSecurePairing)
{
return false;
}
return true;
}
bool StatusUpdatesOk(chip::Controller::CommissioningStage failedStage)
{
// Because we're just simulating a failure here, we will have received a success callback even for the failed stage.
for (uint8_t i = 0; i < kNumCommissioningStages; ++i)
{
if (mReceivedStageFailure[i])
{
return false;
}
if (!ValidStage(static_cast<chip::Controller::CommissioningStage>(i)))
{
continue;
}
// Anything above our current stage we won't have received a callback for. We also expect that the "failed" stage will
// have a success callback because we're just faking the failure here and overwriting error.
if (i == chip::to_underlying(failedStage))
{
break;
}
}
return true;
}
};
TestCommissioner sTestCommissioner;
extern "C" {
struct OpCredsContext
{
Platform::UniquePtr<Controller::Python::OperationalCredentialsAdapter> mAdapter;
void * mPyContext;
};
void * pychip_OpCreds_InitializeDelegate(void * pyContext, uint32_t fabricCredentialsIndex,
Controller::Python::StorageAdapter * storageAdapter)
{
auto context = Platform::MakeUnique<OpCredsContext>();
context->mAdapter = Platform::MakeUnique<Controller::Python::OperationalCredentialsAdapter>(fabricCredentialsIndex);
if (context->mAdapter->Initialize(*storageAdapter) != CHIP_NO_ERROR)
{
return nullptr;
}
return context.release();
}
void pychip_OnCommissioningSuccess(PeerId peerId)
{
sTestCommissioner.OnCommissioningSuccess(peerId);
}
void pychip_OnCommissioningFailure(chip::PeerId peerId, CHIP_ERROR error, chip::Controller::CommissioningStage stageFailed,
chip::Optional<chip::Credentials::AttestationVerificationResult> additionalErrorInfo)
{
sTestCommissioner.OnCommissioningFailure(peerId, error, stageFailed, additionalErrorInfo);
}
void pychip_OnCommissioningStatusUpdate(chip::PeerId peerId, chip::Controller::CommissioningStage stageCompleted, CHIP_ERROR err)
{
return sTestCommissioner.OnCommissioningStatusUpdate(peerId, stageCompleted, err);
}
ChipError::StorageType pychip_OpCreds_AllocateController(OpCredsContext * context,
chip::Controller::DeviceCommissioner ** outDevCtrl, FabricId fabricId,
chip::NodeId nodeId, chip::VendorId adminVendorId,
const char * paaTrustStorePath, bool useTestCommissioner,
bool enableServerInteractions, CASEAuthTag * caseAuthTags,
uint32_t caseAuthTagLen)
{
ChipLogDetail(Controller, "Creating New Device Controller");
VerifyOrReturnError(context != nullptr, CHIP_ERROR_INVALID_ARGUMENT.AsInteger());
auto devCtrl = std::make_unique<chip::Controller::DeviceCommissioner>();
VerifyOrReturnError(devCtrl != nullptr, CHIP_ERROR_NO_MEMORY.AsInteger());
if (paaTrustStorePath == nullptr)
{
paaTrustStorePath = "./credentials/development/paa-root-certs";
}
ChipLogProgress(Support, "Using device attestation PAA trust store path %s.", paaTrustStorePath);
// Initialize device attestation verifier
const chip::Credentials::AttestationTrustStore * testingRootStore = GetTestFileAttestationTrustStore(paaTrustStorePath);
SetDeviceAttestationVerifier(GetDefaultDACVerifier(testingRootStore));
chip::Crypto::P256Keypair ephemeralKey;
CHIP_ERROR err = ephemeralKey.Initialize();
VerifyOrReturnError(err == CHIP_NO_ERROR, err.AsInteger());
chip::Platform::ScopedMemoryBuffer<uint8_t> noc;
ReturnErrorCodeIf(!noc.Alloc(Controller::kMaxCHIPDERCertLength), CHIP_ERROR_NO_MEMORY.AsInteger());
MutableByteSpan nocSpan(noc.Get(), Controller::kMaxCHIPDERCertLength);
chip::Platform::ScopedMemoryBuffer<uint8_t> icac;
ReturnErrorCodeIf(!icac.Alloc(Controller::kMaxCHIPDERCertLength), CHIP_ERROR_NO_MEMORY.AsInteger());
MutableByteSpan icacSpan(icac.Get(), Controller::kMaxCHIPDERCertLength);
chip::Platform::ScopedMemoryBuffer<uint8_t> rcac;
ReturnErrorCodeIf(!rcac.Alloc(Controller::kMaxCHIPDERCertLength), CHIP_ERROR_NO_MEMORY.AsInteger());
MutableByteSpan rcacSpan(rcac.Get(), Controller::kMaxCHIPDERCertLength);
CATValues catValues;
if (caseAuthTagLen > kMaxSubjectCATAttributeCount)
{
ChipLogError(Controller, "Too many of CASE Tags (%u) exceeds kMaxSubjectCATAttributeCount",
static_cast<unsigned>(caseAuthTagLen));
return CHIP_ERROR_INVALID_ARGUMENT.AsInteger();
}
memcpy(catValues.values.data(), caseAuthTags, caseAuthTagLen * sizeof(CASEAuthTag));
err = context->mAdapter->GenerateNOCChain(nodeId, fabricId, catValues, ephemeralKey.Pubkey(), rcacSpan, icacSpan, nocSpan);
VerifyOrReturnError(err == CHIP_NO_ERROR, err.AsInteger());
Controller::SetupParams initParams;
initParams.pairingDelegate = &sPairingDelegate;
initParams.operationalCredentialsDelegate = context->mAdapter.get();
initParams.operationalKeypair = &ephemeralKey;
initParams.controllerRCAC = rcacSpan;
initParams.controllerICAC = icacSpan;
initParams.controllerNOC = nocSpan;
initParams.enableServerInteractions = enableServerInteractions;
initParams.controllerVendorId = adminVendorId;
initParams.permitMultiControllerFabrics = true;
if (useTestCommissioner)
{
initParams.defaultCommissioner = &sTestCommissioner;
sPairingDelegate.SetCommissioningSuccessCallback(pychip_OnCommissioningSuccess);
sPairingDelegate.SetCommissioningFailureCallback(pychip_OnCommissioningFailure);
sPairingDelegate.SetCommissioningStatusUpdateCallback(pychip_OnCommissioningStatusUpdate);
}
err = Controller::DeviceControllerFactory::GetInstance().SetupCommissioner(initParams, *devCtrl);
VerifyOrReturnError(err == CHIP_NO_ERROR, err.AsInteger());
// Setup IPK in Group Data Provider for controller after Commissioner init which sets-up the fabric table entry
uint8_t compressedFabricId[sizeof(uint64_t)] = { 0 };
chip::MutableByteSpan compressedFabricIdSpan(compressedFabricId);
err = devCtrl->GetCompressedFabricIdBytes(compressedFabricIdSpan);
VerifyOrReturnError(err == CHIP_NO_ERROR, err.AsInteger());
ChipLogProgress(Support, "Setting up group data for Fabric Index %u with Compressed Fabric ID:",
static_cast<unsigned>(devCtrl->GetFabricIndex()));
ChipLogByteSpan(Support, compressedFabricIdSpan);
chip::ByteSpan defaultIpk = chip::GroupTesting::DefaultIpkValue::GetDefaultIpk();
err =
chip::Credentials::SetSingleIpkEpochKey(&sGroupDataProvider, devCtrl->GetFabricIndex(), defaultIpk, compressedFabricIdSpan);
VerifyOrReturnError(err == CHIP_NO_ERROR, err.AsInteger());
*outDevCtrl = devCtrl.release();
return CHIP_NO_ERROR.AsInteger();
}
ChipError::StorageType pychip_OpCreds_SetMaximallyLargeCertsUsed(OpCredsContext * context, bool enabled)
{
VerifyOrReturnError(context != nullptr && context->mAdapter != nullptr, CHIP_ERROR_INCORRECT_STATE.AsInteger());
context->mAdapter->SetMaximallyLargeCertsUsed(enabled);
return CHIP_NO_ERROR.AsInteger();
}
void pychip_OpCreds_FreeDelegate(OpCredsContext * context)
{
Platform::Delete(context);
}
ChipError::StorageType pychip_DeviceController_DeleteDeviceController(chip::Controller::DeviceCommissioner * devCtrl)
{
if (devCtrl != nullptr)
{
devCtrl->Shutdown();
delete devCtrl;
}
return CHIP_NO_ERROR.AsInteger();
}
bool pychip_TestCommissionerUsed()
{
return sTestCommissioner.GetTestCommissionerUsed();
}
bool pychip_TestCommissioningCallbacks()
{
return sTestCommissioner.CheckCallbacks();
}
bool pychip_TestPaseConnection(NodeId nodeId)
{
return sTestCommissioner.CheckPaseConnection(nodeId);
}
void pychip_ResetCommissioningTests()
{
sTestCommissioner.Reset();
}
// Returns True if this is a valid test, false otherwise
bool pychip_SetTestCommissionerSimulateFailureOnStage(uint8_t failStage)
{
return sTestCommissioner.SimulateFailAfter(static_cast<chip::Controller::CommissioningStage>(failStage));
}
bool pychip_SetTestCommissionerSimulateFailureOnReport(uint8_t failStage)
{
return sTestCommissioner.SimulateFailOnReport(static_cast<chip::Controller::CommissioningStage>(failStage));
}
} // extern "C"