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