Skip to content
0.2.0-dev Download ZIP
998 lines ·35.3 KB Raw
1/*
2 * PSA crypto layer on top of Mbed TLS crypto
3 */
4/*
5 * Copyright The Mbed TLS Contributors
6 * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
7 */
8
9#include "tf_psa_crypto_common.h"
10
11#if defined(MBEDTLS_PSA_CRYPTO_C)
12
13#include "psa/crypto.h"
14
15#include "psa_crypto_core.h"
16#include "psa_crypto_driver_wrappers_no_static.h"
17#include "psa_crypto_slot_management.h"
18#include "psa_crypto_storage.h"
19
20#include <stdlib.h>
21#include <string.h>
22#include "mbedtls/platform.h"
23#if defined(MBEDTLS_THREADING_C)
24#include "mbedtls/threading.h"
25#include "threading_internal.h"
26#endif
27
28
29
30/* Make sure we have distinct ranges of key identifiers for distinct
31 * purposes. */
32MBEDTLS_STATIC_ASSERT(PSA_KEY_ID_USER_MIN < PSA_KEY_ID_USER_MAX,
33 "Empty user key ID range");
34MBEDTLS_STATIC_ASSERT(PSA_KEY_ID_VENDOR_MIN < PSA_KEY_ID_VENDOR_MAX,
35 "Empty vendor key ID range");
36MBEDTLS_STATIC_ASSERT(MBEDTLS_PSA_KEY_ID_BUILTIN_MIN <= MBEDTLS_PSA_KEY_ID_BUILTIN_MAX,
37 "Empty builtin key ID range");
38MBEDTLS_STATIC_ASSERT(PSA_KEY_ID_VOLATILE_MIN <= PSA_KEY_ID_VOLATILE_MAX,
39 "Empty volatile key ID range");
40
41MBEDTLS_STATIC_ASSERT(PSA_KEY_ID_USER_MAX < PSA_KEY_ID_VENDOR_MIN ||
42 PSA_KEY_ID_VENDOR_MAX < PSA_KEY_ID_USER_MIN,
43 "Overlap between user key IDs and vendor key IDs");
44
45MBEDTLS_STATIC_ASSERT(PSA_KEY_ID_VENDOR_MIN <= MBEDTLS_PSA_KEY_ID_BUILTIN_MIN &&
46 MBEDTLS_PSA_KEY_ID_BUILTIN_MAX <= PSA_KEY_ID_VENDOR_MAX,
47 "Builtin key identifiers are not in the vendor range");
48
49MBEDTLS_STATIC_ASSERT(PSA_KEY_ID_VENDOR_MIN <= PSA_KEY_ID_VOLATILE_MIN &&
50 PSA_KEY_ID_VOLATILE_MAX <= PSA_KEY_ID_VENDOR_MAX,
51 "Volatile key identifiers are not in the vendor range");
52
53MBEDTLS_STATIC_ASSERT(PSA_KEY_ID_VOLATILE_MAX < MBEDTLS_PSA_KEY_ID_BUILTIN_MIN ||
54 MBEDTLS_PSA_KEY_ID_BUILTIN_MAX < PSA_KEY_ID_VOLATILE_MIN,
55 "Overlap between builtin key IDs and volatile key IDs");
56
57
58
59#if defined(MBEDTLS_PSA_KEY_STORE_DYNAMIC)
60
61/* Dynamic key store.
62 *
63 * The key store consists of multiple slices.
64 *
65 * The volatile keys are stored in variable-sized tables called slices.
66 * Slices are allocated on demand and deallocated when possible.
67 * The size of slices increases exponentially, so the average overhead
68 * (number of slots that are allocated but not used) is roughly
69 * proportional to the number of keys (with a factor that grows
70 * when the key store is fragmented).
71 *
72 * One slice is dedicated to the cache of persistent and built-in keys.
73 * For simplicity, they are separated from volatile keys. This cache
74 * slice has a fixed size and has the slice index KEY_SLOT_CACHE_SLICE_INDEX,
75 * located after the slices for volatile keys.
76 */
77
78/* Size of the last slice containing the cache of persistent and built-in keys. */
79#define PERSISTENT_KEY_CACHE_COUNT MBEDTLS_PSA_KEY_SLOT_COUNT
80
81/* Volatile keys are stored in slices 0 through
82 * (KEY_SLOT_VOLATILE_SLICE_COUNT - 1) inclusive.
83 * Each slice is twice the size of the previous slice.
84 * Volatile key identifiers encode the slice number as follows:
85 * bits 30..31: 0b10 (mandated by the PSA Crypto specification).
86 * bits 25..29: slice index (0...KEY_SLOT_VOLATILE_SLICE_COUNT-1)
87 * bits 0..24: slot index in slice
88 */
89#define KEY_ID_SLOT_INDEX_WIDTH 25u
90#define KEY_ID_SLICE_INDEX_WIDTH 5u
91
92#define KEY_SLOT_VOLATILE_SLICE_BASE_LENGTH 16u
93#define KEY_SLOT_VOLATILE_SLICE_COUNT 22u
94#define KEY_SLICE_COUNT (KEY_SLOT_VOLATILE_SLICE_COUNT + 1u)
95#define KEY_SLOT_CACHE_SLICE_INDEX KEY_SLOT_VOLATILE_SLICE_COUNT
96
97
98/* Check that the length of the largest slice (calculated as
99 * KEY_SLICE_LENGTH_MAX below) does not overflow size_t. We use
100 * an indirect method in case the calculation of KEY_SLICE_LENGTH_MAX
101 * itself overflows uintmax_t: if (BASE_LENGTH << c)
102 * overflows size_t then BASE_LENGTH > SIZE_MAX >> c.
103 */
104#if (KEY_SLOT_VOLATILE_SLICE_BASE_LENGTH > \
105 SIZE_MAX >> (KEY_SLOT_VOLATILE_SLICE_COUNT - 1))
106#error "Maximum slice length overflows size_t"
107#endif
108
109#if KEY_ID_SLICE_INDEX_WIDTH + KEY_ID_SLOT_INDEX_WIDTH > 30
110#error "Not enough room in volatile key IDs for slice index and slot index"
111#endif
112#if KEY_SLOT_VOLATILE_SLICE_COUNT > (1 << KEY_ID_SLICE_INDEX_WIDTH)
113#error "Too many slices to fit the slice index in a volatile key ID"
114#endif
115#define KEY_SLICE_LENGTH_MAX \
116 (KEY_SLOT_VOLATILE_SLICE_BASE_LENGTH << (KEY_SLOT_VOLATILE_SLICE_COUNT - 1))
117#if KEY_SLICE_LENGTH_MAX > 1 << KEY_ID_SLOT_INDEX_WIDTH
118#error "Not enough room in volatile key IDs for a slot index in the largest slice"
119#endif
120#if KEY_ID_SLICE_INDEX_WIDTH > 8
121#error "Slice index does not fit in uint8_t for psa_key_slot_t::slice_index"
122#endif
123
124
125/* Calculate the volatile key id to use for a given slot.
126 * This function assumes valid parameter values. */
127static psa_key_id_t volatile_key_id_of_index(size_t slice_idx,
128 size_t slot_idx)
129{
130 /* We assert above that the slice and slot indexes fit in separate
131 * bit-fields inside psa_key_id_t, which is a 32-bit type per the
132 * PSA Cryptography specification. */
133 return (psa_key_id_t) (0x40000000u |
134 (slice_idx << KEY_ID_SLOT_INDEX_WIDTH) |
135 slot_idx);
136}
137
138/* Calculate the slice containing the given volatile key.
139 * This function assumes valid parameter values. */
140static size_t slice_index_of_volatile_key_id(psa_key_id_t key_id)
141{
142 size_t mask = (1LU << KEY_ID_SLICE_INDEX_WIDTH) - 1;
143 return (key_id >> KEY_ID_SLOT_INDEX_WIDTH) & mask;
144}
145
146/* Calculate the index of the slot containing the given volatile key.
147 * This function assumes valid parameter values. */
148static size_t slot_index_of_volatile_key_id(psa_key_id_t key_id)
149{
150 return key_id & ((1LU << KEY_ID_SLOT_INDEX_WIDTH) - 1);
151}
152
153/* In global_data.first_free_slot_index, use this special value to
154 * indicate that the slice is full. */
155#define FREE_SLOT_INDEX_NONE ((size_t) -1)
156
157#if defined(MBEDTLS_TEST_HOOKS)
158size_t psa_key_slot_volatile_slice_count(void)
159{
160 return KEY_SLOT_VOLATILE_SLICE_COUNT;
161}
162#endif
163
164#else /* MBEDTLS_PSA_KEY_STORE_DYNAMIC */
165
166/* Static key store.
167 *
168 * All the keys (volatile or persistent) are in a single slice.
169 * We only use slices as a concept to allow some differences between
170 * static and dynamic key store management to be buried in auxiliary
171 * functions.
172 */
173
174#define PERSISTENT_KEY_CACHE_COUNT MBEDTLS_PSA_KEY_SLOT_COUNT
175#define KEY_SLICE_COUNT 1u
176#define KEY_SLOT_CACHE_SLICE_INDEX 0
177
178#endif /* MBEDTLS_PSA_KEY_STORE_DYNAMIC */
179
180
181typedef struct {
182#if defined(MBEDTLS_PSA_KEY_STORE_DYNAMIC)
183 psa_key_slot_t *key_slices[KEY_SLICE_COUNT];
184 size_t first_free_slot_index[KEY_SLOT_VOLATILE_SLICE_COUNT];
185#else /* MBEDTLS_PSA_KEY_STORE_DYNAMIC */
186 psa_key_slot_t key_slots[MBEDTLS_PSA_KEY_SLOT_COUNT];
187#endif /* MBEDTLS_PSA_KEY_STORE_DYNAMIC */
188 uint8_t key_slots_initialized;
189} psa_global_data_t;
190
191static psa_global_data_t global_data;
192
193static uint8_t psa_get_key_slots_initialized(void)
194{
195 uint8_t initialized;
196
197#if defined(MBEDTLS_THREADING_C)
198 mbedtls_mutex_lock(&mbedtls_threading_psa_globaldata_mutex);
199#endif /* defined(MBEDTLS_THREADING_C) */
200
201 initialized = global_data.key_slots_initialized;
202
203#if defined(MBEDTLS_THREADING_C)
204 mbedtls_mutex_unlock(&mbedtls_threading_psa_globaldata_mutex);
205#endif /* defined(MBEDTLS_THREADING_C) */
206
207 return initialized;
208}
209
210
211
212/** The length of the given slice in the key slot table.
213 *
214 * \param slice_idx The slice number. It must satisfy
215 * 0 <= slice_idx < KEY_SLICE_COUNT.
216 *
217 * \return The number of elements in the given slice.
218 */
219static inline size_t key_slice_length(size_t slice_idx);
220
221/** Get a pointer to the slot where the given volatile key is located.
222 *
223 * \param key_id The key identifier. It must be a valid volatile key
224 * identifier.
225 * \return A pointer to the only slot that the given key
226 * can be in. Note that the slot may be empty or
227 * contain a different key.
228 */
229static inline psa_key_slot_t *get_volatile_key_slot(psa_key_id_t key_id);
230
231/** Get a pointer to an entry in the persistent key cache.
232 *
233 * \param slot_idx The index in the table. It must satisfy
234 * 0 <= slot_idx < PERSISTENT_KEY_CACHE_COUNT.
235 * \return A pointer to the slot containing the given
236 * persistent key cache entry.
237 */
238static inline psa_key_slot_t *get_persistent_key_slot(size_t slot_idx);
239
240/** Get a pointer to a slot given by slice and index.
241 *
242 * \param slice_idx The slice number. It must satisfy
243 * 0 <= slice_idx < KEY_SLICE_COUNT.
244 * \param slot_idx An index in the given slice. It must satisfy
245 * 0 <= slot_idx < key_slice_length(slice_idx).
246 *
247 * \return A pointer to the given slot.
248 */
249static inline psa_key_slot_t *get_key_slot(size_t slice_idx, size_t slot_idx);
250
251#if defined(MBEDTLS_PSA_KEY_STORE_DYNAMIC)
252
253#if defined(MBEDTLS_TEST_HOOKS)
254size_t (*mbedtls_test_hook_psa_volatile_key_slice_length)(size_t slice_idx) = NULL;
255#endif
256
257static inline size_t key_slice_length(size_t slice_idx)
258{
259 if (slice_idx == KEY_SLOT_CACHE_SLICE_INDEX) {
260 return PERSISTENT_KEY_CACHE_COUNT;
261 } else {
262#if defined(MBEDTLS_TEST_HOOKS)
263 if (mbedtls_test_hook_psa_volatile_key_slice_length != NULL) {
264 return mbedtls_test_hook_psa_volatile_key_slice_length(slice_idx);
265 }
266#endif
267 return KEY_SLOT_VOLATILE_SLICE_BASE_LENGTH << slice_idx;
268 }
269}
270
271static inline psa_key_slot_t *get_volatile_key_slot(psa_key_id_t key_id)
272{
273 size_t slice_idx = slice_index_of_volatile_key_id(key_id);
274 if (slice_idx >= KEY_SLOT_VOLATILE_SLICE_COUNT) {
275 return NULL;
276 }
277 size_t slot_idx = slot_index_of_volatile_key_id(key_id);
278 if (slot_idx >= key_slice_length(slice_idx)) {
279 return NULL;
280 }
281 psa_key_slot_t *slice = global_data.key_slices[slice_idx];
282 if (slice == NULL) {
283 return NULL;
284 }
285 return &slice[slot_idx];
286}
287
288static inline psa_key_slot_t *get_persistent_key_slot(size_t slot_idx)
289{
290 return &global_data.key_slices[KEY_SLOT_CACHE_SLICE_INDEX][slot_idx];
291}
292
293static inline psa_key_slot_t *get_key_slot(size_t slice_idx, size_t slot_idx)
294{
295 return &global_data.key_slices[slice_idx][slot_idx];
296}
297
298#else /* MBEDTLS_PSA_KEY_STORE_DYNAMIC */
299
300static inline size_t key_slice_length(size_t slice_idx)
301{
302 (void) slice_idx;
303 return ARRAY_LENGTH(global_data.key_slots);
304}
305
306static inline psa_key_slot_t *get_volatile_key_slot(psa_key_id_t key_id)
307{
308 MBEDTLS_STATIC_ASSERT(ARRAY_LENGTH(global_data.key_slots) <=
309 PSA_KEY_ID_VOLATILE_MAX - PSA_KEY_ID_VOLATILE_MIN + 1,
310 "The key slot array is larger than the volatile key ID range");
311 return &global_data.key_slots[key_id - PSA_KEY_ID_VOLATILE_MIN];
312}
313
314static inline psa_key_slot_t *get_persistent_key_slot(size_t slot_idx)
315{
316 return &global_data.key_slots[slot_idx];
317}
318
319static inline psa_key_slot_t *get_key_slot(size_t slice_idx, size_t slot_idx)
320{
321 (void) slice_idx;
322 return &global_data.key_slots[slot_idx];
323}
324
325#endif /* MBEDTLS_PSA_KEY_STORE_DYNAMIC */
326
327/** Get the description in memory of a key given its identifier and lock it.
328 *
329 * The descriptions of volatile keys and loaded persistent keys are
330 * stored in key slots. This function returns a pointer to the key slot
331 * containing the description of a key given its identifier.
332 *
333 * The function searches the key slots containing the description of the key
334 * with \p key identifier. The function does only read accesses to the key
335 * slots. The function does not load any persistent key thus does not access
336 * any storage.
337 *
338 * For volatile key identifiers, only one key slot is queried as a volatile
339 * key with identifier key_id can only be stored in slot of index
340 * ( key_id - #PSA_KEY_ID_VOLATILE_MIN ).
341 *
342 * On success, the function locks the key slot. It is the responsibility of
343 * the caller to unlock the key slot when it does not access it anymore.
344 *
345 * If multi-threading is enabled, the caller must hold the
346 * global key slot mutex.
347 *
348 * \param key Key identifier to query.
349 * \param[out] p_slot On success, `*p_slot` contains a pointer to the
350 * key slot containing the description of the key
351 * identified by \p key.
352 *
353 * \retval #PSA_SUCCESS
354 * The pointer to the key slot containing the description of the key
355 * identified by \p key was returned.
356 * \retval #PSA_ERROR_INVALID_HANDLE
357 * \p key is not a valid key identifier.
358 * \retval #PSA_ERROR_DOES_NOT_EXIST
359 * There is no key with key identifier \p key in the key slots.
360 */
361static psa_status_t psa_get_and_lock_key_slot_in_memory(
362 mbedtls_svc_key_id_t key, psa_key_slot_t **p_slot)
363{
364 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
365 psa_key_id_t key_id = MBEDTLS_SVC_KEY_ID_GET_KEY_ID(key);
366 size_t slot_idx;
367 psa_key_slot_t *slot = NULL;
368
369 if (psa_key_id_is_volatile(key_id)) {
370 slot = get_volatile_key_slot(key_id);
371
372 /* Check if both the PSA key identifier key_id and the owner
373 * identifier of key match those of the key slot. */
374 if (slot != NULL &&
375 slot->state == PSA_SLOT_FULL &&
376 mbedtls_svc_key_id_equal(key, slot->attr.id)) {
377 status = PSA_SUCCESS;
378 } else {
379 status = PSA_ERROR_DOES_NOT_EXIST;
380 }
381 } else if (psa_key_id_is_user(key_id) || psa_key_id_is_builtin(key_id)) {
382 for (slot_idx = 0; slot_idx < PERSISTENT_KEY_CACHE_COUNT; slot_idx++) {
383 slot = get_persistent_key_slot(slot_idx);
384 /* Only consider slots which are in a full state. */
385 if ((slot->state == PSA_SLOT_FULL) &&
386 (mbedtls_svc_key_id_equal(key, slot->attr.id))) {
387 break;
388 }
389 }
390 status = (slot_idx < MBEDTLS_PSA_KEY_SLOT_COUNT) ?
391 PSA_SUCCESS : PSA_ERROR_DOES_NOT_EXIST;
392 } else {
393 return PSA_ERROR_INVALID_HANDLE;
394 }
395
396 if (status == PSA_SUCCESS) {
397 status = psa_register_read(slot);
398 if (status == PSA_SUCCESS) {
399 *p_slot = slot;
400 }
401 }
402
403 return status;
404}
405
406psa_status_t psa_initialize_key_slots(void)
407{
408#if defined(MBEDTLS_PSA_KEY_STORE_DYNAMIC)
409 global_data.key_slices[KEY_SLOT_CACHE_SLICE_INDEX] =
410 mbedtls_calloc(PERSISTENT_KEY_CACHE_COUNT,
411 sizeof(*global_data.key_slices[KEY_SLOT_CACHE_SLICE_INDEX]));
412 if (global_data.key_slices[KEY_SLOT_CACHE_SLICE_INDEX] == NULL) {
413 return PSA_ERROR_INSUFFICIENT_MEMORY;
414 }
415#else /* MBEDTLS_PSA_KEY_STORE_DYNAMIC */
416 /* Nothing to do: program startup and psa_wipe_all_key_slots() both
417 * guarantee that the key slots are initialized to all-zero, which
418 * means that all the key slots are in a valid, empty state. The global
419 * data mutex is already held when calling this function, so no need to
420 * lock it here, to set the flag. */
421#endif /* MBEDTLS_PSA_KEY_STORE_DYNAMIC */
422
423 global_data.key_slots_initialized = 1;
424 return PSA_SUCCESS;
425}
426
427void psa_wipe_all_key_slots(void)
428{
429 for (size_t slice_idx = 0; slice_idx < KEY_SLICE_COUNT; slice_idx++) {
430#if defined(MBEDTLS_PSA_KEY_STORE_DYNAMIC)
431 if (global_data.key_slices[slice_idx] == NULL) {
432 continue;
433 }
434#endif /* MBEDTLS_PSA_KEY_STORE_DYNAMIC */
435 for (size_t slot_idx = 0; slot_idx < key_slice_length(slice_idx); slot_idx++) {
436 psa_key_slot_t *slot = get_key_slot(slice_idx, slot_idx);
437#if defined(MBEDTLS_PSA_KEY_STORE_DYNAMIC)
438 /* When MBEDTLS_PSA_KEY_STORE_DYNAMIC is disabled, calling
439 * psa_wipe_key_slot() on an unused slot is useless, but it
440 * happens to work (because we flip the state to PENDING_DELETION).
441 *
442 * When MBEDTLS_PSA_KEY_STORE_DYNAMIC is enabled,
443 * psa_wipe_key_slot() needs to have a valid slice_index
444 * field, but that value might not be correct in a
445 * free slot, so we must not call it.
446 *
447 * Bypass the call to psa_wipe_key_slot() if the slot is empty,
448 * but only if MBEDTLS_PSA_KEY_STORE_DYNAMIC is enabled, to save
449 * a few bytes of code size otherwise.
450 */
451 if (slot->state == PSA_SLOT_EMPTY) {
452 continue;
453 }
454#endif
455 slot->var.occupied.registered_readers = 1;
456 slot->state = PSA_SLOT_PENDING_DELETION;
457 (void) psa_wipe_key_slot(slot);
458 }
459#if defined(MBEDTLS_PSA_KEY_STORE_DYNAMIC)
460 mbedtls_free(global_data.key_slices[slice_idx]);
461 global_data.key_slices[slice_idx] = NULL;
462#endif /* MBEDTLS_PSA_KEY_STORE_DYNAMIC */
463 }
464
465#if defined(MBEDTLS_PSA_KEY_STORE_DYNAMIC)
466 for (size_t slice_idx = 0; slice_idx < KEY_SLOT_VOLATILE_SLICE_COUNT; slice_idx++) {
467 global_data.first_free_slot_index[slice_idx] = 0;
468 }
469#endif /* MBEDTLS_PSA_KEY_STORE_DYNAMIC */
470
471 /* The global data mutex is already held when calling this function. */
472 global_data.key_slots_initialized = 0;
473}
474
475#if defined(MBEDTLS_PSA_KEY_STORE_DYNAMIC)
476
477static psa_status_t psa_allocate_volatile_key_slot(psa_key_id_t *key_id,
478 psa_key_slot_t **p_slot)
479{
480 size_t slice_idx;
481 for (slice_idx = 0; slice_idx < KEY_SLOT_VOLATILE_SLICE_COUNT; slice_idx++) {
482 if (global_data.first_free_slot_index[slice_idx] != FREE_SLOT_INDEX_NONE) {
483 break;
484 }
485 }
486 if (slice_idx == KEY_SLOT_VOLATILE_SLICE_COUNT) {
487 return PSA_ERROR_INSUFFICIENT_MEMORY;
488 }
489
490 if (global_data.key_slices[slice_idx] == NULL) {
491 global_data.key_slices[slice_idx] =
492 mbedtls_calloc(key_slice_length(slice_idx),
493 sizeof(psa_key_slot_t));
494 if (global_data.key_slices[slice_idx] == NULL) {
495 return PSA_ERROR_INSUFFICIENT_MEMORY;
496 }
497 }
498 psa_key_slot_t *slice = global_data.key_slices[slice_idx];
499
500 size_t slot_idx = global_data.first_free_slot_index[slice_idx];
501 *key_id = volatile_key_id_of_index(slice_idx, slot_idx);
502
503 psa_key_slot_t *slot = &slice[slot_idx];
504 size_t next_free = slot_idx + 1 + slot->var.free.next_free_relative_to_next;
505 if (next_free >= key_slice_length(slice_idx)) {
506 next_free = FREE_SLOT_INDEX_NONE;
507 }
508 global_data.first_free_slot_index[slice_idx] = next_free;
509 /* The .next_free field is not meaningful when the slot is not free,
510 * so give it the same content as freshly initialized memory. */
511 slot->var.free.next_free_relative_to_next = 0;
512
513 psa_status_t status = psa_key_slot_state_transition(slot,
514 PSA_SLOT_EMPTY,
515 PSA_SLOT_FILLING);
516 if (status != PSA_SUCCESS) {
517 /* The only reason for failure is if the slot state was not empty.
518 * This indicates that something has gone horribly wrong.
519 * In this case, we leave the slot out of the free list, and stop
520 * modifying it. This minimizes any further corruption. The slot
521 * is a memory leak, but that's a lesser evil. */
522 return status;
523 }
524
525 *p_slot = slot;
526 /* We assert at compile time that the slice index fits in uint8_t. */
527 slot->slice_index = (uint8_t) slice_idx;
528 return PSA_SUCCESS;
529}
530
531psa_status_t psa_free_key_slot(size_t slice_idx,
532 psa_key_slot_t *slot)
533{
534
535 if (slice_idx == KEY_SLOT_CACHE_SLICE_INDEX) {
536 /* This is a cache entry. We don't maintain a free list, so
537 * there's nothing to do. */
538 return PSA_SUCCESS;
539 }
540 if (slice_idx >= KEY_SLOT_VOLATILE_SLICE_COUNT) {
541 return PSA_ERROR_CORRUPTION_DETECTED;
542 }
543
544 psa_key_slot_t *slice = global_data.key_slices[slice_idx];
545 psa_key_slot_t *slice_end = slice + key_slice_length(slice_idx);
546 if (slot < slice || slot >= slice_end) {
547 /* The slot isn't actually in the slice! We can't detect that
548 * condition for sure, because the pointer comparison itself is
549 * undefined behavior in that case. That same condition makes the
550 * subtraction to calculate the slot index also UB.
551 * Give up now to avoid causing further corruption.
552 */
553 return PSA_ERROR_CORRUPTION_DETECTED;
554 }
555 size_t slot_idx = slot - slice;
556
557 size_t next_free = global_data.first_free_slot_index[slice_idx];
558 if (next_free >= key_slice_length(slice_idx)) {
559 /* The slot was full. The newly freed slot thus becomes the
560 * end of the free list. */
561 next_free = key_slice_length(slice_idx);
562 }
563 global_data.first_free_slot_index[slice_idx] = slot_idx;
564 slot->var.free.next_free_relative_to_next =
565 (int32_t) next_free - (int32_t) slot_idx - 1;
566
567 return PSA_SUCCESS;
568}
569#endif /* MBEDTLS_PSA_KEY_STORE_DYNAMIC */
570
571psa_status_t psa_reserve_free_key_slot(psa_key_id_t *volatile_key_id,
572 psa_key_slot_t **p_slot)
573{
574 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
575 size_t slot_idx;
576 psa_key_slot_t *selected_slot, *unused_persistent_key_slot;
577
578 if (!psa_get_key_slots_initialized()) {
579 status = PSA_ERROR_BAD_STATE;
580 goto error;
581 }
582
583#if defined(MBEDTLS_PSA_KEY_STORE_DYNAMIC)
584 if (volatile_key_id != NULL) {
585 return psa_allocate_volatile_key_slot(volatile_key_id, p_slot);
586 }
587#endif /* MBEDTLS_PSA_KEY_STORE_DYNAMIC */
588
589 /* With a dynamic key store, allocate an entry in the cache slice,
590 * applicable only to non-volatile keys that get cached in RAM.
591 * With a static key store, allocate an entry in the sole slice,
592 * applicable to all keys. */
593 selected_slot = unused_persistent_key_slot = NULL;
594 for (slot_idx = 0; slot_idx < PERSISTENT_KEY_CACHE_COUNT; slot_idx++) {
595 psa_key_slot_t *slot = get_key_slot(KEY_SLOT_CACHE_SLICE_INDEX, slot_idx);
596 if (slot->state == PSA_SLOT_EMPTY) {
597 selected_slot = slot;
598 break;
599 }
600
601 if ((unused_persistent_key_slot == NULL) &&
602 (slot->state == PSA_SLOT_FULL) &&
603 (!psa_key_slot_has_readers(slot)) &&
604 (!PSA_KEY_LIFETIME_IS_VOLATILE(slot->attr.lifetime))) {
605 unused_persistent_key_slot = slot;
606 }
607 }
608
609 /*
610 * If there is no unused key slot and there is at least one unlocked key
611 * slot containing the description of a persistent key, recycle the first
612 * such key slot we encountered. If we later need to operate on the
613 * persistent key we are evicting now, we will reload its description from
614 * storage.
615 */
616 if ((selected_slot == NULL) &&
617 (unused_persistent_key_slot != NULL)) {
618 selected_slot = unused_persistent_key_slot;
619 psa_register_read(selected_slot);
620 status = psa_wipe_key_slot(selected_slot);
621 if (status != PSA_SUCCESS) {
622 goto error;
623 }
624 }
625
626 if (selected_slot != NULL) {
627 status = psa_key_slot_state_transition(selected_slot, PSA_SLOT_EMPTY,
628 PSA_SLOT_FILLING);
629 if (status != PSA_SUCCESS) {
630 goto error;
631 }
632
633#if defined(MBEDTLS_PSA_KEY_STORE_DYNAMIC)
634 selected_slot->slice_index = KEY_SLOT_CACHE_SLICE_INDEX;
635#endif /* MBEDTLS_PSA_KEY_STORE_DYNAMIC */
636
637#if !defined(MBEDTLS_PSA_KEY_STORE_DYNAMIC)
638 if (volatile_key_id != NULL) {
639 /* Refresh slot_idx, for when the slot is not the original
640 * selected_slot but rather unused_persistent_key_slot. */
641 slot_idx = selected_slot - global_data.key_slots;
642 *volatile_key_id = PSA_KEY_ID_VOLATILE_MIN + (psa_key_id_t) slot_idx;
643 }
644#endif
645 *p_slot = selected_slot;
646
647 return PSA_SUCCESS;
648 }
649 status = PSA_ERROR_INSUFFICIENT_MEMORY;
650
651error:
652 *p_slot = NULL;
653
654 return status;
655}
656
657#if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C)
658static psa_status_t psa_load_persistent_key_into_slot(psa_key_slot_t *slot)
659{
660 psa_status_t status = PSA_SUCCESS;
661 uint8_t *key_data = NULL;
662 size_t key_data_length = 0;
663
664 if (!psa_key_id_is_user(MBEDTLS_SVC_KEY_ID_GET_KEY_ID(slot->attr.id))) {
665 return PSA_ERROR_DOES_NOT_EXIST;
666 }
667
668 status = psa_load_persistent_key(&slot->attr,
669 &key_data, &key_data_length);
670 if (status != PSA_SUCCESS) {
671 goto exit;
672 }
673
674 status = psa_copy_key_material_into_slot(slot, key_data, key_data_length);
675 if (status != PSA_SUCCESS) {
676 goto exit;
677 }
678
679exit:
680 psa_free_persistent_key_data(key_data, key_data_length);
681 return status;
682}
683#endif /* MBEDTLS_PSA_CRYPTO_STORAGE_C */
684
685#if defined(MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS)
686
687static psa_status_t psa_load_builtin_key_into_slot(psa_key_slot_t *slot)
688{
689 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
690 psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
691 psa_key_lifetime_t lifetime = PSA_KEY_LIFETIME_VOLATILE;
692 psa_drv_slot_number_t slot_number = 0;
693 size_t key_buffer_size = 0;
694 size_t key_buffer_length = 0;
695
696 if (!psa_key_id_is_builtin(
697 MBEDTLS_SVC_KEY_ID_GET_KEY_ID(slot->attr.id))) {
698 return PSA_ERROR_DOES_NOT_EXIST;
699 }
700
701 /* Check the platform function to see whether this key actually exists */
702 status = mbedtls_psa_platform_get_builtin_key(
703 slot->attr.id, &lifetime, &slot_number);
704 if (status != PSA_SUCCESS) {
705 return status;
706 }
707
708 /* Set required key attributes to ensure get_builtin_key can retrieve the
709 * full attributes. */
710 psa_set_key_id(&attributes, slot->attr.id);
711 psa_set_key_lifetime(&attributes, lifetime);
712
713 /* Get the full key attributes from the driver in order to be able to
714 * calculate the required buffer size. */
715 status = psa_driver_wrapper_get_builtin_key(
716 slot_number, &attributes,
717 NULL, 0, NULL);
718 if (status != PSA_ERROR_BUFFER_TOO_SMALL) {
719 /* Builtin keys cannot be defined by the attributes alone */
720 if (status == PSA_SUCCESS) {
721 status = PSA_ERROR_CORRUPTION_DETECTED;
722 }
723 return status;
724 }
725
726 /* If the key should exist according to the platform, then ask the driver
727 * what its expected size is. */
728 status = psa_driver_wrapper_get_key_buffer_size(&attributes,
729 &key_buffer_size);
730 if (status != PSA_SUCCESS) {
731 return status;
732 }
733
734 /* Allocate a buffer of the required size and load the builtin key directly
735 * into the (now properly sized) slot buffer. */
736 status = psa_allocate_buffer_to_slot(slot, key_buffer_size);
737 if (status != PSA_SUCCESS) {
738 return status;
739 }
740
741 status = psa_driver_wrapper_get_builtin_key(
742 slot_number, &attributes,
743 slot->key.data, slot->key.bytes, &key_buffer_length);
744 if (status != PSA_SUCCESS) {
745 goto exit;
746 }
747
748 /* Copy actual key length and core attributes into the slot on success */
749 slot->key.bytes = key_buffer_length;
750 slot->attr = attributes;
751exit:
752 if (status != PSA_SUCCESS) {
753 psa_remove_key_data_from_memory(slot);
754 }
755 return status;
756}
757#endif /* MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS */
758
759psa_status_t psa_get_and_lock_key_slot(mbedtls_svc_key_id_t key,
760 psa_key_slot_t **p_slot)
761{
762 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
763
764 *p_slot = NULL;
765 if (!psa_get_key_slots_initialized()) {
766 return PSA_ERROR_BAD_STATE;
767 }
768
769#if defined(MBEDTLS_THREADING_C)
770 /* We need to set status as success, otherwise CORRUPTION_DETECTED
771 * would be returned if the lock fails. */
772 status = PSA_SUCCESS;
773 /* If the key is persistent and not loaded, we cannot unlock the mutex
774 * between checking if the key is loaded and setting the slot as FULL,
775 * as otherwise another thread may load and then destroy the key
776 * in the meantime. */
777 PSA_THREADING_CHK_RET(mbedtls_mutex_lock(
778 &mbedtls_threading_key_slot_mutex));
779#endif
780 /*
781 * On success, the pointer to the slot is passed directly to the caller
782 * thus no need to unlock the key slot here.
783 */
784 status = psa_get_and_lock_key_slot_in_memory(key, p_slot);
785 if (status != PSA_ERROR_DOES_NOT_EXIST) {
786#if defined(MBEDTLS_THREADING_C)
787 PSA_THREADING_CHK_RET(mbedtls_mutex_unlock(
788 &mbedtls_threading_key_slot_mutex));
789#endif
790 return status;
791 }
792
793 /* Loading keys from storage requires support for such a mechanism */
794#if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) || \
795 defined(MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS)
796
797 status = psa_reserve_free_key_slot(NULL, p_slot);
798 if (status != PSA_SUCCESS) {
799#if defined(MBEDTLS_THREADING_C)
800 PSA_THREADING_CHK_RET(mbedtls_mutex_unlock(
801 &mbedtls_threading_key_slot_mutex));
802#endif
803 return status;
804 }
805
806 (*p_slot)->attr.id = key;
807 (*p_slot)->attr.lifetime = PSA_KEY_LIFETIME_PERSISTENT;
808
809 status = PSA_ERROR_DOES_NOT_EXIST;
810#if defined(MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS)
811 /* Load keys in the 'builtin' range through their own interface */
812 status = psa_load_builtin_key_into_slot(*p_slot);
813#endif /* MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS */
814
815#if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C)
816 if (status == PSA_ERROR_DOES_NOT_EXIST) {
817 status = psa_load_persistent_key_into_slot(*p_slot);
818 }
819#endif /* defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) */
820
821 if (status != PSA_SUCCESS) {
822 psa_wipe_key_slot(*p_slot);
823
824 /* If the key does not exist, we need to return
825 * PSA_ERROR_INVALID_HANDLE. */
826 if (status == PSA_ERROR_DOES_NOT_EXIST) {
827 status = PSA_ERROR_INVALID_HANDLE;
828 }
829 } else {
830 /* Add implicit usage flags. */
831 psa_extend_key_usage_flags(&(*p_slot)->attr.policy.usage);
832
833 psa_key_slot_state_transition((*p_slot), PSA_SLOT_FILLING,
834 PSA_SLOT_FULL);
835 status = psa_register_read(*p_slot);
836 }
837
838#else /* MBEDTLS_PSA_CRYPTO_STORAGE_C || MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS */
839 status = PSA_ERROR_INVALID_HANDLE;
840#endif /* MBEDTLS_PSA_CRYPTO_STORAGE_C || MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS */
841
842 if (status != PSA_SUCCESS) {
843 *p_slot = NULL;
844 }
845#if defined(MBEDTLS_THREADING_C)
846 PSA_THREADING_CHK_RET(mbedtls_mutex_unlock(
847 &mbedtls_threading_key_slot_mutex));
848#endif
849 return status;
850}
851
852psa_status_t psa_unregister_read(psa_key_slot_t *slot)
853{
854 if (slot == NULL) {
855 return PSA_SUCCESS;
856 }
857 if ((slot->state != PSA_SLOT_FULL) &&
858 (slot->state != PSA_SLOT_PENDING_DELETION)) {
859 return PSA_ERROR_CORRUPTION_DETECTED;
860 }
861
862 /* If we are the last reader and the slot is marked for deletion,
863 * we must wipe the slot here. */
864 if ((slot->state == PSA_SLOT_PENDING_DELETION) &&
865 (slot->var.occupied.registered_readers == 1)) {
866 return psa_wipe_key_slot(slot);
867 }
868
869 if (psa_key_slot_has_readers(slot)) {
870 slot->var.occupied.registered_readers--;
871 return PSA_SUCCESS;
872 }
873
874 /*
875 * As the return error code may not be handled in case of multiple errors,
876 * do our best to report if there are no registered readers. Assert with
877 * MBEDTLS_TEST_HOOK_TEST_ASSERT that there are registered readers:
878 * if the MBEDTLS_TEST_HOOKS configuration option is enabled and
879 * the function is called as part of the execution of a test suite, the
880 * execution of the test suite is stopped in error if the assertion fails.
881 */
882 MBEDTLS_TEST_HOOK_TEST_ASSERT(psa_key_slot_has_readers(slot));
883 return PSA_ERROR_CORRUPTION_DETECTED;
884}
885
886psa_status_t psa_unregister_read_under_mutex(psa_key_slot_t *slot)
887{
888 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
889#if defined(MBEDTLS_THREADING_C)
890 /* We need to set status as success, otherwise CORRUPTION_DETECTED
891 * would be returned if the lock fails. */
892 status = PSA_SUCCESS;
893 PSA_THREADING_CHK_RET(mbedtls_mutex_lock(
894 &mbedtls_threading_key_slot_mutex));
895#endif
896 status = psa_unregister_read(slot);
897#if defined(MBEDTLS_THREADING_C)
898 PSA_THREADING_CHK_RET(mbedtls_mutex_unlock(
899 &mbedtls_threading_key_slot_mutex));
900#endif
901 return status;
902}
903
904psa_status_t psa_validate_key_persistence(psa_key_lifetime_t lifetime)
905{
906 if (PSA_KEY_LIFETIME_IS_VOLATILE(lifetime)) {
907 /* Volatile keys are always supported */
908 return PSA_SUCCESS;
909 } else {
910 /* Persistent keys require storage support */
911#if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C)
912 if (PSA_KEY_LIFETIME_IS_READ_ONLY(lifetime)) {
913 return PSA_ERROR_INVALID_ARGUMENT;
914 } else {
915 return PSA_SUCCESS;
916 }
917#else /* MBEDTLS_PSA_CRYPTO_STORAGE_C */
918 return PSA_ERROR_NOT_SUPPORTED;
919#endif /* !MBEDTLS_PSA_CRYPTO_STORAGE_C */
920 }
921}
922
923psa_status_t psa_purge_key(mbedtls_svc_key_id_t key)
924{
925 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
926 psa_key_slot_t *slot;
927
928#if defined(MBEDTLS_THREADING_C)
929 /* We need to set status as success, otherwise CORRUPTION_DETECTED
930 * would be returned if the lock fails. */
931 status = PSA_SUCCESS;
932 PSA_THREADING_CHK_RET(mbedtls_mutex_lock(
933 &mbedtls_threading_key_slot_mutex));
934#endif
935 status = psa_get_and_lock_key_slot_in_memory(key, &slot);
936 if (status != PSA_SUCCESS) {
937#if defined(MBEDTLS_THREADING_C)
938 PSA_THREADING_CHK_RET(mbedtls_mutex_unlock(
939 &mbedtls_threading_key_slot_mutex));
940#endif
941 return status;
942 }
943
944 if ((!PSA_KEY_LIFETIME_IS_VOLATILE(slot->attr.lifetime)) &&
945 (slot->var.occupied.registered_readers == 1)) {
946 status = psa_wipe_key_slot(slot);
947 } else {
948 status = psa_unregister_read(slot);
949 }
950#if defined(MBEDTLS_THREADING_C)
951 PSA_THREADING_CHK_RET(mbedtls_mutex_unlock(
952 &mbedtls_threading_key_slot_mutex));
953#endif
954
955 return status;
956}
957
958void mbedtls_psa_get_stats(mbedtls_psa_stats_t *stats)
959{
960 memset(stats, 0, sizeof(*stats));
961
962 for (size_t slice_idx = 0; slice_idx < KEY_SLICE_COUNT; slice_idx++) {
963#if defined(MBEDTLS_PSA_KEY_STORE_DYNAMIC)
964 if (global_data.key_slices[slice_idx] == NULL) {
965 continue;
966 }
967#endif /* MBEDTLS_PSA_KEY_STORE_DYNAMIC */
968 for (size_t slot_idx = 0; slot_idx < key_slice_length(slice_idx); slot_idx++) {
969 const psa_key_slot_t *slot = get_key_slot(slice_idx, slot_idx);
970 if (slot->state == PSA_SLOT_EMPTY) {
971 ++stats->empty_slots;
972 continue;
973 }
974 if (psa_key_slot_has_readers(slot)) {
975 ++stats->locked_slots;
976 }
977 if (PSA_KEY_LIFETIME_IS_VOLATILE(slot->attr.lifetime)) {
978 ++stats->volatile_slots;
979 } else {
980 psa_key_id_t id = MBEDTLS_SVC_KEY_ID_GET_KEY_ID(slot->attr.id);
981 ++stats->persistent_slots;
982 if (id > stats->max_open_internal_key_id) {
983 stats->max_open_internal_key_id = id;
984 }
985 }
986 if (PSA_KEY_LIFETIME_GET_LOCATION(slot->attr.lifetime) !=
987 PSA_KEY_LOCATION_LOCAL_STORAGE) {
988 psa_key_id_t id = MBEDTLS_SVC_KEY_ID_GET_KEY_ID(slot->attr.id);
989 ++stats->external_slots;
990 if (id > stats->max_open_external_key_id) {
991 stats->max_open_external_key_id = id;
992 }
993 }
994 }
995 }
996}
997
998#endif /* MBEDTLS_PSA_CRYPTO_C */