• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "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.h"
17 #include "psa_crypto_slot_management.h"
18 #include "psa_crypto_storage.h"
19 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
20 #include "psa_crypto_se.h"
21 #endif
22 
23 #include <stdlib.h>
24 #include <string.h>
25 #include "mbedtls/platform.h"
26 
27 #define ARRAY_LENGTH(array) (sizeof(array) / sizeof(*(array)))
28 
29 typedef struct {
30     psa_key_slot_t key_slots[MBEDTLS_PSA_KEY_SLOT_COUNT];
31     unsigned key_slots_initialized : 1;
32 } psa_global_data_t;
33 
34 static psa_global_data_t global_data;
35 
psa_is_valid_key_id(mbedtls_svc_key_id_t key,int vendor_ok)36 int psa_is_valid_key_id(mbedtls_svc_key_id_t key, int vendor_ok)
37 {
38     psa_key_id_t key_id = MBEDTLS_SVC_KEY_ID_GET_KEY_ID(key);
39 
40     if ((PSA_KEY_ID_USER_MIN <= key_id) &&
41         (key_id <= PSA_KEY_ID_USER_MAX)) {
42         return 1;
43     }
44 
45     if (vendor_ok &&
46         (PSA_KEY_ID_VENDOR_MIN <= key_id) &&
47         (key_id <= PSA_KEY_ID_VENDOR_MAX)) {
48         return 1;
49     }
50 
51     return 0;
52 }
53 
54 /** Get the description in memory of a key given its identifier and lock it.
55  *
56  * The descriptions of volatile keys and loaded persistent keys are
57  * stored in key slots. This function returns a pointer to the key slot
58  * containing the description of a key given its identifier.
59  *
60  * The function searches the key slots containing the description of the key
61  * with \p key identifier. The function does only read accesses to the key
62  * slots. The function does not load any persistent key thus does not access
63  * any storage.
64  *
65  * For volatile key identifiers, only one key slot is queried as a volatile
66  * key with identifier key_id can only be stored in slot of index
67  * ( key_id - #PSA_KEY_ID_VOLATILE_MIN ).
68  *
69  * On success, the function locks the key slot. It is the responsibility of
70  * the caller to unlock the key slot when it does not access it anymore.
71  *
72  * \param key           Key identifier to query.
73  * \param[out] p_slot   On success, `*p_slot` contains a pointer to the
74  *                      key slot containing the description of the key
75  *                      identified by \p key.
76  *
77  * \retval #PSA_SUCCESS
78  *         The pointer to the key slot containing the description of the key
79  *         identified by \p key was returned.
80  * \retval #PSA_ERROR_INVALID_HANDLE
81  *         \p key is not a valid key identifier.
82  * \retval #PSA_ERROR_DOES_NOT_EXIST
83  *         There is no key with key identifier \p key in the key slots.
84  */
psa_get_and_lock_key_slot_in_memory(mbedtls_svc_key_id_t key,psa_key_slot_t ** p_slot)85 static psa_status_t psa_get_and_lock_key_slot_in_memory(
86     mbedtls_svc_key_id_t key, psa_key_slot_t **p_slot)
87 {
88     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
89     psa_key_id_t key_id = MBEDTLS_SVC_KEY_ID_GET_KEY_ID(key);
90     size_t slot_idx;
91     psa_key_slot_t *slot = NULL;
92 
93     if (psa_key_id_is_volatile(key_id)) {
94         slot = &global_data.key_slots[key_id - PSA_KEY_ID_VOLATILE_MIN];
95 
96         /*
97          * Check if both the PSA key identifier key_id and the owner
98          * identifier of key match those of the key slot.
99          *
100          * Note that, if the key slot is not occupied, its PSA key identifier
101          * is equal to zero. This is an invalid value for a PSA key identifier
102          * and thus cannot be equal to the valid PSA key identifier key_id.
103          */
104         status = mbedtls_svc_key_id_equal(key, slot->attr.id) ?
105                  PSA_SUCCESS : PSA_ERROR_DOES_NOT_EXIST;
106     } else {
107         if (!psa_is_valid_key_id(key, 1)) {
108             return PSA_ERROR_INVALID_HANDLE;
109         }
110 
111         for (slot_idx = 0; slot_idx < MBEDTLS_PSA_KEY_SLOT_COUNT; slot_idx++) {
112             slot = &global_data.key_slots[slot_idx];
113             if (mbedtls_svc_key_id_equal(key, slot->attr.id)) {
114                 break;
115             }
116         }
117         status = (slot_idx < MBEDTLS_PSA_KEY_SLOT_COUNT) ?
118                  PSA_SUCCESS : PSA_ERROR_DOES_NOT_EXIST;
119     }
120 
121     if (status == PSA_SUCCESS) {
122         status = psa_lock_key_slot(slot);
123         if (status == PSA_SUCCESS) {
124             *p_slot = slot;
125         }
126     }
127 
128     return status;
129 }
130 
psa_initialize_key_slots(void)131 psa_status_t psa_initialize_key_slots(void)
132 {
133     /* Nothing to do: program startup and psa_wipe_all_key_slots() both
134      * guarantee that the key slots are initialized to all-zero, which
135      * means that all the key slots are in a valid, empty state. */
136     global_data.key_slots_initialized = 1;
137     return PSA_SUCCESS;
138 }
139 
psa_wipe_all_key_slots(void)140 void psa_wipe_all_key_slots(void)
141 {
142     size_t slot_idx;
143 
144     for (slot_idx = 0; slot_idx < MBEDTLS_PSA_KEY_SLOT_COUNT; slot_idx++) {
145         psa_key_slot_t *slot = &global_data.key_slots[slot_idx];
146         slot->lock_count = 1;
147         (void) psa_wipe_key_slot(slot);
148     }
149     global_data.key_slots_initialized = 0;
150 }
151 
psa_get_empty_key_slot(psa_key_id_t * volatile_key_id,psa_key_slot_t ** p_slot)152 psa_status_t psa_get_empty_key_slot(psa_key_id_t *volatile_key_id,
153                                     psa_key_slot_t **p_slot)
154 {
155     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
156     size_t slot_idx;
157     psa_key_slot_t *selected_slot, *unlocked_persistent_key_slot;
158 
159     if (!global_data.key_slots_initialized) {
160         status = PSA_ERROR_BAD_STATE;
161         goto error;
162     }
163 
164     selected_slot = unlocked_persistent_key_slot = NULL;
165     for (slot_idx = 0; slot_idx < MBEDTLS_PSA_KEY_SLOT_COUNT; slot_idx++) {
166         psa_key_slot_t *slot = &global_data.key_slots[slot_idx];
167         if (!psa_is_key_slot_occupied(slot)) {
168             selected_slot = slot;
169             break;
170         }
171 
172         if ((unlocked_persistent_key_slot == NULL) &&
173             (!PSA_KEY_LIFETIME_IS_VOLATILE(slot->attr.lifetime)) &&
174             (!psa_is_key_slot_locked(slot))) {
175             unlocked_persistent_key_slot = slot;
176         }
177     }
178 
179     /*
180      * If there is no unused key slot and there is at least one unlocked key
181      * slot containing the description of a persistent key, recycle the first
182      * such key slot we encountered. If we later need to operate on the
183      * persistent key we are evicting now, we will reload its description from
184      * storage.
185      */
186     if ((selected_slot == NULL) &&
187         (unlocked_persistent_key_slot != NULL)) {
188         selected_slot = unlocked_persistent_key_slot;
189         selected_slot->lock_count = 1;
190         psa_wipe_key_slot(selected_slot);
191     }
192 
193     if (selected_slot != NULL) {
194         status = psa_lock_key_slot(selected_slot);
195         if (status != PSA_SUCCESS) {
196             goto error;
197         }
198 
199         *volatile_key_id = PSA_KEY_ID_VOLATILE_MIN +
200                            ((psa_key_id_t) (selected_slot - global_data.key_slots));
201         *p_slot = selected_slot;
202 
203         return PSA_SUCCESS;
204     }
205     status = PSA_ERROR_INSUFFICIENT_MEMORY;
206 
207 error:
208     *p_slot = NULL;
209     *volatile_key_id = 0;
210 
211     return status;
212 }
213 
214 #if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C)
psa_load_persistent_key_into_slot(psa_key_slot_t * slot)215 static psa_status_t psa_load_persistent_key_into_slot(psa_key_slot_t *slot)
216 {
217     psa_status_t status = PSA_SUCCESS;
218     uint8_t *key_data = NULL;
219     size_t key_data_length = 0;
220 
221     status = psa_load_persistent_key(&slot->attr,
222                                      &key_data, &key_data_length);
223     if (status != PSA_SUCCESS) {
224         goto exit;
225     }
226 
227 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
228     /* Special handling is required for loading keys associated with a
229      * dynamically registered SE interface. */
230     const psa_drv_se_t *drv;
231     psa_drv_se_context_t *drv_context;
232     if (psa_get_se_driver(slot->attr.lifetime, &drv, &drv_context)) {
233         psa_se_key_data_storage_t *data;
234 
235         if (key_data_length != sizeof(*data)) {
236             status = PSA_ERROR_DATA_INVALID;
237             goto exit;
238         }
239         data = (psa_se_key_data_storage_t *) key_data;
240         status = psa_copy_key_material_into_slot(
241             slot, data->slot_number, sizeof(data->slot_number));
242         goto exit;
243     }
244 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
245 
246     status = psa_copy_key_material_into_slot(slot, key_data, key_data_length);
247 
248 exit:
249     psa_free_persistent_key_data(key_data, key_data_length);
250     return status;
251 }
252 #endif /* MBEDTLS_PSA_CRYPTO_STORAGE_C */
253 
254 #if defined(MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS)
255 
psa_load_builtin_key_into_slot(psa_key_slot_t * slot)256 static psa_status_t psa_load_builtin_key_into_slot(psa_key_slot_t *slot)
257 {
258     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
259     psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
260     psa_key_lifetime_t lifetime = PSA_KEY_LIFETIME_VOLATILE;
261     psa_drv_slot_number_t slot_number = 0;
262     size_t key_buffer_size = 0;
263     size_t key_buffer_length = 0;
264 
265     if (!psa_key_id_is_builtin(
266             MBEDTLS_SVC_KEY_ID_GET_KEY_ID(slot->attr.id))) {
267         return PSA_ERROR_DOES_NOT_EXIST;
268     }
269 
270     /* Check the platform function to see whether this key actually exists */
271     status = mbedtls_psa_platform_get_builtin_key(
272         slot->attr.id, &lifetime, &slot_number);
273     if (status != PSA_SUCCESS) {
274         return status;
275     }
276 
277     /* Set required key attributes to ensure get_builtin_key can retrieve the
278      * full attributes. */
279     psa_set_key_id(&attributes, slot->attr.id);
280     psa_set_key_lifetime(&attributes, lifetime);
281 
282     /* Get the full key attributes from the driver in order to be able to
283      * calculate the required buffer size. */
284     status = psa_driver_wrapper_get_builtin_key(
285         slot_number, &attributes,
286         NULL, 0, NULL);
287     if (status != PSA_ERROR_BUFFER_TOO_SMALL) {
288         /* Builtin keys cannot be defined by the attributes alone */
289         if (status == PSA_SUCCESS) {
290             status = PSA_ERROR_CORRUPTION_DETECTED;
291         }
292         return status;
293     }
294 
295     /* If the key should exist according to the platform, then ask the driver
296      * what its expected size is. */
297     status = psa_driver_wrapper_get_key_buffer_size(&attributes,
298                                                     &key_buffer_size);
299     if (status != PSA_SUCCESS) {
300         return status;
301     }
302 
303     /* Allocate a buffer of the required size and load the builtin key directly
304      * into the (now properly sized) slot buffer. */
305     status = psa_allocate_buffer_to_slot(slot, key_buffer_size);
306     if (status != PSA_SUCCESS) {
307         return status;
308     }
309 
310     status = psa_driver_wrapper_get_builtin_key(
311         slot_number, &attributes,
312         slot->key.data, slot->key.bytes, &key_buffer_length);
313     if (status != PSA_SUCCESS) {
314         goto exit;
315     }
316 
317     /* Copy actual key length and core attributes into the slot on success */
318     slot->key.bytes = key_buffer_length;
319     slot->attr = attributes.core;
320 
321 exit:
322     if (status != PSA_SUCCESS) {
323         psa_remove_key_data_from_memory(slot);
324     }
325     return status;
326 }
327 #endif /* MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS */
328 
psa_get_and_lock_key_slot(mbedtls_svc_key_id_t key,psa_key_slot_t ** p_slot)329 psa_status_t psa_get_and_lock_key_slot(mbedtls_svc_key_id_t key,
330                                        psa_key_slot_t **p_slot)
331 {
332     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
333 
334     *p_slot = NULL;
335     if (!global_data.key_slots_initialized) {
336         return PSA_ERROR_BAD_STATE;
337     }
338 
339     /*
340      * On success, the pointer to the slot is passed directly to the caller
341      * thus no need to unlock the key slot here.
342      */
343     status = psa_get_and_lock_key_slot_in_memory(key, p_slot);
344     if (status != PSA_ERROR_DOES_NOT_EXIST) {
345         return status;
346     }
347 
348     /* Loading keys from storage requires support for such a mechanism */
349 #if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) || \
350     defined(MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS)
351     psa_key_id_t volatile_key_id;
352 
353     status = psa_get_empty_key_slot(&volatile_key_id, p_slot);
354     if (status != PSA_SUCCESS) {
355         return status;
356     }
357 
358     (*p_slot)->attr.id = key;
359     (*p_slot)->attr.lifetime = PSA_KEY_LIFETIME_PERSISTENT;
360 
361     status = PSA_ERROR_DOES_NOT_EXIST;
362 #if defined(MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS)
363     /* Load keys in the 'builtin' range through their own interface */
364     status = psa_load_builtin_key_into_slot(*p_slot);
365 #endif /* MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS */
366 
367 #if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C)
368     if (status == PSA_ERROR_DOES_NOT_EXIST) {
369         status = psa_load_persistent_key_into_slot(*p_slot);
370     }
371 #endif /* defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) */
372 
373     if (status != PSA_SUCCESS) {
374         psa_wipe_key_slot(*p_slot);
375         if (status == PSA_ERROR_DOES_NOT_EXIST) {
376             status = PSA_ERROR_INVALID_HANDLE;
377         }
378     } else {
379         /* Add implicit usage flags. */
380         psa_extend_key_usage_flags(&(*p_slot)->attr.policy.usage);
381     }
382 
383     return status;
384 #else /* MBEDTLS_PSA_CRYPTO_STORAGE_C || MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS */
385     return PSA_ERROR_INVALID_HANDLE;
386 #endif /* MBEDTLS_PSA_CRYPTO_STORAGE_C || MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS */
387 }
388 
psa_unlock_key_slot(psa_key_slot_t * slot)389 psa_status_t psa_unlock_key_slot(psa_key_slot_t *slot)
390 {
391     if (slot == NULL) {
392         return PSA_SUCCESS;
393     }
394 
395     if (slot->lock_count > 0) {
396         slot->lock_count--;
397         return PSA_SUCCESS;
398     }
399 
400     /*
401      * As the return error code may not be handled in case of multiple errors,
402      * do our best to report if the lock counter is equal to zero: if
403      * available call MBEDTLS_PARAM_FAILED that may terminate execution (if
404      * called as part of the execution of a unit test suite this will stop the
405      * test suite execution).
406      */
407 #ifdef MBEDTLS_CHECK_PARAMS
408     MBEDTLS_PARAM_FAILED(slot->lock_count > 0);
409 #endif
410 
411     return PSA_ERROR_CORRUPTION_DETECTED;
412 }
413 
psa_validate_key_location(psa_key_lifetime_t lifetime,psa_se_drv_table_entry_t ** p_drv)414 psa_status_t psa_validate_key_location(psa_key_lifetime_t lifetime,
415                                        psa_se_drv_table_entry_t **p_drv)
416 {
417     if (psa_key_lifetime_is_external(lifetime)) {
418 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
419         /* Check whether a driver is registered against this lifetime */
420         psa_se_drv_table_entry_t *driver = psa_get_se_driver_entry(lifetime);
421         if (driver != NULL) {
422             if (p_drv != NULL) {
423                 *p_drv = driver;
424             }
425             return PSA_SUCCESS;
426         }
427 #else /* MBEDTLS_PSA_CRYPTO_SE_C */
428         (void) p_drv;
429 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
430 
431 #if defined(MBEDTLS_PSA_CRYPTO_DRIVERS)
432         /* Key location for external keys gets checked by the wrapper */
433         return PSA_SUCCESS;
434 #else /* MBEDTLS_PSA_CRYPTO_DRIVERS */
435         /* No support for external lifetimes at all, or dynamic interface
436          * did not find driver for requested lifetime. */
437         return PSA_ERROR_INVALID_ARGUMENT;
438 #endif /* MBEDTLS_PSA_CRYPTO_DRIVERS */
439     } else {
440         /* Local/internal keys are always valid */
441         return PSA_SUCCESS;
442     }
443 }
444 
psa_validate_key_persistence(psa_key_lifetime_t lifetime)445 psa_status_t psa_validate_key_persistence(psa_key_lifetime_t lifetime)
446 {
447     if (PSA_KEY_LIFETIME_IS_VOLATILE(lifetime)) {
448         /* Volatile keys are always supported */
449         return PSA_SUCCESS;
450     } else {
451         /* Persistent keys require storage support */
452 #if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C)
453         if (PSA_KEY_LIFETIME_IS_READ_ONLY(lifetime)) {
454             return PSA_ERROR_INVALID_ARGUMENT;
455         } else {
456             return PSA_SUCCESS;
457         }
458 #else /* MBEDTLS_PSA_CRYPTO_STORAGE_C */
459         return PSA_ERROR_NOT_SUPPORTED;
460 #endif /* !MBEDTLS_PSA_CRYPTO_STORAGE_C */
461     }
462 }
463 
psa_open_key(mbedtls_svc_key_id_t key,psa_key_handle_t * handle)464 psa_status_t psa_open_key(mbedtls_svc_key_id_t key, psa_key_handle_t *handle)
465 {
466 #if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) || \
467     defined(MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS)
468     psa_status_t status;
469     psa_key_slot_t *slot;
470 
471     status = psa_get_and_lock_key_slot(key, &slot);
472     if (status != PSA_SUCCESS) {
473         *handle = PSA_KEY_HANDLE_INIT;
474         if (status == PSA_ERROR_INVALID_HANDLE) {
475             status = PSA_ERROR_DOES_NOT_EXIST;
476         }
477 
478         return status;
479     }
480 
481     *handle = key;
482 
483     return psa_unlock_key_slot(slot);
484 
485 #else /* MBEDTLS_PSA_CRYPTO_STORAGE_C || MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS */
486     (void) key;
487     *handle = PSA_KEY_HANDLE_INIT;
488     return PSA_ERROR_NOT_SUPPORTED;
489 #endif /* MBEDTLS_PSA_CRYPTO_STORAGE_C || MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS */
490 }
491 
psa_close_key(psa_key_handle_t handle)492 psa_status_t psa_close_key(psa_key_handle_t handle)
493 {
494     psa_status_t status;
495     psa_key_slot_t *slot;
496 
497     if (psa_key_handle_is_null(handle)) {
498         return PSA_SUCCESS;
499     }
500 
501     status = psa_get_and_lock_key_slot_in_memory(handle, &slot);
502     if (status != PSA_SUCCESS) {
503         if (status == PSA_ERROR_DOES_NOT_EXIST) {
504             status = PSA_ERROR_INVALID_HANDLE;
505         }
506 
507         return status;
508     }
509     if (slot->lock_count <= 1) {
510         return psa_wipe_key_slot(slot);
511     } else {
512         return psa_unlock_key_slot(slot);
513     }
514 }
515 
psa_purge_key(mbedtls_svc_key_id_t key)516 psa_status_t psa_purge_key(mbedtls_svc_key_id_t key)
517 {
518     psa_status_t status;
519     psa_key_slot_t *slot;
520 
521     status = psa_get_and_lock_key_slot_in_memory(key, &slot);
522     if (status != PSA_SUCCESS) {
523         return status;
524     }
525 
526     if ((!PSA_KEY_LIFETIME_IS_VOLATILE(slot->attr.lifetime)) &&
527         (slot->lock_count <= 1)) {
528         return psa_wipe_key_slot(slot);
529     } else {
530         return psa_unlock_key_slot(slot);
531     }
532 }
533 
mbedtls_psa_get_stats(mbedtls_psa_stats_t * stats)534 void mbedtls_psa_get_stats(mbedtls_psa_stats_t *stats)
535 {
536     size_t slot_idx;
537 
538     memset(stats, 0, sizeof(*stats));
539 
540     for (slot_idx = 0; slot_idx < MBEDTLS_PSA_KEY_SLOT_COUNT; slot_idx++) {
541         const psa_key_slot_t *slot = &global_data.key_slots[slot_idx];
542         if (psa_is_key_slot_locked(slot)) {
543             ++stats->locked_slots;
544         }
545         if (!psa_is_key_slot_occupied(slot)) {
546             ++stats->empty_slots;
547             continue;
548         }
549         if (PSA_KEY_LIFETIME_IS_VOLATILE(slot->attr.lifetime)) {
550             ++stats->volatile_slots;
551         } else {
552             psa_key_id_t id = MBEDTLS_SVC_KEY_ID_GET_KEY_ID(slot->attr.id);
553             ++stats->persistent_slots;
554             if (id > stats->max_open_internal_key_id) {
555                 stats->max_open_internal_key_id = id;
556             }
557         }
558         if (PSA_KEY_LIFETIME_GET_LOCATION(slot->attr.lifetime) !=
559             PSA_KEY_LOCATION_LOCAL_STORAGE) {
560             psa_key_id_t id = MBEDTLS_SVC_KEY_ID_GET_KEY_ID(slot->attr.id);
561             ++stats->external_slots;
562             if (id > stats->max_open_external_key_id) {
563                 stats->max_open_external_key_id = id;
564             }
565         }
566     }
567 }
568 
569 #endif /* MBEDTLS_PSA_CRYPTO_C */
570