• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/* BEGIN_HEADER */
2#include "psa/crypto_se_driver.h"
3
4#include "psa_crypto_se.h"
5#include "psa_crypto_slot_management.h"
6#include "psa_crypto_storage.h"
7
8/* Invasive peeking: check the persistent data */
9#if defined(MBEDTLS_PSA_ITS_FILE_C)
10#include "psa_crypto_its.h"
11#else /* Native ITS implementation */
12#include "psa/error.h"
13#include "psa/internal_trusted_storage.h"
14#endif
15
16
17/****************************************************************/
18/* Test driver helpers */
19/****************************************************************/
20
21/** The minimum valid location value for a secure element driver. */
22#define MIN_DRIVER_LOCATION 1
23
24/** The location and lifetime used for tests that use a single driver. */
25#define TEST_DRIVER_LOCATION 1
26#define TEST_SE_PERSISTENT_LIFETIME                             \
27    (PSA_KEY_LIFETIME_FROM_PERSISTENCE_AND_LOCATION(           \
28         PSA_KEY_PERSISTENCE_DEFAULT, TEST_DRIVER_LOCATION))
29
30#define TEST_SE_VOLATILE_LIFETIME                               \
31    (PSA_KEY_LIFETIME_FROM_PERSISTENCE_AND_LOCATION(           \
32         PSA_KEY_PERSISTENCE_VOLATILE, TEST_DRIVER_LOCATION))
33
34/** The driver detected a condition that shouldn't happen.
35 * This is probably a bug in the library. */
36#define PSA_ERROR_DETECTED_BY_DRIVER ((psa_status_t) (-500))
37
38/** Like #TEST_ASSERT for use in a driver method, with no cleanup.
39 *
40 * If an error happens, this macro returns from the calling function.
41 *
42 * Use this macro to assert on guarantees provided by the core.
43 */
44#define DRIVER_ASSERT_RETURN(TEST)                        \
45    do {                                                    \
46        if (!(TEST))                                       \
47        {                                                    \
48            mbedtls_test_fail( #TEST, __LINE__, __FILE__);   \
49            return PSA_ERROR_DETECTED_BY_DRIVER;           \
50        }                                                    \
51    } while (0)
52
53/** Like #TEST_ASSERT for use in a driver method, with cleanup.
54 *
55 * In case of error, this macro sets `status` and jumps to the
56 * label `exit`.
57 *
58 * Use this macro to assert on guarantees provided by the core.
59 */
60#define DRIVER_ASSERT(TEST)                               \
61    do {                                                    \
62        if (!(TEST))                                       \
63        {                                                    \
64            mbedtls_test_fail( #TEST, __LINE__, __FILE__);   \
65            status = PSA_ERROR_DETECTED_BY_DRIVER;            \
66            goto exit;                                        \
67        }                                                    \
68    } while (0)
69
70/** Like #PSA_ASSERT for a PSA API call that calls a driver underneath.
71 *
72 * Run the code \p expr. If this returns \p expected_status,
73 * do nothing. If this returns #PSA_ERROR_DETECTED_BY_DRIVER,
74 * jump directly to the `exit` label. If this returns any other
75 * status, call mbedtls_test_fail() then jump to `exit`.
76 *
77 * The special case for #PSA_ERROR_DETECTED_BY_DRIVER is because in this
78 * case, the test driver code is expected to have called mbedtls_test_fail()
79 * already, so we make sure not to overwrite the failure information.
80 */
81#define PSA_ASSERT_VIA_DRIVER(expr, expected_status)                  \
82    do {                                                                \
83        psa_status_t PSA_ASSERT_VIA_DRIVER_status = (expr);           \
84        if (PSA_ASSERT_VIA_DRIVER_status == PSA_ERROR_DETECTED_BY_DRIVER) \
85        goto exit;                                                  \
86        if (PSA_ASSERT_VIA_DRIVER_status != (expected_status))       \
87        {                                                               \
88            mbedtls_test_fail( #expr, __LINE__, __FILE__);                     \
89            goto exit;                                                  \
90        }                                                               \
91    } while (0)
92
93
94
95/****************************************************************/
96/* Domain support functions */
97/****************************************************************/
98
99/* Return the exact bit size given a curve family and a byte length. */
100static size_t ecc_curve_bits(psa_ecc_family_t curve, size_t data_length)
101{
102    switch (curve) {
103        case PSA_ECC_FAMILY_SECP_R1:
104            if (data_length == PSA_BYTES_TO_BITS(521)) {
105                return 521;
106            }
107            break;
108        case PSA_ECC_FAMILY_MONTGOMERY:
109            if (data_length == PSA_BYTES_TO_BITS(255)) {
110                return 255;
111            }
112    }
113    /* If not listed above, assume a multiple of 8 bits. */
114    return PSA_BYTES_TO_BITS(data_length);
115}
116
117
118/****************************************************************/
119/* Miscellaneous driver methods */
120/****************************************************************/
121
122typedef struct {
123    psa_key_slot_number_t slot_number;
124    psa_key_creation_method_t method;
125    psa_status_t status;
126} validate_slot_number_directions_t;
127static validate_slot_number_directions_t validate_slot_number_directions;
128
129/* Validate a choice of slot number as directed. */
130static psa_status_t validate_slot_number_as_directed(
131    psa_drv_se_context_t *context,
132    void *persistent_data,
133    const psa_key_attributes_t *attributes,
134    psa_key_creation_method_t method,
135    psa_key_slot_number_t slot_number)
136{
137    (void) context;
138    (void) persistent_data;
139    (void) attributes;
140    DRIVER_ASSERT_RETURN(slot_number ==
141                         validate_slot_number_directions.slot_number);
142    DRIVER_ASSERT_RETURN(method ==
143                         validate_slot_number_directions.method);
144    return validate_slot_number_directions.status;
145}
146
147/* Allocate slot numbers with a monotonic counter. */
148static psa_key_slot_number_t shadow_counter;
149static void counter_reset(void)
150{
151    shadow_counter = 0;
152}
153static psa_status_t counter_allocate(psa_drv_se_context_t *context,
154                                     void *persistent_data,
155                                     const psa_key_attributes_t *attributes,
156                                     psa_key_creation_method_t method,
157                                     psa_key_slot_number_t *slot_number)
158{
159    psa_key_slot_number_t *p_counter = persistent_data;
160    (void) attributes;
161    (void) method;
162    if (context->persistent_data_size != sizeof(psa_key_slot_number_t)) {
163        return PSA_ERROR_DETECTED_BY_DRIVER;
164    }
165    ++*p_counter;
166    if (*p_counter == 0) {
167        return PSA_ERROR_INSUFFICIENT_STORAGE;
168    }
169    shadow_counter = *p_counter;
170    *slot_number = *p_counter;
171    return PSA_SUCCESS;
172}
173
174/* Null import: do nothing, but pretend it worked. */
175#if defined(AT_LEAST_ONE_BUILTIN_KDF)
176static psa_status_t null_import(psa_drv_se_context_t *context,
177                                psa_key_slot_number_t slot_number,
178                                const psa_key_attributes_t *attributes,
179                                const uint8_t *data,
180                                size_t data_length,
181                                size_t *bits)
182{
183    (void) context;
184    (void) slot_number;
185    (void) attributes;
186    (void) data;
187    /* We're supposed to return a key size. Return one that's correct for
188     * plain data keys. */
189    *bits = PSA_BYTES_TO_BITS(data_length);
190    return PSA_SUCCESS;
191}
192#endif /* AT_LEAST_ONE_BUILTIN_KDF */
193
194/* Null generate: do nothing, but pretend it worked. */
195#if defined(AT_LEAST_ONE_BUILTIN_KDF)
196static psa_status_t null_generate(psa_drv_se_context_t *context,
197                                  psa_key_slot_number_t slot_number,
198                                  const psa_key_attributes_t *attributes,
199                                  uint8_t *pubkey,
200                                  size_t pubkey_size,
201                                  size_t *pubkey_length)
202{
203    (void) context;
204    (void) slot_number;
205    (void) attributes;
206
207    DRIVER_ASSERT_RETURN(*pubkey_length == 0);
208    if (!PSA_KEY_TYPE_IS_KEY_PAIR(psa_get_key_type(attributes))) {
209        DRIVER_ASSERT_RETURN(pubkey == NULL);
210        DRIVER_ASSERT_RETURN(pubkey_size == 0);
211    }
212
213    return PSA_SUCCESS;
214}
215#endif /* AT_LEAST_ONE_BUILTIN_KDF */
216
217/* Null destroy: do nothing, but pretend it worked. */
218static psa_status_t null_destroy(psa_drv_se_context_t *context,
219                                 void *persistent_data,
220                                 psa_key_slot_number_t slot_number)
221{
222    (void) context;
223    (void) persistent_data;
224    (void) slot_number;
225    return PSA_SUCCESS;
226}
227
228
229
230/****************************************************************/
231/* RAM-based test driver */
232/****************************************************************/
233
234#define RAM_MAX_KEY_SIZE 64
235typedef struct {
236    psa_key_lifetime_t lifetime;
237    psa_key_type_t type;
238    size_t bits;
239    uint8_t content[RAM_MAX_KEY_SIZE];
240} ram_slot_t;
241static ram_slot_t ram_slots[16];
242
243/* A type with at least ARRAY_LENGTH(ram_slots) bits, containing a
244 * bit vector indicating which slots are in use. */
245typedef uint16_t ram_slot_usage_t;
246
247static ram_slot_usage_t ram_shadow_slot_usage;
248
249static uint8_t ram_min_slot = 0;
250
251static void ram_slots_reset(void)
252{
253    memset(ram_slots, 0, sizeof(ram_slots));
254    ram_min_slot = 0;
255    ram_shadow_slot_usage = 0;
256}
257
258/* Common parts of key creation.
259 *
260 * In case of error, zero out ram_slots[slot_number]. But don't
261 * do that if the error is PSA_ERROR_DETECTED_BY_DRIVER: in this case
262 * you don't need to clean up (ram_slot_reset() will take care of it
263 * in the test case function's cleanup code) and it might be wrong
264 * (if slot_number is invalid).
265 */
266static psa_status_t ram_create_common(psa_drv_se_context_t *context,
267                                      psa_key_slot_number_t slot_number,
268                                      const psa_key_attributes_t *attributes,
269                                      size_t required_storage)
270{
271    (void) context;
272    DRIVER_ASSERT_RETURN(slot_number < ARRAY_LENGTH(ram_slots));
273
274    ram_slots[slot_number].lifetime = psa_get_key_lifetime(attributes);
275    ram_slots[slot_number].type = psa_get_key_type(attributes);
276    ram_slots[slot_number].bits = psa_get_key_bits(attributes);
277
278    if (required_storage > sizeof(ram_slots[slot_number].content)) {
279        memset(&ram_slots[slot_number], 0, sizeof(ram_slots[slot_number]));
280        return PSA_ERROR_INSUFFICIENT_STORAGE;
281    }
282
283    return PSA_SUCCESS;
284}
285
286/* This function does everything except actually generating key material.
287 * After calling it, you must copy the desired key material to
288 * ram_slots[slot_number].content. */
289static psa_status_t ram_fake_generate(psa_drv_se_context_t *context,
290                                      psa_key_slot_number_t slot_number,
291                                      const psa_key_attributes_t *attributes,
292                                      uint8_t *pubkey,
293                                      size_t pubkey_size,
294                                      size_t *pubkey_length)
295{
296    psa_status_t status;
297    size_t required_storage =
298        PSA_EXPORT_KEY_OUTPUT_SIZE(psa_get_key_type(attributes),
299                                   psa_get_key_bits(attributes));
300
301    DRIVER_ASSERT_RETURN(*pubkey_length == 0);
302    if (!PSA_KEY_TYPE_IS_KEY_PAIR(psa_get_key_type(attributes))) {
303        DRIVER_ASSERT_RETURN(pubkey == NULL);
304        DRIVER_ASSERT_RETURN(pubkey_size == 0);
305    }
306
307    status = ram_create_common(context, slot_number, attributes,
308                               required_storage);
309    return status;
310}
311
312static psa_status_t ram_import(psa_drv_se_context_t *context,
313                               psa_key_slot_number_t slot_number,
314                               const psa_key_attributes_t *attributes,
315                               const uint8_t *data,
316                               size_t data_length,
317                               size_t *bits)
318{
319    psa_key_type_t type = psa_get_key_type(attributes);
320    psa_status_t status = ram_create_common(context, slot_number, attributes,
321                                            data_length);
322    if (status != PSA_SUCCESS) {
323        return status;
324    }
325
326    /* The RAM driver only works for certain key types: raw keys,
327     * and ECC key pairs. This is true in particular of the bit-size
328     * calculation here. */
329    if (PSA_KEY_TYPE_IS_UNSTRUCTURED(type)) {
330        *bits = PSA_BYTES_TO_BITS(data_length);
331    } else if (PSA_KEY_TYPE_IS_ECC_KEY_PAIR(type)) {
332        *bits = ecc_curve_bits(PSA_KEY_TYPE_ECC_GET_FAMILY(type), data_length);
333        if (*bits == 0) {
334            return PSA_ERROR_DETECTED_BY_DRIVER;
335        }
336    } else {
337        memset(&ram_slots[slot_number], 0, sizeof(ram_slots[slot_number]));
338        return PSA_ERROR_NOT_SUPPORTED;
339    }
340
341    ram_slots[slot_number].bits = *bits;
342    memcpy(ram_slots[slot_number].content, data, data_length);
343
344    return PSA_SUCCESS;
345}
346
347static psa_status_t ram_export(psa_drv_se_context_t *context,
348                               psa_key_slot_number_t slot_number,
349                               uint8_t *data,
350                               size_t data_size,
351                               size_t *data_length)
352{
353    size_t actual_size;
354    (void) context;
355    DRIVER_ASSERT_RETURN(slot_number < ARRAY_LENGTH(ram_slots));
356    actual_size = PSA_BITS_TO_BYTES(ram_slots[slot_number].bits);
357    if (actual_size > data_size) {
358        return PSA_ERROR_BUFFER_TOO_SMALL;
359    }
360    *data_length = actual_size;
361    memcpy(data, ram_slots[slot_number].content, actual_size);
362    return PSA_SUCCESS;
363}
364
365static psa_status_t ram_export_public(psa_drv_se_context_t *context,
366                                      psa_key_slot_number_t slot_number,
367                                      uint8_t *data,
368                                      size_t data_size,
369                                      size_t *data_length)
370{
371    psa_status_t status;
372    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
373    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
374
375    (void) context;
376    DRIVER_ASSERT_RETURN(slot_number < ARRAY_LENGTH(ram_slots));
377    DRIVER_ASSERT_RETURN(
378        PSA_KEY_TYPE_IS_KEY_PAIR(ram_slots[slot_number].type));
379
380    psa_set_key_type(&attributes, ram_slots[slot_number].type);
381    status = psa_import_key(&attributes,
382                            ram_slots[slot_number].content,
383                            PSA_BITS_TO_BYTES(ram_slots[slot_number].bits),
384                            &key);
385    if (status != PSA_SUCCESS) {
386        return status;
387    }
388    status = psa_export_public_key(key, data, data_size, data_length);
389    psa_destroy_key(key);
390    return PSA_SUCCESS;
391}
392
393static psa_status_t ram_destroy(psa_drv_se_context_t *context,
394                                void *persistent_data,
395                                psa_key_slot_number_t slot_number)
396{
397    ram_slot_usage_t *slot_usage = persistent_data;
398    DRIVER_ASSERT_RETURN(context->persistent_data_size == sizeof(ram_slot_usage_t));
399    DRIVER_ASSERT_RETURN(slot_number < ARRAY_LENGTH(ram_slots));
400    memset(&ram_slots[slot_number], 0, sizeof(ram_slots[slot_number]));
401    *slot_usage &= ~(ram_slot_usage_t) (1 << slot_number);
402    ram_shadow_slot_usage = *slot_usage;
403    return PSA_SUCCESS;
404}
405
406static psa_status_t ram_allocate(psa_drv_se_context_t *context,
407                                 void *persistent_data,
408                                 const psa_key_attributes_t *attributes,
409                                 psa_key_creation_method_t method,
410                                 psa_key_slot_number_t *slot_number)
411{
412    ram_slot_usage_t *slot_usage = persistent_data;
413    (void) attributes;
414    (void) method;
415    DRIVER_ASSERT_RETURN(context->persistent_data_size == sizeof(ram_slot_usage_t));
416    for (*slot_number = ram_min_slot;
417         *slot_number < ARRAY_LENGTH(ram_slots);
418         ++(*slot_number)) {
419        if (!(*slot_usage & 1 << *slot_number)) {
420            ram_shadow_slot_usage = *slot_usage;
421            return PSA_SUCCESS;
422        }
423    }
424    return PSA_ERROR_INSUFFICIENT_STORAGE;
425}
426
427static psa_status_t ram_validate_slot_number(
428    psa_drv_se_context_t *context,
429    void *persistent_data,
430    const psa_key_attributes_t *attributes,
431    psa_key_creation_method_t method,
432    psa_key_slot_number_t slot_number)
433{
434    (void) context;
435    (void) persistent_data;
436    (void) attributes;
437    (void) method;
438    if (slot_number >= ARRAY_LENGTH(ram_slots)) {
439        return PSA_ERROR_INVALID_ARGUMENT;
440    }
441    return PSA_SUCCESS;
442}
443
444static psa_status_t ram_sign(psa_drv_se_context_t *context,
445                             psa_key_slot_number_t slot_number,
446                             psa_algorithm_t alg,
447                             const uint8_t *hash,
448                             size_t hash_length,
449                             uint8_t *signature,
450                             size_t signature_size,
451                             size_t *signature_length)
452{
453    ram_slot_t *slot;
454    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
455    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
456    psa_status_t status = PSA_ERROR_GENERIC_ERROR;
457
458    (void) context;
459    DRIVER_ASSERT_RETURN(slot_number < ARRAY_LENGTH(ram_slots));
460    slot = &ram_slots[slot_number];
461
462    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_HASH);
463    psa_set_key_algorithm(&attributes, alg);
464    psa_set_key_type(&attributes, slot->type);
465    DRIVER_ASSERT(psa_import_key(&attributes,
466                                 slot->content,
467                                 PSA_BITS_TO_BYTES(slot->bits),
468                                 &key) == PSA_SUCCESS);
469    status = psa_sign_hash(key, alg,
470                           hash, hash_length,
471                           signature, signature_size, signature_length);
472
473exit:
474    psa_destroy_key(key);
475    return status;
476}
477
478static psa_status_t ram_verify(psa_drv_se_context_t *context,
479                               psa_key_slot_number_t slot_number,
480                               psa_algorithm_t alg,
481                               const uint8_t *hash,
482                               size_t hash_length,
483                               const uint8_t *signature,
484                               size_t signature_length)
485{
486    ram_slot_t *slot;
487    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
488    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
489    psa_status_t status = PSA_ERROR_GENERIC_ERROR;
490
491    (void) context;
492    DRIVER_ASSERT_RETURN(slot_number < ARRAY_LENGTH(ram_slots));
493    slot = &ram_slots[slot_number];
494
495    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_VERIFY_HASH);
496    psa_set_key_algorithm(&attributes, alg);
497    psa_set_key_type(&attributes, slot->type);
498    DRIVER_ASSERT(psa_import_key(&attributes,
499                                 slot->content,
500                                 PSA_BITS_TO_BYTES(slot->bits),
501                                 &key) ==
502                  PSA_SUCCESS);
503    status = psa_verify_hash(key, alg,
504                             hash, hash_length,
505                             signature, signature_length);
506
507exit:
508    psa_destroy_key(key);
509    return status;
510}
511
512
513/****************************************************************/
514/* Other test helper functions */
515/****************************************************************/
516
517typedef enum {
518    SIGN_IN_SOFTWARE_AND_PARALLEL_CREATION,
519    SIGN_IN_DRIVER_AND_PARALLEL_CREATION,
520    SIGN_IN_DRIVER_THEN_EXPORT_PUBLIC,
521} sign_verify_method_t;
522
523/* Check that the attributes of a key reported by psa_get_key_attributes()
524 * are consistent with the attributes used when creating the key. */
525static int check_key_attributes(
526    mbedtls_svc_key_id_t key,
527    const psa_key_attributes_t *reference_attributes)
528{
529    int ok = 0;
530    psa_key_attributes_t actual_attributes = PSA_KEY_ATTRIBUTES_INIT;
531
532    PSA_ASSERT(psa_get_key_attributes(key, &actual_attributes));
533
534    TEST_ASSERT(mbedtls_svc_key_id_equal(
535                    psa_get_key_id(&actual_attributes),
536                    psa_get_key_id(reference_attributes)));
537    TEST_EQUAL(psa_get_key_lifetime(&actual_attributes),
538               psa_get_key_lifetime(reference_attributes));
539    TEST_EQUAL(psa_get_key_type(&actual_attributes),
540               psa_get_key_type(reference_attributes));
541    TEST_EQUAL(psa_get_key_usage_flags(&actual_attributes),
542               psa_get_key_usage_flags(reference_attributes));
543    TEST_EQUAL(psa_get_key_algorithm(&actual_attributes),
544               psa_get_key_algorithm(reference_attributes));
545    TEST_EQUAL(psa_get_key_enrollment_algorithm(&actual_attributes),
546               psa_get_key_enrollment_algorithm(reference_attributes));
547    if (psa_get_key_bits(reference_attributes) != 0) {
548        TEST_EQUAL(psa_get_key_bits(&actual_attributes),
549                   psa_get_key_bits(reference_attributes));
550    }
551
552    {
553        psa_key_slot_number_t actual_slot_number = 0xdeadbeef;
554        psa_key_slot_number_t desired_slot_number = 0xb90cc011;
555        psa_key_lifetime_t lifetime =
556            psa_get_key_lifetime(&actual_attributes);
557        psa_status_t status = psa_get_key_slot_number(&actual_attributes,
558                                                      &actual_slot_number);
559        if (PSA_KEY_LIFETIME_GET_LOCATION(lifetime) < MIN_DRIVER_LOCATION) {
560            /* The key is not in a secure element. */
561            TEST_EQUAL(status, PSA_ERROR_INVALID_ARGUMENT);
562        } else {
563            /* The key is in a secure element. If it had been created
564             * in a specific slot, check that it is reported there. */
565            PSA_ASSERT(status);
566            status = psa_get_key_slot_number(reference_attributes,
567                                             &desired_slot_number);
568            if (status == PSA_SUCCESS) {
569                TEST_EQUAL(desired_slot_number, actual_slot_number);
570            }
571        }
572    }
573    ok = 1;
574
575exit:
576    /*
577     * Actual key attributes may have been returned by psa_get_key_attributes()
578     * thus reset them as required.
579     */
580    psa_reset_key_attributes(&actual_attributes);
581
582    return ok;
583}
584
585/* Get the file UID corresponding to the specified location.
586 * If this changes, the storage format version must change.
587 * See psa_get_se_driver_its_file_uid() in psa_crypto_se.c.
588 */
589psa_storage_uid_t file_uid_for_location(psa_key_location_t location)
590{
591    if (location > PSA_MAX_SE_LOCATION) {
592        return 0;
593    }
594    return 0xfffffe00 + location;
595}
596
597/* Check that the persistent data of a driver has its expected content. */
598static int check_persistent_data(psa_key_location_t location,
599                                 const void *expected_data,
600                                 size_t size)
601{
602    psa_storage_uid_t uid = file_uid_for_location(location);
603    struct psa_storage_info_t info;
604    uint8_t *loaded = NULL;
605    int ok = 0;
606
607    PSA_ASSERT(psa_its_get_info(uid, &info));
608    TEST_CALLOC(loaded, info.size);
609    PSA_ASSERT(psa_its_get(uid, 0, info.size, loaded, NULL));
610    TEST_MEMORY_COMPARE(expected_data, size, loaded, info.size);
611    ok = 1;
612
613exit:
614    mbedtls_free(loaded);
615    return ok;
616}
617
618/* Check that no persistent data exists for the given location. */
619static int check_no_persistent_data(psa_key_location_t location)
620{
621    psa_storage_uid_t uid = file_uid_for_location(location);
622    struct psa_storage_info_t info;
623    int ok = 0;
624
625    TEST_EQUAL(psa_its_get_info(uid, &info), PSA_ERROR_DOES_NOT_EXIST);
626    ok = 1;
627
628exit:
629    return ok;
630}
631
632/* Check that a function's return status is "smoke-free", i.e. that
633 * it's an acceptable error code when calling an API function that operates
634 * on a key with potentially bogus parameters. */
635#if defined(AT_LEAST_ONE_BUILTIN_KDF)
636static int is_status_smoke_free(psa_status_t status)
637{
638    switch (status) {
639        case PSA_SUCCESS:
640        case PSA_ERROR_NOT_SUPPORTED:
641        case PSA_ERROR_NOT_PERMITTED:
642        case PSA_ERROR_BUFFER_TOO_SMALL:
643        case PSA_ERROR_INVALID_ARGUMENT:
644        case PSA_ERROR_INVALID_SIGNATURE:
645        case PSA_ERROR_INVALID_PADDING:
646            return 1;
647        default:
648            return 0;
649    }
650}
651#endif /* AT_LEAST_ONE_BUILTIN_KDF */
652
653#define SMOKE_ASSERT(expr)                    \
654    TEST_ASSERT(is_status_smoke_free(expr))
655
656/* Smoke test a key. There are mostly no wrong answers here since we pass
657 * mostly bogus parameters: the goal is to ensure that there is no memory
658 * corruption or crash. This test function is most useful when run under
659 * an environment with sanity checks such as ASan or MSan. */
660#if defined(AT_LEAST_ONE_BUILTIN_KDF)
661static int smoke_test_key(mbedtls_svc_key_id_t key)
662{
663    int ok = 0;
664    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
665    psa_mac_operation_t mac_operation = PSA_MAC_OPERATION_INIT;
666    psa_cipher_operation_t cipher_operation = PSA_CIPHER_OPERATION_INIT;
667    psa_key_derivation_operation_t derivation_operation =
668        PSA_KEY_DERIVATION_OPERATION_INIT;
669    uint8_t buffer[80]; /* large enough for a public key for ECDH */
670    size_t length;
671    mbedtls_svc_key_id_t key2 = MBEDTLS_SVC_KEY_ID_INIT;
672
673    SMOKE_ASSERT(psa_get_key_attributes(key, &attributes));
674
675    SMOKE_ASSERT(psa_export_key(key,
676                                buffer, sizeof(buffer), &length));
677    SMOKE_ASSERT(psa_export_public_key(key,
678                                       buffer, sizeof(buffer), &length));
679
680    SMOKE_ASSERT(psa_copy_key(key, &attributes, &key2));
681    if (!mbedtls_svc_key_id_is_null(key2)) {
682        PSA_ASSERT(psa_destroy_key(key2));
683    }
684
685    SMOKE_ASSERT(psa_mac_sign_setup(&mac_operation, key, PSA_ALG_CMAC));
686    PSA_ASSERT(psa_mac_abort(&mac_operation));
687    SMOKE_ASSERT(psa_mac_verify_setup(&mac_operation, key,
688                                      PSA_ALG_HMAC(PSA_ALG_SHA_256)));
689    PSA_ASSERT(psa_mac_abort(&mac_operation));
690
691    SMOKE_ASSERT(psa_cipher_encrypt_setup(&cipher_operation, key,
692                                          PSA_ALG_CTR));
693    PSA_ASSERT(psa_cipher_abort(&cipher_operation));
694    SMOKE_ASSERT(psa_cipher_decrypt_setup(&cipher_operation, key,
695                                          PSA_ALG_CTR));
696    PSA_ASSERT(psa_cipher_abort(&cipher_operation));
697
698    SMOKE_ASSERT(psa_aead_encrypt(key, PSA_ALG_CCM,
699                                  buffer, sizeof(buffer),
700                                  NULL, 0,
701                                  buffer, sizeof(buffer),
702                                  buffer, sizeof(buffer), &length));
703    SMOKE_ASSERT(psa_aead_decrypt(key, PSA_ALG_CCM,
704                                  buffer, sizeof(buffer),
705                                  NULL, 0,
706                                  buffer, sizeof(buffer),
707                                  buffer, sizeof(buffer), &length));
708
709    SMOKE_ASSERT(psa_sign_hash(key, PSA_ALG_ECDSA_ANY,
710                               buffer, 32,
711                               buffer, sizeof(buffer), &length));
712    SMOKE_ASSERT(psa_verify_hash(key, PSA_ALG_ECDSA_ANY,
713                                 buffer, 32,
714                                 buffer, sizeof(buffer)));
715
716    SMOKE_ASSERT(psa_asymmetric_encrypt(key, PSA_ALG_RSA_PKCS1V15_CRYPT,
717                                        buffer, 10, NULL, 0,
718                                        buffer, sizeof(buffer), &length));
719    SMOKE_ASSERT(psa_asymmetric_decrypt(key, PSA_ALG_RSA_PKCS1V15_CRYPT,
720                                        buffer, sizeof(buffer), NULL, 0,
721                                        buffer, sizeof(buffer), &length));
722
723#if defined(PSA_WANT_ALG_SHA_256)
724    /* Try the key in a plain key derivation. */
725    PSA_ASSERT(psa_key_derivation_setup(&derivation_operation,
726                                        PSA_ALG_HKDF(PSA_ALG_SHA_256)));
727    PSA_ASSERT(psa_key_derivation_input_bytes(&derivation_operation,
728                                              PSA_KEY_DERIVATION_INPUT_SALT,
729                                              NULL, 0));
730    SMOKE_ASSERT(psa_key_derivation_input_key(&derivation_operation,
731                                              PSA_KEY_DERIVATION_INPUT_SECRET,
732                                              key));
733    PSA_ASSERT(psa_key_derivation_abort(&derivation_operation));
734
735    /* If the key is asymmetric, try it in a key agreement, both as
736     * part of a derivation operation and standalone. */
737    if (psa_export_public_key(key, buffer, sizeof(buffer), &length) ==
738        PSA_SUCCESS) {
739        psa_algorithm_t alg =
740            PSA_ALG_KEY_AGREEMENT(PSA_ALG_ECDH,
741                                  PSA_ALG_HKDF(PSA_ALG_SHA_256));
742        PSA_ASSERT(psa_key_derivation_setup(&derivation_operation, alg));
743        PSA_ASSERT(psa_key_derivation_input_bytes(
744                       &derivation_operation, PSA_KEY_DERIVATION_INPUT_SALT,
745                       NULL, 0));
746        SMOKE_ASSERT(psa_key_derivation_key_agreement(
747                         &derivation_operation,
748                         PSA_KEY_DERIVATION_INPUT_SECRET,
749                         key, buffer, length));
750        PSA_ASSERT(psa_key_derivation_abort(&derivation_operation));
751
752        SMOKE_ASSERT(psa_raw_key_agreement(
753                         alg, key, buffer, length,
754                         buffer, sizeof(buffer), &length));
755    }
756#endif /* PSA_WANT_ALG_SHA_256 */
757
758    ok = 1;
759
760exit:
761    /*
762     * Key attributes may have been returned by psa_get_key_attributes()
763     * thus reset them as required.
764     */
765    psa_reset_key_attributes(&attributes);
766
767    return ok;
768}
769#endif /* AT_LEAST_ONE_BUILTIN_KDF */
770
771static void psa_purge_storage(void)
772{
773    /* The generic code in mbedtls_test_psa_purge_key_storage()
774     * (which is called by PSA_DONE()) doesn't take care of things that are
775     * specific to dynamic secure elements. */
776    psa_key_location_t location;
777    /* Purge the transaction file. */
778    psa_crypto_stop_transaction();
779    /* Purge driver persistent data. */
780    for (location = 0; location < PSA_MAX_SE_LOCATION; location++) {
781        psa_destroy_se_persistent_data(location);
782    }
783}
784
785/* END_HEADER */
786
787/* BEGIN_DEPENDENCIES
788 * depends_on:MBEDTLS_PSA_CRYPTO_SE_C
789 * END_DEPENDENCIES
790 */
791
792/* BEGIN_CASE */
793void register_one(int location, int version, int expected_status_arg)
794{
795    psa_status_t expected_status = expected_status_arg;
796    psa_drv_se_t driver;
797
798    memset(&driver, 0, sizeof(driver));
799    driver.hal_version = version;
800
801    TEST_EQUAL(psa_register_se_driver(location, &driver),
802               expected_status);
803
804    PSA_ASSERT(psa_crypto_init());
805
806exit:
807    PSA_DONE();
808}
809/* END_CASE */
810
811/* BEGIN_CASE */
812void register_twice(int count)
813{
814    psa_drv_se_t driver;
815    psa_key_location_t location;
816    psa_key_location_t max = MIN_DRIVER_LOCATION + count;
817
818    memset(&driver, 0, sizeof(driver));
819    driver.hal_version = PSA_DRV_SE_HAL_VERSION;
820
821    for (location = MIN_DRIVER_LOCATION; location < max; location++) {
822        PSA_ASSERT(psa_register_se_driver(location, &driver));
823    }
824    for (location = MIN_DRIVER_LOCATION; location < max; location++) {
825        TEST_EQUAL(psa_register_se_driver(location, &driver),
826                   PSA_ERROR_ALREADY_EXISTS);
827    }
828
829    PSA_ASSERT(psa_crypto_init());
830
831exit:
832    PSA_DONE();
833}
834/* END_CASE */
835
836/* BEGIN_CASE */
837void register_max()
838{
839    psa_drv_se_t driver;
840    psa_key_location_t location;
841    psa_key_location_t max = MIN_DRIVER_LOCATION + PSA_MAX_SE_DRIVERS;
842
843    memset(&driver, 0, sizeof(driver));
844    driver.hal_version = PSA_DRV_SE_HAL_VERSION;
845
846    for (location = MIN_DRIVER_LOCATION; location < max; location++) {
847        PSA_ASSERT(psa_register_se_driver(location, &driver));
848    }
849
850    TEST_EQUAL(psa_register_se_driver(location, &driver),
851               PSA_ERROR_INSUFFICIENT_MEMORY);
852
853    PSA_ASSERT(psa_crypto_init());
854
855exit:
856    PSA_DONE();
857}
858/* END_CASE */
859
860/* BEGIN_CASE */
861void key_creation_import_export(int lifetime_arg, int min_slot, int restart)
862{
863    psa_drv_se_t driver;
864    psa_drv_se_key_management_t key_management;
865    psa_key_lifetime_t lifetime = (psa_key_lifetime_t) lifetime_arg;
866    psa_key_location_t location = PSA_KEY_LIFETIME_GET_LOCATION(lifetime);
867    mbedtls_svc_key_id_t id = mbedtls_svc_key_id_make(1, 1);
868    mbedtls_svc_key_id_t returned_id = MBEDTLS_SVC_KEY_ID_INIT;
869    psa_key_handle_t handle;
870    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
871    const uint8_t key_material[3] = { 0xfa, 0xca, 0xde };
872    uint8_t exported[sizeof(key_material)];
873    size_t exported_length;
874
875    TEST_USES_KEY_ID(id);
876
877    memset(&driver, 0, sizeof(driver));
878    memset(&key_management, 0, sizeof(key_management));
879    driver.hal_version = PSA_DRV_SE_HAL_VERSION;
880    driver.key_management = &key_management;
881    driver.persistent_data_size = sizeof(ram_slot_usage_t);
882    key_management.p_allocate = ram_allocate;
883    key_management.p_import = ram_import;
884    key_management.p_destroy = ram_destroy;
885    key_management.p_export = ram_export;
886    ram_min_slot = min_slot;
887
888    PSA_ASSERT(psa_register_se_driver(location, &driver));
889    PSA_ASSERT(psa_crypto_init());
890
891    /* Create a key. */
892    psa_set_key_id(&attributes, id);
893    psa_set_key_lifetime(&attributes, lifetime);
894    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_EXPORT);
895    psa_set_key_type(&attributes, PSA_KEY_TYPE_RAW_DATA);
896    PSA_ASSERT(psa_import_key(&attributes,
897                              key_material, sizeof(key_material),
898                              &returned_id));
899
900    if (PSA_KEY_LIFETIME_IS_VOLATILE(lifetime)) {
901        /* For volatile keys, check no persistent data was created */
902        if (!check_no_persistent_data(location)) {
903            goto exit;
904        }
905    } else {
906        /* For persistent keys, check persistent data */
907        if (!check_persistent_data(location,
908                                   &ram_shadow_slot_usage,
909                                   sizeof(ram_shadow_slot_usage))) {
910            goto exit;
911        }
912    }
913
914    /* Test that the key was created in the expected slot. */
915    TEST_EQUAL(ram_slots[min_slot].type, PSA_KEY_TYPE_RAW_DATA);
916
917    /* Maybe restart, to check that the information is saved correctly. */
918    if (restart) {
919        mbedtls_psa_crypto_free();
920        PSA_ASSERT(psa_register_se_driver(location, &driver));
921        PSA_ASSERT(psa_crypto_init());
922
923        if (PSA_KEY_LIFETIME_IS_VOLATILE(lifetime)) {
924            /* Check that the PSA core has no knowledge of the volatile key */
925            TEST_ASSERT(psa_open_key(returned_id, &handle) ==
926                        PSA_ERROR_DOES_NOT_EXIST);
927
928            /* Drop data from our mockup driver */
929            ram_slots_reset();
930            ram_min_slot = min_slot;
931
932            /* Re-import key */
933            PSA_ASSERT(psa_import_key(&attributes,
934                                      key_material, sizeof(key_material),
935                                      &returned_id));
936        } else {
937            /* Check the persistent key file */
938            if (!check_persistent_data(location,
939                                       &ram_shadow_slot_usage,
940                                       sizeof(ram_shadow_slot_usage))) {
941                goto exit;
942            }
943        }
944    }
945
946    /* Test that the key was created in the expected slot. */
947    TEST_EQUAL(ram_slots[min_slot].type, PSA_KEY_TYPE_RAW_DATA);
948
949    /* Test the key attributes, including the reported slot number. */
950    psa_set_key_bits(&attributes,
951                     PSA_BYTES_TO_BITS(sizeof(key_material)));
952    psa_set_key_slot_number(&attributes, min_slot);
953
954    if (PSA_KEY_LIFETIME_IS_VOLATILE(lifetime)) {
955        attributes.id = returned_id;
956    } else {
957        psa_set_key_id(&attributes, returned_id);
958    }
959
960    if (!check_key_attributes(returned_id, &attributes)) {
961        goto exit;
962    }
963
964    /* Test the key data. */
965    PSA_ASSERT(psa_export_key(returned_id,
966                              exported, sizeof(exported),
967                              &exported_length));
968    TEST_MEMORY_COMPARE(key_material, sizeof(key_material),
969                        exported, exported_length);
970
971    PSA_ASSERT(psa_destroy_key(returned_id));
972    if (!check_persistent_data(location,
973                               &ram_shadow_slot_usage,
974                               sizeof(ram_shadow_slot_usage))) {
975        goto exit;
976    }
977    TEST_EQUAL(psa_open_key(returned_id, &handle),
978               PSA_ERROR_DOES_NOT_EXIST);
979
980    /* Test that the key has been erased from the designated slot. */
981    TEST_EQUAL(ram_slots[min_slot].type, 0);
982
983exit:
984    PSA_DONE();
985    ram_slots_reset();
986    psa_purge_storage();
987}
988/* END_CASE */
989
990/* BEGIN_CASE */
991void key_creation_in_chosen_slot(int slot_arg,
992                                 int restart,
993                                 int expected_status_arg)
994{
995    psa_key_slot_number_t wanted_slot = slot_arg;
996    psa_status_t expected_status = expected_status_arg;
997    psa_status_t status;
998    psa_drv_se_t driver;
999    psa_drv_se_key_management_t key_management;
1000    psa_key_lifetime_t lifetime = TEST_SE_PERSISTENT_LIFETIME;
1001    psa_key_location_t location = PSA_KEY_LIFETIME_GET_LOCATION(lifetime);
1002    mbedtls_svc_key_id_t id = mbedtls_svc_key_id_make(1, 1);
1003    mbedtls_svc_key_id_t returned_id;
1004    psa_key_handle_t handle;
1005    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
1006    const uint8_t key_material[3] = { 0xfa, 0xca, 0xde };
1007
1008    TEST_USES_KEY_ID(id);
1009
1010    memset(&driver, 0, sizeof(driver));
1011    memset(&key_management, 0, sizeof(key_management));
1012    driver.hal_version = PSA_DRV_SE_HAL_VERSION;
1013    driver.key_management = &key_management;
1014    driver.persistent_data_size = sizeof(ram_slot_usage_t);
1015    key_management.p_validate_slot_number = ram_validate_slot_number;
1016    key_management.p_import = ram_import;
1017    key_management.p_destroy = ram_destroy;
1018    key_management.p_export = ram_export;
1019
1020    PSA_ASSERT(psa_register_se_driver(location, &driver));
1021    PSA_ASSERT(psa_crypto_init());
1022
1023    /* Create a key. */
1024    psa_set_key_id(&attributes, id);
1025    psa_set_key_lifetime(&attributes, lifetime);
1026    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_EXPORT);
1027    psa_set_key_type(&attributes, PSA_KEY_TYPE_RAW_DATA);
1028    psa_set_key_slot_number(&attributes, wanted_slot);
1029    status = psa_import_key(&attributes,
1030                            key_material, sizeof(key_material),
1031                            &returned_id);
1032    TEST_EQUAL(status, expected_status);
1033
1034    if (status != PSA_SUCCESS) {
1035        goto exit;
1036    }
1037    if (!check_persistent_data(location,
1038                               &ram_shadow_slot_usage,
1039                               sizeof(ram_shadow_slot_usage))) {
1040        goto exit;
1041    }
1042
1043    /* Maybe restart, to check that the information is saved correctly. */
1044    if (restart) {
1045        mbedtls_psa_crypto_free();
1046        PSA_ASSERT(psa_register_se_driver(location, &driver));
1047        PSA_ASSERT(psa_crypto_init());
1048        if (!check_persistent_data(location,
1049                                   &ram_shadow_slot_usage,
1050                                   sizeof(ram_shadow_slot_usage))) {
1051            goto exit;
1052        }
1053    }
1054
1055    /* Test that the key was created in the expected slot. */
1056    TEST_EQUAL(ram_slots[wanted_slot].type, PSA_KEY_TYPE_RAW_DATA);
1057
1058    /* Test that the key is reported with the correct attributes,
1059     * including the expected slot. */
1060    PSA_ASSERT(psa_get_key_attributes(id, &attributes));
1061
1062    PSA_ASSERT(psa_destroy_key(id));
1063    if (!check_persistent_data(location,
1064                               &ram_shadow_slot_usage,
1065                               sizeof(ram_shadow_slot_usage))) {
1066        goto exit;
1067    }
1068    TEST_EQUAL(psa_open_key(id, &handle), PSA_ERROR_DOES_NOT_EXIST);
1069
1070exit:
1071    /*
1072     * Key attributes may have been returned by psa_get_key_attributes()
1073     * thus reset them as required.
1074     */
1075    psa_reset_key_attributes(&attributes);
1076
1077    PSA_DONE();
1078    ram_slots_reset();
1079    psa_purge_storage();
1080}
1081/* END_CASE */
1082
1083/* BEGIN_CASE depends_on:AT_LEAST_ONE_BUILTIN_KDF */
1084void import_key_smoke(int type_arg, int alg_arg,
1085                      data_t *key_material)
1086{
1087    psa_key_type_t type = type_arg;
1088    psa_algorithm_t alg = alg_arg;
1089    psa_drv_se_t driver;
1090    psa_drv_se_key_management_t key_management;
1091    psa_key_lifetime_t lifetime = TEST_SE_PERSISTENT_LIFETIME;
1092    psa_key_location_t location = PSA_KEY_LIFETIME_GET_LOCATION(lifetime);
1093    mbedtls_svc_key_id_t id = mbedtls_svc_key_id_make(1, 1);
1094    mbedtls_svc_key_id_t returned_id;
1095    psa_key_handle_t handle;
1096    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
1097
1098    TEST_USES_KEY_ID(id);
1099
1100    memset(&driver, 0, sizeof(driver));
1101    memset(&key_management, 0, sizeof(key_management));
1102    driver.hal_version = PSA_DRV_SE_HAL_VERSION;
1103    driver.key_management = &key_management;
1104    driver.persistent_data_size = sizeof(psa_key_slot_number_t);
1105    key_management.p_allocate = counter_allocate;
1106    key_management.p_import = null_import;
1107    key_management.p_destroy = null_destroy;
1108
1109    PSA_ASSERT(psa_register_se_driver(location, &driver));
1110    PSA_ASSERT(psa_crypto_init());
1111
1112    /* Create a key. */
1113    psa_set_key_id(&attributes, id);
1114    psa_set_key_lifetime(&attributes, lifetime);
1115    psa_set_key_usage_flags(&attributes,
1116                            PSA_KEY_USAGE_SIGN_HASH | PSA_KEY_USAGE_VERIFY_HASH |
1117                            PSA_KEY_USAGE_ENCRYPT | PSA_KEY_USAGE_DECRYPT |
1118                            PSA_KEY_USAGE_EXPORT);
1119    psa_set_key_algorithm(&attributes, alg);
1120    psa_set_key_type(&attributes, type);
1121    PSA_ASSERT(psa_import_key(&attributes,
1122                              key_material->x, key_material->len,
1123                              &returned_id));
1124    if (!check_persistent_data(location,
1125                               &shadow_counter, sizeof(shadow_counter))) {
1126        goto exit;
1127    }
1128
1129    /* Do stuff with the key. */
1130    if (!smoke_test_key(id)) {
1131        goto exit;
1132    }
1133
1134    /* Restart and try again. */
1135    mbedtls_psa_crypto_free();
1136    PSA_ASSERT(psa_register_se_driver(location, &driver));
1137    PSA_ASSERT(psa_crypto_init());
1138    if (!check_persistent_data(location,
1139                               &shadow_counter, sizeof(shadow_counter))) {
1140        goto exit;
1141    }
1142    if (!smoke_test_key(id)) {
1143        goto exit;
1144    }
1145
1146    /* We're done. */
1147    PSA_ASSERT(psa_destroy_key(id));
1148    if (!check_persistent_data(location,
1149                               &shadow_counter, sizeof(shadow_counter))) {
1150        goto exit;
1151    }
1152    TEST_EQUAL(psa_open_key(id, &handle), PSA_ERROR_DOES_NOT_EXIST);
1153
1154exit:
1155    PSA_DONE();
1156    counter_reset();
1157    psa_purge_storage();
1158}
1159/* END_CASE */
1160
1161/* BEGIN_CASE */
1162void generate_key_not_supported(int type_arg, int bits_arg)
1163{
1164    psa_key_type_t type = type_arg;
1165    size_t bits = bits_arg;
1166    psa_drv_se_t driver;
1167    psa_drv_se_key_management_t key_management;
1168    psa_key_lifetime_t lifetime = TEST_SE_PERSISTENT_LIFETIME;
1169    psa_key_location_t location = PSA_KEY_LIFETIME_GET_LOCATION(lifetime);
1170    mbedtls_svc_key_id_t id = mbedtls_svc_key_id_make(1, 1);
1171    mbedtls_svc_key_id_t returned_id;
1172    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
1173
1174    TEST_USES_KEY_ID(id);
1175
1176    memset(&driver, 0, sizeof(driver));
1177    memset(&key_management, 0, sizeof(key_management));
1178    driver.hal_version = PSA_DRV_SE_HAL_VERSION;
1179    driver.key_management = &key_management;
1180    driver.persistent_data_size = sizeof(psa_key_slot_number_t);
1181    key_management.p_allocate = counter_allocate;
1182    /* No p_generate method */
1183
1184    PSA_ASSERT(psa_register_se_driver(location, &driver));
1185    PSA_ASSERT(psa_crypto_init());
1186
1187    psa_set_key_id(&attributes, id);
1188    psa_set_key_lifetime(&attributes, lifetime);
1189    psa_set_key_type(&attributes, type);
1190    psa_set_key_bits(&attributes, bits);
1191    TEST_EQUAL(psa_generate_key(&attributes, &returned_id),
1192               PSA_ERROR_NOT_SUPPORTED);
1193
1194exit:
1195    PSA_DONE();
1196    counter_reset();
1197    psa_purge_storage();
1198}
1199/* END_CASE */
1200
1201/* BEGIN_CASE depends_on:AT_LEAST_ONE_BUILTIN_KDF */
1202void generate_key_smoke(int type_arg, int bits_arg, int alg_arg)
1203{
1204    psa_key_type_t type = type_arg;
1205    psa_key_bits_t bits = bits_arg;
1206    psa_algorithm_t alg = alg_arg;
1207    psa_drv_se_t driver;
1208    psa_drv_se_key_management_t key_management;
1209    psa_key_lifetime_t lifetime = TEST_SE_PERSISTENT_LIFETIME;
1210    psa_key_location_t location = PSA_KEY_LIFETIME_GET_LOCATION(lifetime);
1211    mbedtls_svc_key_id_t id = mbedtls_svc_key_id_make(1, 1);
1212    mbedtls_svc_key_id_t returned_id;
1213    psa_key_handle_t handle;
1214    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
1215
1216    TEST_USES_KEY_ID(id);
1217
1218    memset(&driver, 0, sizeof(driver));
1219    memset(&key_management, 0, sizeof(key_management));
1220    driver.hal_version = PSA_DRV_SE_HAL_VERSION;
1221    driver.key_management = &key_management;
1222    driver.persistent_data_size = sizeof(psa_key_slot_number_t);
1223    key_management.p_allocate = counter_allocate;
1224    key_management.p_generate = null_generate;
1225    key_management.p_destroy = null_destroy;
1226
1227    PSA_ASSERT(psa_register_se_driver(location, &driver));
1228    PSA_ASSERT(psa_crypto_init());
1229
1230    /* Create a key. */
1231    psa_set_key_id(&attributes, id);
1232    psa_set_key_lifetime(&attributes, lifetime);
1233    psa_set_key_usage_flags(&attributes,
1234                            PSA_KEY_USAGE_SIGN_HASH | PSA_KEY_USAGE_VERIFY_HASH |
1235                            PSA_KEY_USAGE_ENCRYPT | PSA_KEY_USAGE_DECRYPT |
1236                            PSA_KEY_USAGE_EXPORT);
1237    psa_set_key_algorithm(&attributes, alg);
1238    psa_set_key_type(&attributes, type);
1239    psa_set_key_bits(&attributes, bits);
1240    PSA_ASSERT(psa_generate_key(&attributes, &returned_id));
1241    if (!check_persistent_data(location,
1242                               &shadow_counter, sizeof(shadow_counter))) {
1243        goto exit;
1244    }
1245
1246    /* Do stuff with the key. */
1247    if (!smoke_test_key(id)) {
1248        goto exit;
1249    }
1250
1251    /* Restart and try again. */
1252    mbedtls_psa_crypto_free();
1253    PSA_ASSERT(psa_register_se_driver(location, &driver));
1254    PSA_ASSERT(psa_crypto_init());
1255    if (!check_persistent_data(location,
1256                               &shadow_counter, sizeof(shadow_counter))) {
1257        goto exit;
1258    }
1259    if (!smoke_test_key(id)) {
1260        goto exit;
1261    }
1262
1263    /* We're done. */
1264    PSA_ASSERT(psa_destroy_key(id));
1265    if (!check_persistent_data(location,
1266                               &shadow_counter, sizeof(shadow_counter))) {
1267        goto exit;
1268    }
1269    TEST_EQUAL(psa_open_key(id, &handle), PSA_ERROR_DOES_NOT_EXIST);
1270
1271exit:
1272    PSA_DONE();
1273    counter_reset();
1274    psa_purge_storage();
1275}
1276/* END_CASE */
1277
1278/* BEGIN_CASE */
1279void sign_verify(int flow,
1280                 int type_arg, int alg_arg,
1281                 int bits_arg, data_t *key_material,
1282                 data_t *input)
1283{
1284    psa_key_type_t type = type_arg;
1285    psa_algorithm_t alg = alg_arg;
1286    size_t bits = bits_arg;
1287    /* Pass bits=0 to import, bits>0 to fake-generate */
1288    int generating = (bits != 0);
1289
1290    psa_drv_se_t driver;
1291    psa_drv_se_key_management_t key_management;
1292    psa_drv_se_asymmetric_t asymmetric;
1293
1294    psa_key_lifetime_t lifetime = TEST_SE_PERSISTENT_LIFETIME;
1295    psa_key_location_t location = PSA_KEY_LIFETIME_GET_LOCATION(lifetime);
1296    mbedtls_svc_key_id_t id = mbedtls_svc_key_id_make(1, 1);
1297    mbedtls_svc_key_id_t returned_id;
1298    mbedtls_svc_key_id_t sw_key = MBEDTLS_SVC_KEY_ID_INIT;
1299    psa_key_attributes_t sw_attributes = PSA_KEY_ATTRIBUTES_INIT;
1300    psa_key_attributes_t drv_attributes = PSA_KEY_ATTRIBUTES_INIT;
1301    uint8_t signature[PSA_SIGNATURE_MAX_SIZE];
1302    size_t signature_length;
1303
1304    TEST_USES_KEY_ID(id);
1305
1306    memset(&driver, 0, sizeof(driver));
1307    memset(&key_management, 0, sizeof(key_management));
1308    memset(&asymmetric, 0, sizeof(asymmetric));
1309    driver.hal_version = PSA_DRV_SE_HAL_VERSION;
1310    driver.key_management = &key_management;
1311    driver.asymmetric = &asymmetric;
1312    driver.persistent_data_size = sizeof(ram_slot_usage_t);
1313    key_management.p_allocate = ram_allocate;
1314    key_management.p_destroy = ram_destroy;
1315    if (generating) {
1316        key_management.p_generate = ram_fake_generate;
1317    } else {
1318        key_management.p_import = ram_import;
1319    }
1320    switch (flow) {
1321        case SIGN_IN_SOFTWARE_AND_PARALLEL_CREATION:
1322            break;
1323        case SIGN_IN_DRIVER_AND_PARALLEL_CREATION:
1324            asymmetric.p_sign = ram_sign;
1325            break;
1326        case SIGN_IN_DRIVER_THEN_EXPORT_PUBLIC:
1327            asymmetric.p_sign = ram_sign;
1328            key_management.p_export_public = ram_export_public;
1329            break;
1330        default:
1331            TEST_FAIL("unsupported flow (should be SIGN_IN_xxx)");
1332            break;
1333    }
1334    asymmetric.p_verify = ram_verify;
1335
1336    PSA_ASSERT(psa_register_se_driver(location, &driver));
1337    PSA_ASSERT(psa_crypto_init());
1338
1339    /* Prepare to create two keys with the same key material: a transparent
1340     * key, and one that goes through the driver. */
1341    psa_set_key_usage_flags(&sw_attributes,
1342                            PSA_KEY_USAGE_SIGN_HASH | PSA_KEY_USAGE_VERIFY_HASH);
1343    psa_set_key_algorithm(&sw_attributes, alg);
1344    psa_set_key_type(&sw_attributes, type);
1345    drv_attributes = sw_attributes;
1346    psa_set_key_id(&drv_attributes, id);
1347    psa_set_key_lifetime(&drv_attributes, lifetime);
1348
1349    /* Create the key in the driver. */
1350    if (generating) {
1351        psa_set_key_bits(&drv_attributes, bits);
1352        PSA_ASSERT(psa_generate_key(&drv_attributes, &returned_id));
1353        /* Since we called a generate method that does not actually
1354         * generate material, store the desired result of generation in
1355         * the mock secure element storage. */
1356        PSA_ASSERT(psa_get_key_attributes(id, &drv_attributes));
1357        TEST_EQUAL(key_material->len, PSA_BITS_TO_BYTES(bits));
1358        memcpy(ram_slots[ram_min_slot].content, key_material->x,
1359               key_material->len);
1360    } else {
1361        PSA_ASSERT(psa_import_key(&drv_attributes,
1362                                  key_material->x, key_material->len,
1363                                  &returned_id));
1364    }
1365
1366    /* Either import the same key in software, or export the driver's
1367     * public key and import that. */
1368    switch (flow) {
1369        case SIGN_IN_SOFTWARE_AND_PARALLEL_CREATION:
1370        case SIGN_IN_DRIVER_AND_PARALLEL_CREATION:
1371            PSA_ASSERT(psa_import_key(&sw_attributes,
1372                                      key_material->x, key_material->len,
1373                                      &sw_key));
1374            break;
1375        case SIGN_IN_DRIVER_THEN_EXPORT_PUBLIC:
1376        {
1377            uint8_t public_key[PSA_KEY_EXPORT_ECC_PUBLIC_KEY_MAX_SIZE(PSA_VENDOR_ECC_MAX_CURVE_BITS)
1378            ];
1379            size_t public_key_length;
1380            PSA_ASSERT(psa_export_public_key(id,
1381                                             public_key, sizeof(public_key),
1382                                             &public_key_length));
1383            psa_set_key_type(&sw_attributes,
1384                             PSA_KEY_TYPE_PUBLIC_KEY_OF_KEY_PAIR(type));
1385            PSA_ASSERT(psa_import_key(&sw_attributes,
1386                                      public_key, public_key_length,
1387                                      &sw_key));
1388            break;
1389        }
1390    }
1391
1392    /* Sign with the chosen key. */
1393    switch (flow) {
1394        case SIGN_IN_DRIVER_AND_PARALLEL_CREATION:
1395        case SIGN_IN_DRIVER_THEN_EXPORT_PUBLIC:
1396            PSA_ASSERT_VIA_DRIVER(
1397                psa_sign_hash(id, alg,
1398                              input->x, input->len,
1399                              signature, sizeof(signature),
1400                              &signature_length),
1401                PSA_SUCCESS);
1402            break;
1403        case SIGN_IN_SOFTWARE_AND_PARALLEL_CREATION:
1404            PSA_ASSERT(psa_sign_hash(sw_key, alg,
1405                                     input->x, input->len,
1406                                     signature, sizeof(signature),
1407                                     &signature_length));
1408            break;
1409    }
1410
1411    /* Verify with both keys. */
1412    PSA_ASSERT(psa_verify_hash(sw_key, alg,
1413                               input->x, input->len,
1414                               signature, signature_length));
1415    PSA_ASSERT_VIA_DRIVER(
1416        psa_verify_hash(id, alg,
1417                        input->x, input->len,
1418                        signature, signature_length),
1419        PSA_SUCCESS);
1420
1421    /* Change the signature and verify again. */
1422    signature[0] ^= 1;
1423    TEST_EQUAL(psa_verify_hash(sw_key, alg,
1424                               input->x, input->len,
1425                               signature, signature_length),
1426               PSA_ERROR_INVALID_SIGNATURE);
1427    PSA_ASSERT_VIA_DRIVER(
1428        psa_verify_hash(id, alg,
1429                        input->x, input->len,
1430                        signature, signature_length),
1431        PSA_ERROR_INVALID_SIGNATURE);
1432
1433exit:
1434    /*
1435     * Driver key attributes may have been returned by psa_get_key_attributes()
1436     * thus reset them as required.
1437     */
1438    psa_reset_key_attributes(&drv_attributes);
1439
1440    psa_destroy_key(id);
1441    psa_destroy_key(sw_key);
1442    PSA_DONE();
1443    ram_slots_reset();
1444    psa_purge_storage();
1445}
1446/* END_CASE */
1447
1448/* BEGIN_CASE */
1449void register_key_smoke_test(int lifetime_arg,
1450                             int owner_id_arg,
1451                             int id_arg,
1452                             int validate,
1453                             int expected_status_arg)
1454{
1455    psa_key_lifetime_t lifetime = lifetime_arg;
1456    psa_key_location_t location = PSA_KEY_LIFETIME_GET_LOCATION(lifetime);
1457    psa_status_t expected_status = expected_status_arg;
1458    psa_drv_se_t driver;
1459    psa_drv_se_key_management_t key_management;
1460    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
1461    mbedtls_svc_key_id_t id = mbedtls_svc_key_id_make(owner_id_arg, id_arg);
1462    psa_key_handle_t handle;
1463    size_t bit_size = 48;
1464    psa_key_slot_number_t wanted_slot = 0x123456789;
1465    psa_status_t status;
1466
1467    TEST_USES_KEY_ID(id);
1468
1469    memset(&driver, 0, sizeof(driver));
1470    driver.hal_version = PSA_DRV_SE_HAL_VERSION;
1471    memset(&key_management, 0, sizeof(key_management));
1472    driver.key_management = &key_management;
1473    key_management.p_destroy = null_destroy;
1474    if (validate >= 0) {
1475        key_management.p_validate_slot_number = validate_slot_number_as_directed;
1476        validate_slot_number_directions.slot_number = wanted_slot;
1477        validate_slot_number_directions.method = PSA_KEY_CREATION_REGISTER;
1478        validate_slot_number_directions.status =
1479            (validate > 0 ? PSA_SUCCESS : PSA_ERROR_NOT_PERMITTED);
1480    }
1481
1482    mbedtls_test_set_step(1);
1483    PSA_ASSERT(psa_register_se_driver(MIN_DRIVER_LOCATION, &driver));
1484    PSA_ASSERT(psa_crypto_init());
1485
1486    psa_set_key_id(&attributes, id);
1487    psa_set_key_lifetime(&attributes, lifetime);
1488    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_EXPORT);
1489    psa_set_key_type(&attributes, PSA_KEY_TYPE_RAW_DATA);
1490    psa_set_key_bits(&attributes, bit_size);
1491    psa_set_key_slot_number(&attributes, wanted_slot);
1492
1493    status = mbedtls_psa_register_se_key(&attributes);
1494    TEST_EQUAL(status, expected_status);
1495
1496    if (status != PSA_SUCCESS) {
1497        goto exit;
1498    }
1499
1500    /* Test that the key exists and has the expected attributes. */
1501    if (!check_key_attributes(id, &attributes)) {
1502        goto exit;
1503    }
1504
1505#if defined(MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER)
1506    mbedtls_svc_key_id_t invalid_id =
1507        mbedtls_svc_key_id_make(owner_id_arg + 1, id_arg);
1508    TEST_EQUAL(psa_open_key(invalid_id, &handle), PSA_ERROR_DOES_NOT_EXIST);
1509#endif
1510
1511    PSA_ASSERT(psa_purge_key(id));
1512
1513    /* Restart and try again. */
1514    mbedtls_test_set_step(2);
1515    PSA_SESSION_DONE();
1516    PSA_ASSERT(psa_register_se_driver(location, &driver));
1517    PSA_ASSERT(psa_crypto_init());
1518    if (!check_key_attributes(id, &attributes)) {
1519        goto exit;
1520    }
1521    /* This time, destroy the key. */
1522    PSA_ASSERT(psa_destroy_key(id));
1523    TEST_EQUAL(psa_open_key(id, &handle), PSA_ERROR_DOES_NOT_EXIST);
1524
1525exit:
1526    psa_reset_key_attributes(&attributes);
1527    psa_destroy_key(id);
1528    PSA_DONE();
1529    psa_purge_storage();
1530    memset(&validate_slot_number_directions, 0,
1531           sizeof(validate_slot_number_directions));
1532}
1533/* END_CASE */
1534