forked from project-chip/connectedhomeip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEfr32PsaOperationalKeystore.cpp
453 lines (371 loc) · 14.4 KB
/
Efr32PsaOperationalKeystore.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
/*
* Copyright (c) 2022 Project CHIP Authors
* 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 "Efr32PsaOperationalKeystore.h"
#include <crypto/OperationalKeystore.h>
#include <lib/core/CHIPError.h>
#include <lib/core/DataModelTypes.h>
#include <lib/core/TLV.h>
#include <lib/support/CHIPMem.h>
#include <lib/support/CodeUtils.h>
#include <lib/support/SafeInt.h>
#include "Efr32OpaqueKeypair.h"
#include <platform/silabs/SilabsConfig.h>
namespace chip {
namespace DeviceLayer {
namespace Internal {
static_assert((sizeof(FabricIndex) == 1), "Implementation is not prepared for large fabric indices");
static_assert(SL_MATTER_MAX_STORED_OP_KEYS <= (kEFR32OpaqueKeyIdPersistentMax - kEFR32OpaqueKeyIdPersistentMin),
"Not enough opaque keys available to cover all requested operational keys");
static_assert((CHIP_CONFIG_MAX_FABRICS + 1) <= SL_MATTER_MAX_STORED_OP_KEYS,
"Not enough operational keys requested to cover all potential fabrics (+1 staging for fabric update)");
static_assert(SL_MATTER_MAX_STORED_OP_KEYS >= 1, "Minimum supported amount of operational keys is 1");
using namespace chip::Crypto;
using chip::Platform::MemoryCalloc;
using chip::Platform::MemoryFree;
Efr32PsaOperationalKeystore::~Efr32PsaOperationalKeystore()
{
Deinit();
}
CHIP_ERROR Efr32PsaOperationalKeystore::Init()
{
// Detect existing keymap size
CHIP_ERROR error = CHIP_NO_ERROR;
size_t wantedLen = SL_MATTER_MAX_STORED_OP_KEYS * sizeof(FabricIndex);
size_t existingLen = 0;
bool update_cache = false;
if (SilabsConfig::ConfigValueExists(SilabsConfig::kConfigKey_OpKeyMap, existingLen))
{
// There's a pre-existing key map on disk. Size the map to read it fully.
size_t outLen = 0;
if (existingLen > (kEFR32OpaqueKeyIdPersistentMax - kEFR32OpaqueKeyIdPersistentMin) * sizeof(FabricIndex))
{
return CHIP_ERROR_INTERNAL;
}
// Upsize the map if the config was changed
if (existingLen < wantedLen)
{
existingLen = wantedLen;
}
mKeyMap = (FabricIndex *) MemoryCalloc(1, existingLen);
VerifyOrExit(mKeyMap, error = CHIP_ERROR_NO_MEMORY);
// Read the existing key map
error = SilabsConfig::ReadConfigValueBin(SilabsConfig::kConfigKey_OpKeyMap, (uint8_t *) mKeyMap, existingLen, outLen);
SuccessOrExit(error);
// If upsizing, extend the map with undefined indices
for (size_t i = (outLen / sizeof(FabricIndex)); i < (existingLen / sizeof(FabricIndex)); i++)
{
mKeyMap[i] = kUndefinedFabricIndex;
}
// If the config has changed, check whether it can be downsized fully or partially
if (existingLen > wantedLen)
{
size_t highest_found_index = 0;
for (size_t i = (wantedLen / sizeof(FabricIndex)); i < (existingLen / sizeof(FabricIndex)); i++)
{
if (mKeyMap[i] != kUndefinedFabricIndex)
{
highest_found_index = i;
}
}
// set size to the smallest that will fit the upper opaque key ID in use
if (highest_found_index > 0)
{
existingLen = (highest_found_index + 1) * sizeof(FabricIndex);
update_cache = true;
}
}
// Set the key map size
mKeyMapSize = existingLen;
}
else
{
// No key map on disk. Create and initialize a new one.
mKeyMap = (FabricIndex *) MemoryCalloc(1, wantedLen);
VerifyOrExit(mKeyMap, error = CHIP_ERROR_NO_MEMORY);
for (size_t i = 0; i < (wantedLen / sizeof(FabricIndex)); i++)
{
mKeyMap[i] = kUndefinedFabricIndex;
}
mKeyMapSize = wantedLen;
update_cache = true;
}
// Write-out keymap if needed
if (update_cache)
{
error = SilabsConfig::WriteConfigValueBin(SilabsConfig::kConfigKey_OpKeyMap, mKeyMap, mKeyMapSize);
SuccessOrExit(error);
}
// Initialize cache key
mCachedKey = Platform::New<EFR32OpaqueP256Keypair>();
VerifyOrExit(mCachedKey, error = CHIP_ERROR_NO_MEMORY);
exit:
if (error != CHIP_NO_ERROR)
{
Deinit();
return error;
}
mIsInitialized = true;
return CHIP_NO_ERROR;
}
EFR32OpaqueKeyId Efr32PsaOperationalKeystore::FindKeyIdForFabric(FabricIndex fabricIndex) const
{
// Search the map linearly to find a matching index slot
for (size_t i = 0; i < (mKeyMapSize / sizeof(FabricIndex)); i++)
{
if (mKeyMap[i] == fabricIndex)
{
// Found a match
return i + kEFR32OpaqueKeyIdPersistentMin;
}
}
return kEFR32OpaqueKeyIdUnknown;
}
bool Efr32PsaOperationalKeystore::HasOpKeypairForFabric(FabricIndex fabricIndex) const
{
VerifyOrReturnError(mIsInitialized, false);
VerifyOrReturnError(IsValidFabricIndex(fabricIndex), false);
// If there was a pending keypair, then there's really a usable key
if (mIsPendingKeypairActive && (fabricIndex == mPendingFabricIndex) && (mPendingKeypair != nullptr))
{
return true;
}
// Check whether we have a match in the map
if (FindKeyIdForFabric(fabricIndex) != kEFR32OpaqueKeyIdUnknown)
{
return true;
}
return false;
}
CHIP_ERROR Efr32PsaOperationalKeystore::NewOpKeypairForFabric(FabricIndex fabricIndex,
MutableByteSpan & outCertificateSigningRequest)
{
CHIP_ERROR error = CHIP_NO_ERROR;
VerifyOrReturnError(mIsInitialized, CHIP_ERROR_UNINITIALIZED);
VerifyOrReturnError(IsValidFabricIndex(fabricIndex), CHIP_ERROR_INVALID_FABRIC_INDEX);
// If a key is pending, we cannot generate for a different fabric index until we commit or revert.
if ((mPendingFabricIndex != kUndefinedFabricIndex) && (fabricIndex != mPendingFabricIndex))
{
return CHIP_ERROR_INVALID_FABRIC_INDEX;
}
VerifyOrReturnError(outCertificateSigningRequest.size() >= Crypto::kMIN_CSR_Buffer_Size, CHIP_ERROR_BUFFER_TOO_SMALL);
// Generate new key
EFR32OpaqueKeyId id = kEFR32OpaqueKeyIdUnknown;
if (mPendingFabricIndex != kUndefinedFabricIndex)
{
// If we already have a pending key, delete it and put a new one in its place
id = mPendingKeypair->GetKeyId();
if (id == kEFR32OpaqueKeyIdUnknown)
{
ResetPendingKey();
}
else
{
mPendingKeypair->DestroyKey();
if (id == kEFR32OpaqueKeyIdVolatile)
{
id = kEFR32OpaqueKeyIdUnknown;
}
}
}
if (id == kEFR32OpaqueKeyIdUnknown)
{
// Try to find an available opaque ID in the map
id = FindKeyIdForFabric(kUndefinedFabricIndex);
if (!mPendingKeypair)
{
mPendingKeypair = Platform::New<EFR32OpaqueP256Keypair>();
}
}
if (id == kEFR32OpaqueKeyIdUnknown)
{
// Could not find a free spot in the map
return CHIP_ERROR_NO_MEMORY;
}
// Create new key on the old or found key ID
error = mPendingKeypair->Create(id, EFR32OpaqueKeyUsages::ECDSA_P256_SHA256);
if (error != CHIP_NO_ERROR)
{
ResetPendingKey();
return error;
}
// Set CSR and state
size_t csrLength = outCertificateSigningRequest.size();
error = mPendingKeypair->NewCertificateSigningRequest(outCertificateSigningRequest.data(), csrLength);
if (error != CHIP_NO_ERROR)
{
ResetPendingKey();
return error;
}
outCertificateSigningRequest.reduce_size(csrLength);
mPendingFabricIndex = fabricIndex;
return CHIP_NO_ERROR;
}
CHIP_ERROR Efr32PsaOperationalKeystore::ActivateOpKeypairForFabric(FabricIndex fabricIndex,
const Crypto::P256PublicKey & nocPublicKey)
{
VerifyOrReturnError(mIsInitialized, CHIP_ERROR_UNINITIALIZED);
VerifyOrReturnError(mPendingKeypair != nullptr, CHIP_ERROR_INVALID_FABRIC_INDEX);
VerifyOrReturnError(IsValidFabricIndex(fabricIndex) && (fabricIndex == mPendingFabricIndex), CHIP_ERROR_INVALID_FABRIC_INDEX);
// Validate public key being activated matches last generated pending keypair
VerifyOrReturnError(mPendingKeypair->Pubkey().Matches(nocPublicKey), CHIP_ERROR_INVALID_PUBLIC_KEY);
mIsPendingKeypairActive = true;
return CHIP_NO_ERROR;
}
CHIP_ERROR Efr32PsaOperationalKeystore::CommitOpKeypairForFabric(FabricIndex fabricIndex)
{
VerifyOrReturnError(mIsInitialized, CHIP_ERROR_UNINITIALIZED);
VerifyOrReturnError(mPendingKeypair != nullptr, CHIP_ERROR_INVALID_FABRIC_INDEX);
VerifyOrReturnError(IsValidFabricIndex(fabricIndex) && (fabricIndex == mPendingFabricIndex), CHIP_ERROR_INVALID_FABRIC_INDEX);
VerifyOrReturnError(mIsPendingKeypairActive == true, CHIP_ERROR_INCORRECT_STATE);
// Add key association to key map
EFR32OpaqueKeyId id = mPendingKeypair->GetKeyId();
if (id == kEFR32OpaqueKeyIdUnknown || id == kEFR32OpaqueKeyIdVolatile)
{
ResetPendingKey();
return CHIP_ERROR_INTERNAL;
}
// Guard against array out-of-bounds (should not happen with correctly initialised keys)
size_t keymap_index = id - kEFR32OpaqueKeyIdPersistentMin;
if (keymap_index >= (mKeyMapSize / sizeof(FabricIndex)))
{
return CHIP_ERROR_INTERNAL;
}
if (mKeyMap[keymap_index] != kUndefinedFabricIndex)
{
ResetPendingKey();
return CHIP_ERROR_INTERNAL;
}
mKeyMap[keymap_index] = fabricIndex;
// Persist key map
CHIP_ERROR error = SilabsConfig::WriteConfigValueBin(SilabsConfig::kConfigKey_OpKeyMap, mKeyMap, mKeyMapSize);
if (error != CHIP_NO_ERROR)
{
return error;
}
// There's a good chance we'll need the key again soon
mCachedKey->Load(id);
ResetPendingKey(true /* keepKeyPairInStorage */);
return CHIP_NO_ERROR;
}
CHIP_ERROR Efr32PsaOperationalKeystore::RemoveOpKeypairForFabric(FabricIndex fabricIndex)
{
VerifyOrReturnError(mIsInitialized, CHIP_ERROR_UNINITIALIZED);
VerifyOrReturnError(IsValidFabricIndex(fabricIndex), CHIP_ERROR_INVALID_FABRIC_INDEX);
// Remove pending keypair if we have it and the fabric ID matches
if ((mPendingKeypair != nullptr) && (fabricIndex == mPendingFabricIndex))
{
RevertPendingKeypair();
}
EFR32OpaqueKeyId id = FindKeyIdForFabric(fabricIndex);
if (id == kEFR32OpaqueKeyIdUnknown)
{
// Fabric is not in the map, so assume it's gone already
return CHIP_NO_ERROR;
}
// Guard against array out-of-bounds (should not happen with correctly initialised keys)
size_t keymap_index = id - kEFR32OpaqueKeyIdPersistentMin;
if (keymap_index >= (mKeyMapSize / sizeof(FabricIndex)))
{
return CHIP_ERROR_INTERNAL;
}
// Reset the key mapping since we'll be deleting this key
mKeyMap[keymap_index] = kUndefinedFabricIndex;
// Persist key map
CHIP_ERROR error = SilabsConfig::WriteConfigValueBin(SilabsConfig::kConfigKey_OpKeyMap, mKeyMap, mKeyMapSize);
if (error != CHIP_NO_ERROR)
{
return error;
}
// Check if key is cached
EFR32OpaqueKeyId cachedId = mCachedKey->GetKeyId();
if (id == cachedId)
{
// Delete from persistent storage and unload
mCachedKey->DestroyKey();
return CHIP_NO_ERROR;
}
// Load it for purposes of deletion
error = mCachedKey->Load(id);
if (error != CHIP_NO_ERROR && error != CHIP_DEVICE_ERROR_CONFIG_NOT_FOUND)
{
return CHIP_ERROR_INTERNAL;
}
mCachedKey->DestroyKey();
return CHIP_NO_ERROR;
}
void Efr32PsaOperationalKeystore::RevertPendingKeypair()
{
if (mIsInitialized)
{
// Just delete the pending key from storage
ResetPendingKey();
}
}
CHIP_ERROR Efr32PsaOperationalKeystore::SignWithOpKeypair(FabricIndex fabricIndex, const ByteSpan & message,
Crypto::P256ECDSASignature & outSignature) const
{
VerifyOrReturnError(mIsInitialized, CHIP_ERROR_UNINITIALIZED);
VerifyOrReturnError(IsValidFabricIndex(fabricIndex), CHIP_ERROR_INVALID_FABRIC_INDEX);
// Check to see whether the key is an activated pending key
if (mIsPendingKeypairActive && (fabricIndex == mPendingFabricIndex))
{
VerifyOrReturnError(mPendingKeypair != nullptr, CHIP_ERROR_INTERNAL);
return mPendingKeypair->ECDSA_sign_msg(message.data(), message.size(), outSignature);
}
// Figure out which key ID we're looking for
EFR32OpaqueKeyId id = FindKeyIdForFabric(fabricIndex);
if (id == kEFR32OpaqueKeyIdUnknown)
{
// Fabric is not in the map, but the caller thinks it's there?
return CHIP_ERROR_INTERNAL;
}
// Check whether we have the key in cache
EFR32OpaqueKeyId cachedId = mCachedKey->GetKeyId();
if (id == cachedId)
{
return mCachedKey->ECDSA_sign_msg(message.data(), message.size(), outSignature);
}
// If not, we need to recreate from the backend
CHIP_ERROR error = mCachedKey->Load(id);
if (error != CHIP_NO_ERROR)
{
return CHIP_ERROR_INTERNAL;
}
// Sign with retrieved key
error = mCachedKey->ECDSA_sign_msg(message.data(), message.size(), outSignature);
if (error != CHIP_NO_ERROR)
{
return CHIP_ERROR_INTERNAL;
}
return CHIP_NO_ERROR;
}
Crypto::P256Keypair * Efr32PsaOperationalKeystore::AllocateEphemeralKeypairForCASE()
{
EFR32OpaqueP256Keypair * new_key = Platform::New<EFR32OpaqueP256Keypair>();
if (new_key != nullptr)
{
new_key->Create(kEFR32OpaqueKeyIdVolatile, EFR32OpaqueKeyUsages::ECDH_P256);
}
return new_key;
}
void Efr32PsaOperationalKeystore::ReleaseEphemeralKeypair(Crypto::P256Keypair * keypair)
{
Platform::Delete<EFR32OpaqueP256Keypair>((EFR32OpaqueP256Keypair *) keypair);
}
} // namespace Internal
} // namespace DeviceLayer
} // namespace chip