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