1 /** Code to exercise a PSA key object, i.e. validate that it seems well-formed
2  * and can do what it is supposed to do.
3  */
4 
5 /*
6  *  Copyright The Mbed TLS Contributors
7  *  SPDX-License-Identifier: Apache-2.0
8  *
9  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
10  *  not use this file except in compliance with the License.
11  *  You may obtain a copy of the License at
12  *
13  *  http://www.apache.org/licenses/LICENSE-2.0
14  *
15  *  Unless required by applicable law or agreed to in writing, software
16  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
17  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  *  See the License for the specific language governing permissions and
19  *  limitations under the License.
20  */
21 
22 #include <test/helpers.h>
23 #include <test/macros.h>
24 #include <test/psa_exercise_key.h>
25 
26 #if defined(MBEDTLS_PSA_CRYPTO_C)
27 
28 #include <mbedtls/asn1.h>
29 #include <psa/crypto.h>
30 
31 #include <test/asn1_helpers.h>
32 #include <test/psa_crypto_helpers.h>
33 
34 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
lifetime_is_dynamic_secure_element(psa_key_lifetime_t lifetime)35 static int lifetime_is_dynamic_secure_element( psa_key_lifetime_t lifetime )
36 {
37     return( PSA_KEY_LIFETIME_GET_LOCATION( lifetime ) !=
38             PSA_KEY_LOCATION_LOCAL_STORAGE );
39 }
40 #endif
41 
check_key_attributes_sanity(mbedtls_svc_key_id_t key)42 static int check_key_attributes_sanity( mbedtls_svc_key_id_t key )
43 {
44     int ok = 0;
45     psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
46     psa_key_lifetime_t lifetime;
47     mbedtls_svc_key_id_t id;
48     psa_key_type_t type;
49     size_t bits;
50 
51     PSA_ASSERT( psa_get_key_attributes( key, &attributes ) );
52     lifetime = psa_get_key_lifetime( &attributes );
53     id = psa_get_key_id( &attributes );
54     type = psa_get_key_type( &attributes );
55     bits = psa_get_key_bits( &attributes );
56 
57     /* Persistence */
58     if( PSA_KEY_LIFETIME_IS_VOLATILE( lifetime ) )
59     {
60         TEST_ASSERT(
61             ( PSA_KEY_ID_VOLATILE_MIN <=
62               MBEDTLS_SVC_KEY_ID_GET_KEY_ID( id ) ) &&
63             ( MBEDTLS_SVC_KEY_ID_GET_KEY_ID( id ) <=
64               PSA_KEY_ID_VOLATILE_MAX ) );
65     }
66     else
67     {
68         TEST_ASSERT(
69             ( PSA_KEY_ID_USER_MIN <= MBEDTLS_SVC_KEY_ID_GET_KEY_ID( id ) ) &&
70             ( MBEDTLS_SVC_KEY_ID_GET_KEY_ID( id ) <= PSA_KEY_ID_USER_MAX ) );
71     }
72 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
73     /* randomly-generated 64-bit constant, should never appear in test data */
74     psa_key_slot_number_t slot_number = 0xec94d4a5058a1a21;
75     psa_status_t status = psa_get_key_slot_number( &attributes, &slot_number );
76     if( lifetime_is_dynamic_secure_element( lifetime ) )
77     {
78         /* Mbed Crypto currently always exposes the slot number to
79          * applications. This is not mandated by the PSA specification
80          * and may change in future versions. */
81         TEST_EQUAL( status, 0 );
82         TEST_ASSERT( slot_number != 0xec94d4a5058a1a21 );
83     }
84     else
85     {
86         TEST_EQUAL( status, PSA_ERROR_INVALID_ARGUMENT );
87     }
88 #endif
89 
90     /* Type and size */
91     TEST_ASSERT( type != 0 );
92     TEST_ASSERT( bits != 0 );
93     TEST_ASSERT( bits <= PSA_MAX_KEY_BITS );
94     if( PSA_KEY_TYPE_IS_UNSTRUCTURED( type ) )
95         TEST_ASSERT( bits % 8 == 0 );
96 
97     /* MAX macros concerning specific key types */
98     if( PSA_KEY_TYPE_IS_ECC( type ) )
99         TEST_ASSERT( bits <= PSA_VENDOR_ECC_MAX_CURVE_BITS );
100     else if( PSA_KEY_TYPE_IS_RSA( type ) )
101         TEST_ASSERT( bits <= PSA_VENDOR_RSA_MAX_KEY_BITS );
102     TEST_ASSERT( PSA_BLOCK_CIPHER_BLOCK_LENGTH( type ) <= PSA_BLOCK_CIPHER_BLOCK_MAX_SIZE );
103 
104     ok = 1;
105 
106 exit:
107     /*
108      * Key attributes may have been returned by psa_get_key_attributes()
109      * thus reset them as required.
110      */
111     psa_reset_key_attributes( &attributes );
112 
113     return( ok );
114 }
115 
exercise_mac_key(mbedtls_svc_key_id_t key,psa_key_usage_t usage,psa_algorithm_t alg)116 static int exercise_mac_key( mbedtls_svc_key_id_t key,
117                              psa_key_usage_t usage,
118                              psa_algorithm_t alg )
119 {
120     psa_mac_operation_t operation = PSA_MAC_OPERATION_INIT;
121     const unsigned char input[] = "foo";
122     unsigned char mac[PSA_MAC_MAX_SIZE] = {0};
123     size_t mac_length = sizeof( mac );
124 
125     /* Convert wildcard algorithm to exercisable algorithm */
126     if( alg & PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG )
127     {
128         alg = PSA_ALG_TRUNCATED_MAC( alg, PSA_MAC_TRUNCATED_LENGTH( alg ) );
129     }
130 
131     if( usage & PSA_KEY_USAGE_SIGN_HASH )
132     {
133         PSA_ASSERT( psa_mac_sign_setup( &operation, key, alg ) );
134         PSA_ASSERT( psa_mac_update( &operation,
135                                     input, sizeof( input ) ) );
136         PSA_ASSERT( psa_mac_sign_finish( &operation,
137                                          mac, sizeof( mac ),
138                                          &mac_length ) );
139     }
140 
141     if( usage & PSA_KEY_USAGE_VERIFY_HASH )
142     {
143         psa_status_t verify_status =
144             ( usage & PSA_KEY_USAGE_SIGN_HASH ?
145               PSA_SUCCESS :
146               PSA_ERROR_INVALID_SIGNATURE );
147         PSA_ASSERT( psa_mac_verify_setup( &operation, key, alg ) );
148         PSA_ASSERT( psa_mac_update( &operation,
149                                     input, sizeof( input ) ) );
150         TEST_EQUAL( psa_mac_verify_finish( &operation, mac, mac_length ),
151                     verify_status );
152     }
153 
154     return( 1 );
155 
156 exit:
157     psa_mac_abort( &operation );
158     return( 0 );
159 }
160 
exercise_cipher_key(mbedtls_svc_key_id_t key,psa_key_usage_t usage,psa_algorithm_t alg)161 static int exercise_cipher_key( mbedtls_svc_key_id_t key,
162                                 psa_key_usage_t usage,
163                                 psa_algorithm_t alg )
164 {
165     psa_cipher_operation_t operation = PSA_CIPHER_OPERATION_INIT;
166     unsigned char iv[16] = {0};
167     size_t iv_length = sizeof( iv );
168     const unsigned char plaintext[16] = "Hello, world...";
169     unsigned char ciphertext[32] = "(wabblewebblewibblewobblewubble)";
170     size_t ciphertext_length = sizeof( ciphertext );
171     unsigned char decrypted[sizeof( ciphertext )];
172     size_t part_length;
173 
174     if( usage & PSA_KEY_USAGE_ENCRYPT )
175     {
176         PSA_ASSERT( psa_cipher_encrypt_setup( &operation, key, alg ) );
177         PSA_ASSERT( psa_cipher_generate_iv( &operation,
178                                             iv, sizeof( iv ),
179                                             &iv_length ) );
180         PSA_ASSERT( psa_cipher_update( &operation,
181                                        plaintext, sizeof( plaintext ),
182                                        ciphertext, sizeof( ciphertext ),
183                                        &ciphertext_length ) );
184         PSA_ASSERT( psa_cipher_finish( &operation,
185                                        ciphertext + ciphertext_length,
186                                        sizeof( ciphertext ) - ciphertext_length,
187                                        &part_length ) );
188         ciphertext_length += part_length;
189     }
190 
191     if( usage & PSA_KEY_USAGE_DECRYPT )
192     {
193         psa_status_t status;
194         int maybe_invalid_padding = 0;
195         if( ! ( usage & PSA_KEY_USAGE_ENCRYPT ) )
196         {
197             psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
198             PSA_ASSERT( psa_get_key_attributes( key, &attributes ) );
199             /* This should be PSA_CIPHER_GET_IV_SIZE but the API doesn't
200              * have this macro yet. */
201             iv_length = PSA_BLOCK_CIPHER_BLOCK_LENGTH(
202                 psa_get_key_type( &attributes ) );
203             maybe_invalid_padding = ! PSA_ALG_IS_STREAM_CIPHER( alg );
204             psa_reset_key_attributes( &attributes );
205         }
206         PSA_ASSERT( psa_cipher_decrypt_setup( &operation, key, alg ) );
207         PSA_ASSERT( psa_cipher_set_iv( &operation,
208                                        iv, iv_length ) );
209         PSA_ASSERT( psa_cipher_update( &operation,
210                                        ciphertext, ciphertext_length,
211                                        decrypted, sizeof( decrypted ),
212                                        &part_length ) );
213         status = psa_cipher_finish( &operation,
214                                     decrypted + part_length,
215                                     sizeof( decrypted ) - part_length,
216                                     &part_length );
217         /* For a stream cipher, all inputs are valid. For a block cipher,
218          * if the input is some aribtrary data rather than an actual
219          ciphertext, a padding error is likely.  */
220         if( maybe_invalid_padding )
221             TEST_ASSERT( status == PSA_SUCCESS ||
222                          status == PSA_ERROR_INVALID_PADDING );
223         else
224             PSA_ASSERT( status );
225     }
226 
227     return( 1 );
228 
229 exit:
230     psa_cipher_abort( &operation );
231     return( 0 );
232 }
233 
exercise_aead_key(mbedtls_svc_key_id_t key,psa_key_usage_t usage,psa_algorithm_t alg)234 static int exercise_aead_key( mbedtls_svc_key_id_t key,
235                               psa_key_usage_t usage,
236                               psa_algorithm_t alg )
237 {
238     unsigned char nonce[16] = {0};
239     size_t nonce_length = sizeof( nonce );
240     unsigned char plaintext[16] = "Hello, world...";
241     unsigned char ciphertext[48] = "(wabblewebblewibblewobblewubble)";
242     size_t ciphertext_length = sizeof( ciphertext );
243     size_t plaintext_length = sizeof( ciphertext );
244 
245     /* Convert wildcard algorithm to exercisable algorithm */
246     if( alg & PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG )
247     {
248         alg = PSA_ALG_AEAD_WITH_SHORTENED_TAG( alg, PSA_ALG_AEAD_GET_TAG_LENGTH( alg ) );
249     }
250 
251     /* Default IV length for AES-GCM is 12 bytes */
252     if( PSA_ALG_AEAD_WITH_SHORTENED_TAG( alg, 0 ) ==
253         PSA_ALG_AEAD_WITH_SHORTENED_TAG( PSA_ALG_GCM, 0 ) )
254     {
255         nonce_length = 12;
256     }
257 
258     /* IV length for CCM needs to be between 7 and 13 bytes */
259     if( PSA_ALG_AEAD_WITH_SHORTENED_TAG( alg, 0 ) ==
260         PSA_ALG_AEAD_WITH_SHORTENED_TAG( PSA_ALG_CCM, 0 ) )
261     {
262         nonce_length = 12;
263     }
264 
265     if( usage & PSA_KEY_USAGE_ENCRYPT )
266     {
267         PSA_ASSERT( psa_aead_encrypt( key, alg,
268                                       nonce, nonce_length,
269                                       NULL, 0,
270                                       plaintext, sizeof( plaintext ),
271                                       ciphertext, sizeof( ciphertext ),
272                                       &ciphertext_length ) );
273     }
274 
275     if( usage & PSA_KEY_USAGE_DECRYPT )
276     {
277         psa_status_t verify_status =
278             ( usage & PSA_KEY_USAGE_ENCRYPT ?
279               PSA_SUCCESS :
280               PSA_ERROR_INVALID_SIGNATURE );
281         TEST_EQUAL( psa_aead_decrypt( key, alg,
282                                       nonce, nonce_length,
283                                       NULL, 0,
284                                       ciphertext, ciphertext_length,
285                                       plaintext, sizeof( plaintext ),
286                                       &plaintext_length ),
287                     verify_status );
288     }
289 
290     return( 1 );
291 
292 exit:
293     return( 0 );
294 }
295 
exercise_signature_key(mbedtls_svc_key_id_t key,psa_key_usage_t usage,psa_algorithm_t alg)296 static int exercise_signature_key( mbedtls_svc_key_id_t key,
297                                    psa_key_usage_t usage,
298                                    psa_algorithm_t alg )
299 {
300     if( usage & ( PSA_KEY_USAGE_SIGN_HASH | PSA_KEY_USAGE_VERIFY_HASH ) )
301     {
302         unsigned char payload[PSA_HASH_MAX_SIZE] = {1};
303         size_t payload_length = 16;
304         unsigned char signature[PSA_SIGNATURE_MAX_SIZE] = {0};
305         size_t signature_length = sizeof( signature );
306         psa_algorithm_t hash_alg = PSA_ALG_SIGN_GET_HASH( alg );
307 
308         /* If the policy allows signing with any hash, just pick one. */
309         if( PSA_ALG_IS_SIGN_HASH( alg ) && hash_alg == PSA_ALG_ANY_HASH )
310         {
311     #if defined(KNOWN_SUPPORTED_HASH_ALG)
312             hash_alg = KNOWN_SUPPORTED_HASH_ALG;
313             alg ^= PSA_ALG_ANY_HASH ^ hash_alg;
314     #else
315             TEST_ASSERT( ! "No hash algorithm for hash-and-sign testing" );
316     #endif
317         }
318 
319         /* Some algorithms require the payload to have the size of
320          * the hash encoded in the algorithm. Use this input size
321          * even for algorithms that allow other input sizes. */
322         if( hash_alg != 0 )
323             payload_length = PSA_HASH_LENGTH( hash_alg );
324 
325         if( usage & PSA_KEY_USAGE_SIGN_HASH )
326         {
327             PSA_ASSERT( psa_sign_hash( key, alg,
328                                        payload, payload_length,
329                                        signature, sizeof( signature ),
330                                        &signature_length ) );
331         }
332 
333         if( usage & PSA_KEY_USAGE_VERIFY_HASH )
334         {
335             psa_status_t verify_status =
336                 ( usage & PSA_KEY_USAGE_SIGN_HASH ?
337                   PSA_SUCCESS :
338                   PSA_ERROR_INVALID_SIGNATURE );
339             TEST_EQUAL( psa_verify_hash( key, alg,
340                                          payload, payload_length,
341                                          signature, signature_length ),
342                         verify_status );
343         }
344     }
345 
346     if( usage & ( PSA_KEY_USAGE_SIGN_MESSAGE | PSA_KEY_USAGE_VERIFY_MESSAGE ) )
347     {
348         unsigned char message[256] = "Hello, world...";
349         unsigned char signature[PSA_SIGNATURE_MAX_SIZE] = {0};
350         size_t message_length = 16;
351         size_t signature_length = sizeof( signature );
352 
353         if( usage & PSA_KEY_USAGE_SIGN_MESSAGE )
354         {
355             PSA_ASSERT( psa_sign_message( key, alg,
356                                           message, message_length,
357                                           signature, sizeof( signature ),
358                                           &signature_length ) );
359         }
360 
361         if( usage & PSA_KEY_USAGE_VERIFY_MESSAGE )
362         {
363             psa_status_t verify_status =
364                 ( usage & PSA_KEY_USAGE_SIGN_MESSAGE ?
365                   PSA_SUCCESS :
366                   PSA_ERROR_INVALID_SIGNATURE );
367             TEST_EQUAL( psa_verify_message( key, alg,
368                                             message, message_length,
369                                             signature, signature_length ),
370                         verify_status );
371         }
372     }
373 
374     return( 1 );
375 
376 exit:
377     return( 0 );
378 }
379 
exercise_asymmetric_encryption_key(mbedtls_svc_key_id_t key,psa_key_usage_t usage,psa_algorithm_t alg)380 static int exercise_asymmetric_encryption_key( mbedtls_svc_key_id_t key,
381                                                psa_key_usage_t usage,
382                                                psa_algorithm_t alg )
383 {
384     unsigned char plaintext[256] = "Hello, world...";
385     unsigned char ciphertext[256] = "(wabblewebblewibblewobblewubble)";
386     size_t ciphertext_length = sizeof( ciphertext );
387     size_t plaintext_length = 16;
388 
389     if( usage & PSA_KEY_USAGE_ENCRYPT )
390     {
391         PSA_ASSERT( psa_asymmetric_encrypt( key, alg,
392                                             plaintext, plaintext_length,
393                                             NULL, 0,
394                                             ciphertext, sizeof( ciphertext ),
395                                             &ciphertext_length ) );
396     }
397 
398     if( usage & PSA_KEY_USAGE_DECRYPT )
399     {
400         psa_status_t status =
401             psa_asymmetric_decrypt( key, alg,
402                                     ciphertext, ciphertext_length,
403                                     NULL, 0,
404                                     plaintext, sizeof( plaintext ),
405                                     &plaintext_length );
406         TEST_ASSERT( status == PSA_SUCCESS ||
407                      ( ( usage & PSA_KEY_USAGE_ENCRYPT ) == 0 &&
408                        ( status == PSA_ERROR_INVALID_ARGUMENT ||
409                          status == PSA_ERROR_INVALID_PADDING ) ) );
410     }
411 
412     return( 1 );
413 
414 exit:
415     return( 0 );
416 }
417 
mbedtls_test_psa_setup_key_derivation_wrap(psa_key_derivation_operation_t * operation,mbedtls_svc_key_id_t key,psa_algorithm_t alg,const unsigned char * input1,size_t input1_length,const unsigned char * input2,size_t input2_length,size_t capacity)418 int mbedtls_test_psa_setup_key_derivation_wrap(
419     psa_key_derivation_operation_t* operation,
420     mbedtls_svc_key_id_t key,
421     psa_algorithm_t alg,
422     const unsigned char* input1, size_t input1_length,
423     const unsigned char* input2, size_t input2_length,
424     size_t capacity )
425 {
426     PSA_ASSERT( psa_key_derivation_setup( operation, alg ) );
427     if( PSA_ALG_IS_HKDF( alg ) )
428     {
429         PSA_ASSERT( psa_key_derivation_input_bytes( operation,
430                                                     PSA_KEY_DERIVATION_INPUT_SALT,
431                                                     input1, input1_length ) );
432         PSA_ASSERT( psa_key_derivation_input_key( operation,
433                                                   PSA_KEY_DERIVATION_INPUT_SECRET,
434                                                   key ) );
435         PSA_ASSERT( psa_key_derivation_input_bytes( operation,
436                                                     PSA_KEY_DERIVATION_INPUT_INFO,
437                                                     input2,
438                                                     input2_length ) );
439     }
440     else if( PSA_ALG_IS_TLS12_PRF( alg ) ||
441              PSA_ALG_IS_TLS12_PSK_TO_MS( alg ) )
442     {
443         PSA_ASSERT( psa_key_derivation_input_bytes( operation,
444                                                     PSA_KEY_DERIVATION_INPUT_SEED,
445                                                     input1, input1_length ) );
446         PSA_ASSERT( psa_key_derivation_input_key( operation,
447                                                   PSA_KEY_DERIVATION_INPUT_SECRET,
448                                                   key ) );
449         PSA_ASSERT( psa_key_derivation_input_bytes( operation,
450                                                     PSA_KEY_DERIVATION_INPUT_LABEL,
451                                                     input2, input2_length ) );
452     }
453     else
454     {
455         TEST_ASSERT( ! "Key derivation algorithm not supported" );
456     }
457 
458     if( capacity != SIZE_MAX )
459         PSA_ASSERT( psa_key_derivation_set_capacity( operation, capacity ) );
460 
461     return( 1 );
462 
463 exit:
464     return( 0 );
465 }
466 
467 
exercise_key_derivation_key(mbedtls_svc_key_id_t key,psa_key_usage_t usage,psa_algorithm_t alg)468 static int exercise_key_derivation_key( mbedtls_svc_key_id_t key,
469                                         psa_key_usage_t usage,
470                                         psa_algorithm_t alg )
471 {
472     psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
473     unsigned char input1[] = "Input 1";
474     size_t input1_length = sizeof( input1 );
475     unsigned char input2[] = "Input 2";
476     size_t input2_length = sizeof( input2 );
477     unsigned char output[1];
478     size_t capacity = sizeof( output );
479 
480     if( usage & PSA_KEY_USAGE_DERIVE )
481     {
482         if( !mbedtls_test_psa_setup_key_derivation_wrap( &operation, key, alg,
483                                                          input1, input1_length,
484                                                          input2, input2_length,
485                                                          capacity ) )
486             goto exit;
487 
488         PSA_ASSERT( psa_key_derivation_output_bytes( &operation,
489                                                      output,
490                                                      capacity ) );
491         PSA_ASSERT( psa_key_derivation_abort( &operation ) );
492     }
493 
494     return( 1 );
495 
496 exit:
497     return( 0 );
498 }
499 
500 /* We need two keys to exercise key agreement. Exercise the
501  * private key against its own public key. */
mbedtls_test_psa_key_agreement_with_self(psa_key_derivation_operation_t * operation,mbedtls_svc_key_id_t key)502 psa_status_t mbedtls_test_psa_key_agreement_with_self(
503     psa_key_derivation_operation_t *operation,
504     mbedtls_svc_key_id_t key )
505 {
506     psa_key_type_t private_key_type;
507     psa_key_type_t public_key_type;
508     size_t key_bits;
509     uint8_t *public_key = NULL;
510     size_t public_key_length;
511     /* Return GENERIC_ERROR if something other than the final call to
512      * psa_key_derivation_key_agreement fails. This isn't fully satisfactory,
513      * but it's good enough: callers will report it as a failed test anyway. */
514     psa_status_t status = PSA_ERROR_GENERIC_ERROR;
515     psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
516 
517     PSA_ASSERT( psa_get_key_attributes( key, &attributes ) );
518     private_key_type = psa_get_key_type( &attributes );
519     key_bits = psa_get_key_bits( &attributes );
520     public_key_type = PSA_KEY_TYPE_PUBLIC_KEY_OF_KEY_PAIR( private_key_type );
521     public_key_length = PSA_EXPORT_PUBLIC_KEY_OUTPUT_SIZE( public_key_type, key_bits );
522     ASSERT_ALLOC( public_key, public_key_length );
523     PSA_ASSERT( psa_export_public_key( key, public_key, public_key_length,
524                                        &public_key_length ) );
525 
526     status = psa_key_derivation_key_agreement(
527         operation, PSA_KEY_DERIVATION_INPUT_SECRET, key,
528         public_key, public_key_length );
529 exit:
530     /*
531      * Key attributes may have been returned by psa_get_key_attributes()
532      * thus reset them as required.
533      */
534     psa_reset_key_attributes( &attributes );
535 
536     mbedtls_free( public_key );
537     return( status );
538 }
539 
540 /* We need two keys to exercise key agreement. Exercise the
541  * private key against its own public key. */
mbedtls_test_psa_raw_key_agreement_with_self(psa_algorithm_t alg,mbedtls_svc_key_id_t key)542 psa_status_t mbedtls_test_psa_raw_key_agreement_with_self(
543     psa_algorithm_t alg,
544     mbedtls_svc_key_id_t key )
545 {
546     psa_key_type_t private_key_type;
547     psa_key_type_t public_key_type;
548     size_t key_bits;
549     uint8_t *public_key = NULL;
550     size_t public_key_length;
551     uint8_t output[1024];
552     size_t output_length;
553     /* Return GENERIC_ERROR if something other than the final call to
554      * psa_key_derivation_key_agreement fails. This isn't fully satisfactory,
555      * but it's good enough: callers will report it as a failed test anyway. */
556     psa_status_t status = PSA_ERROR_GENERIC_ERROR;
557     psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
558 
559     PSA_ASSERT( psa_get_key_attributes( key, &attributes ) );
560     private_key_type = psa_get_key_type( &attributes );
561     key_bits = psa_get_key_bits( &attributes );
562     public_key_type = PSA_KEY_TYPE_PUBLIC_KEY_OF_KEY_PAIR( private_key_type );
563     public_key_length = PSA_EXPORT_PUBLIC_KEY_OUTPUT_SIZE( public_key_type, key_bits );
564     ASSERT_ALLOC( public_key, public_key_length );
565     PSA_ASSERT( psa_export_public_key( key,
566                                        public_key, public_key_length,
567                                        &public_key_length ) );
568 
569     status = psa_raw_key_agreement( alg, key,
570                                     public_key, public_key_length,
571                                     output, sizeof( output ), &output_length );
572     if ( status == PSA_SUCCESS )
573     {
574         TEST_ASSERT( output_length <=
575                      PSA_RAW_KEY_AGREEMENT_OUTPUT_SIZE( private_key_type,
576                                                         key_bits ) );
577         TEST_ASSERT( output_length <=
578                      PSA_RAW_KEY_AGREEMENT_OUTPUT_MAX_SIZE );
579     }
580 
581 exit:
582     /*
583      * Key attributes may have been returned by psa_get_key_attributes()
584      * thus reset them as required.
585      */
586     psa_reset_key_attributes( &attributes );
587 
588     mbedtls_free( public_key );
589     return( status );
590 }
591 
exercise_raw_key_agreement_key(mbedtls_svc_key_id_t key,psa_key_usage_t usage,psa_algorithm_t alg)592 static int exercise_raw_key_agreement_key( mbedtls_svc_key_id_t key,
593                                            psa_key_usage_t usage,
594                                            psa_algorithm_t alg )
595 {
596     int ok = 0;
597 
598     if( usage & PSA_KEY_USAGE_DERIVE )
599     {
600         /* We need two keys to exercise key agreement. Exercise the
601          * private key against its own public key. */
602         PSA_ASSERT( mbedtls_test_psa_raw_key_agreement_with_self( alg, key ) );
603     }
604     ok = 1;
605 
606 exit:
607     return( ok );
608 }
609 
exercise_key_agreement_key(mbedtls_svc_key_id_t key,psa_key_usage_t usage,psa_algorithm_t alg)610 static int exercise_key_agreement_key( mbedtls_svc_key_id_t key,
611                                        psa_key_usage_t usage,
612                                        psa_algorithm_t alg )
613 {
614     psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
615     unsigned char output[1];
616     int ok = 0;
617 
618     if( usage & PSA_KEY_USAGE_DERIVE )
619     {
620         /* We need two keys to exercise key agreement. Exercise the
621          * private key against its own public key. */
622         PSA_ASSERT( psa_key_derivation_setup( &operation, alg ) );
623         PSA_ASSERT( mbedtls_test_psa_key_agreement_with_self( &operation, key ) );
624         PSA_ASSERT( psa_key_derivation_output_bytes( &operation,
625                                                      output,
626                                                      sizeof( output ) ) );
627         PSA_ASSERT( psa_key_derivation_abort( &operation ) );
628     }
629     ok = 1;
630 
631 exit:
632     return( ok );
633 }
634 
mbedtls_test_psa_exported_key_sanity_check(psa_key_type_t type,size_t bits,const uint8_t * exported,size_t exported_length)635 int mbedtls_test_psa_exported_key_sanity_check(
636     psa_key_type_t type, size_t bits,
637     const uint8_t *exported, size_t exported_length )
638 {
639     TEST_ASSERT( exported_length <= PSA_EXPORT_KEY_OUTPUT_SIZE( type, bits ) );
640 
641     if( PSA_KEY_TYPE_IS_UNSTRUCTURED( type ) )
642         TEST_EQUAL( exported_length, PSA_BITS_TO_BYTES( bits ) );
643     else
644 
645 #if defined(MBEDTLS_RSA_C) && defined(MBEDTLS_PK_PARSE_C)
646     if( type == PSA_KEY_TYPE_RSA_KEY_PAIR )
647     {
648         uint8_t *p = (uint8_t*) exported;
649         const uint8_t *end = exported + exported_length;
650         size_t len;
651         /*   RSAPrivateKey ::= SEQUENCE {
652          *       version             INTEGER,  -- must be 0
653          *       modulus             INTEGER,  -- n
654          *       publicExponent      INTEGER,  -- e
655          *       privateExponent     INTEGER,  -- d
656          *       prime1              INTEGER,  -- p
657          *       prime2              INTEGER,  -- q
658          *       exponent1           INTEGER,  -- d mod (p-1)
659          *       exponent2           INTEGER,  -- d mod (q-1)
660          *       coefficient         INTEGER,  -- (inverse of q) mod p
661          *   }
662          */
663         TEST_EQUAL( mbedtls_asn1_get_tag( &p, end, &len,
664                                           MBEDTLS_ASN1_SEQUENCE |
665                                           MBEDTLS_ASN1_CONSTRUCTED ), 0 );
666         TEST_EQUAL( len, end - p );
667         if( ! mbedtls_test_asn1_skip_integer( &p, end, 0, 0, 0 ) )
668             goto exit;
669         if( ! mbedtls_test_asn1_skip_integer( &p, end, bits, bits, 1 ) )
670             goto exit;
671         if( ! mbedtls_test_asn1_skip_integer( &p, end, 2, bits, 1 ) )
672             goto exit;
673         /* Require d to be at least half the size of n. */
674         if( ! mbedtls_test_asn1_skip_integer( &p, end, bits / 2, bits, 1 ) )
675             goto exit;
676         /* Require p and q to be at most half the size of n, rounded up. */
677         if( ! mbedtls_test_asn1_skip_integer( &p, end, bits / 2, bits / 2 + 1, 1 ) )
678             goto exit;
679         if( ! mbedtls_test_asn1_skip_integer( &p, end, bits / 2, bits / 2 + 1, 1 ) )
680             goto exit;
681         if( ! mbedtls_test_asn1_skip_integer( &p, end, 1, bits / 2 + 1, 0 ) )
682             goto exit;
683         if( ! mbedtls_test_asn1_skip_integer( &p, end, 1, bits / 2 + 1, 0 ) )
684             goto exit;
685         if( ! mbedtls_test_asn1_skip_integer( &p, end, 1, bits / 2 + 1, 0 ) )
686             goto exit;
687         TEST_EQUAL( p - end, 0 );
688 
689         TEST_ASSERT( exported_length <= PSA_EXPORT_KEY_PAIR_MAX_SIZE );
690     }
691     else
692 #endif /* MBEDTLS_RSA_C */
693 
694 #if defined(MBEDTLS_ECP_C)
695     if( PSA_KEY_TYPE_IS_ECC_KEY_PAIR( type ) )
696     {
697         /* Just the secret value */
698         TEST_EQUAL( exported_length, PSA_BITS_TO_BYTES( bits ) );
699 
700         TEST_ASSERT( exported_length <= PSA_EXPORT_KEY_PAIR_MAX_SIZE );
701     }
702     else
703 #endif /* MBEDTLS_ECP_C */
704 
705 #if defined(MBEDTLS_RSA_C)
706     if( type == PSA_KEY_TYPE_RSA_PUBLIC_KEY )
707     {
708         uint8_t *p = (uint8_t*) exported;
709         const uint8_t *end = exported + exported_length;
710         size_t len;
711         /*   RSAPublicKey ::= SEQUENCE {
712          *      modulus            INTEGER,    -- n
713          *      publicExponent     INTEGER  }  -- e
714          */
715         TEST_EQUAL( mbedtls_asn1_get_tag( &p, end, &len,
716                                           MBEDTLS_ASN1_SEQUENCE |
717                                           MBEDTLS_ASN1_CONSTRUCTED ),
718                     0 );
719         TEST_EQUAL( len, end - p );
720         if( ! mbedtls_test_asn1_skip_integer( &p, end, bits, bits, 1 ) )
721             goto exit;
722         if( ! mbedtls_test_asn1_skip_integer( &p, end, 2, bits, 1 ) )
723             goto exit;
724         TEST_EQUAL( p - end, 0 );
725 
726 
727         TEST_ASSERT( exported_length <=
728                      PSA_EXPORT_PUBLIC_KEY_OUTPUT_SIZE( type, bits ) );
729         TEST_ASSERT( exported_length <=
730                      PSA_EXPORT_PUBLIC_KEY_MAX_SIZE );
731     }
732     else
733 #endif /* MBEDTLS_RSA_C */
734 
735 #if defined(MBEDTLS_ECP_C)
736     if( PSA_KEY_TYPE_IS_ECC_PUBLIC_KEY( type ) )
737     {
738 
739         TEST_ASSERT( exported_length <=
740                      PSA_EXPORT_PUBLIC_KEY_OUTPUT_SIZE( type, bits ) );
741         TEST_ASSERT( exported_length <=
742                      PSA_EXPORT_PUBLIC_KEY_MAX_SIZE );
743 
744         if( PSA_KEY_TYPE_ECC_GET_FAMILY( type ) == PSA_ECC_FAMILY_MONTGOMERY )
745         {
746             /* The representation of an ECC Montgomery public key is
747              * the raw compressed point */
748              TEST_EQUAL( PSA_BITS_TO_BYTES( bits ), exported_length );
749         }
750         else
751         {
752             /* The representation of an ECC Weierstrass public key is:
753              *      - The byte 0x04;
754              *      - `x_P` as a `ceiling(m/8)`-byte string, big-endian;
755              *      - `y_P` as a `ceiling(m/8)`-byte string, big-endian;
756              *      - where m is the bit size associated with the curve.
757              */
758             TEST_EQUAL( 1 + 2 * PSA_BITS_TO_BYTES( bits ), exported_length );
759             TEST_EQUAL( exported[0], 4 );
760         }
761     }
762     else
763 #endif /* MBEDTLS_ECP_C */
764 
765     {
766         TEST_ASSERT( ! "Sanity check not implemented for this key type" );
767     }
768 
769 #if defined(MBEDTLS_DES_C)
770     if( type == PSA_KEY_TYPE_DES )
771     {
772         /* Check the parity bits. */
773         unsigned i;
774         for( i = 0; i < bits / 8; i++ )
775         {
776             unsigned bit_count = 0;
777             unsigned m;
778             for( m = 1; m <= 0x100; m <<= 1 )
779             {
780                 if( exported[i] & m )
781                     ++bit_count;
782             }
783             TEST_ASSERT( bit_count % 2 != 0 );
784         }
785     }
786 #endif
787 
788     return( 1 );
789 
790 exit:
791     return( 0 );
792 }
793 
exercise_export_key(mbedtls_svc_key_id_t key,psa_key_usage_t usage)794 static int exercise_export_key( mbedtls_svc_key_id_t key,
795                                 psa_key_usage_t usage )
796 {
797     psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
798     uint8_t *exported = NULL;
799     size_t exported_size = 0;
800     size_t exported_length = 0;
801     int ok = 0;
802 
803     PSA_ASSERT( psa_get_key_attributes( key, &attributes ) );
804 
805     exported_size = PSA_EXPORT_KEY_OUTPUT_SIZE(
806                         psa_get_key_type( &attributes ),
807                         psa_get_key_bits( &attributes ) );
808     ASSERT_ALLOC( exported, exported_size );
809 
810     if( ( usage & PSA_KEY_USAGE_EXPORT ) == 0 &&
811         ! PSA_KEY_TYPE_IS_PUBLIC_KEY( psa_get_key_type( &attributes ) ) )
812     {
813         TEST_EQUAL( psa_export_key( key, exported,
814                                     exported_size, &exported_length ),
815                     PSA_ERROR_NOT_PERMITTED );
816         ok = 1;
817         goto exit;
818     }
819 
820     PSA_ASSERT( psa_export_key( key,
821                                 exported, exported_size,
822                                 &exported_length ) );
823     ok = mbedtls_test_psa_exported_key_sanity_check(
824         psa_get_key_type( &attributes ), psa_get_key_bits( &attributes ),
825         exported, exported_length );
826 
827 exit:
828     /*
829      * Key attributes may have been returned by psa_get_key_attributes()
830      * thus reset them as required.
831      */
832     psa_reset_key_attributes( &attributes );
833 
834     mbedtls_free( exported );
835     return( ok );
836 }
837 
exercise_export_public_key(mbedtls_svc_key_id_t key)838 static int exercise_export_public_key( mbedtls_svc_key_id_t key )
839 {
840     psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
841     psa_key_type_t public_type;
842     uint8_t *exported = NULL;
843     size_t exported_size = 0;
844     size_t exported_length = 0;
845     int ok = 0;
846 
847     PSA_ASSERT( psa_get_key_attributes( key, &attributes ) );
848     if( ! PSA_KEY_TYPE_IS_ASYMMETRIC( psa_get_key_type( &attributes ) ) )
849     {
850         exported_size = PSA_EXPORT_KEY_OUTPUT_SIZE(
851                             psa_get_key_type( &attributes ),
852                             psa_get_key_bits( &attributes ) );
853         ASSERT_ALLOC( exported, exported_size );
854 
855         TEST_EQUAL( psa_export_public_key( key, exported,
856                                            exported_size, &exported_length ),
857                     PSA_ERROR_INVALID_ARGUMENT );
858         ok = 1;
859         goto exit;
860     }
861 
862     public_type = PSA_KEY_TYPE_PUBLIC_KEY_OF_KEY_PAIR(
863         psa_get_key_type( &attributes ) );
864     exported_size = PSA_EXPORT_PUBLIC_KEY_OUTPUT_SIZE( public_type,
865                                                        psa_get_key_bits( &attributes ) );
866     ASSERT_ALLOC( exported, exported_size );
867 
868     PSA_ASSERT( psa_export_public_key( key,
869                                        exported, exported_size,
870                                        &exported_length ) );
871     ok = mbedtls_test_psa_exported_key_sanity_check(
872         public_type, psa_get_key_bits( &attributes ),
873         exported, exported_length );
874 
875 exit:
876     /*
877      * Key attributes may have been returned by psa_get_key_attributes()
878      * thus reset them as required.
879      */
880     psa_reset_key_attributes( &attributes );
881 
882     mbedtls_free( exported );
883     return( ok );
884 }
885 
mbedtls_test_psa_exercise_key(mbedtls_svc_key_id_t key,psa_key_usage_t usage,psa_algorithm_t alg)886 int mbedtls_test_psa_exercise_key( mbedtls_svc_key_id_t key,
887                                    psa_key_usage_t usage,
888                                    psa_algorithm_t alg )
889 {
890     int ok = 0;
891 
892     if( ! check_key_attributes_sanity( key ) )
893         return( 0 );
894 
895     if( alg == 0 )
896         ok = 1; /* If no algorihm, do nothing (used for raw data "keys"). */
897     else if( PSA_ALG_IS_MAC( alg ) )
898         ok = exercise_mac_key( key, usage, alg );
899     else if( PSA_ALG_IS_CIPHER( alg ) )
900         ok = exercise_cipher_key( key, usage, alg );
901     else if( PSA_ALG_IS_AEAD( alg ) )
902         ok = exercise_aead_key( key, usage, alg );
903     else if( PSA_ALG_IS_SIGN( alg ) )
904         ok = exercise_signature_key( key, usage, alg );
905     else if( PSA_ALG_IS_ASYMMETRIC_ENCRYPTION( alg ) )
906         ok = exercise_asymmetric_encryption_key( key, usage, alg );
907     else if( PSA_ALG_IS_KEY_DERIVATION( alg ) )
908         ok = exercise_key_derivation_key( key, usage, alg );
909     else if( PSA_ALG_IS_RAW_KEY_AGREEMENT( alg ) )
910         ok = exercise_raw_key_agreement_key( key, usage, alg );
911     else if( PSA_ALG_IS_KEY_AGREEMENT( alg ) )
912         ok = exercise_key_agreement_key( key, usage, alg );
913     else
914         TEST_ASSERT( ! "No code to exercise this category of algorithm" );
915 
916     ok = ok && exercise_export_key( key, usage );
917     ok = ok && exercise_export_public_key( key );
918 
919 exit:
920     return( ok );
921 }
922 
mbedtls_test_psa_usage_to_exercise(psa_key_type_t type,psa_algorithm_t alg)923 psa_key_usage_t mbedtls_test_psa_usage_to_exercise( psa_key_type_t type,
924                                                     psa_algorithm_t alg )
925 {
926     if( PSA_ALG_IS_MAC( alg ) || PSA_ALG_IS_SIGN( alg ) )
927     {
928         if( PSA_ALG_IS_SIGN_HASH( alg ) )
929         {
930             if( PSA_ALG_SIGN_GET_HASH( alg ) )
931                 return( PSA_KEY_TYPE_IS_PUBLIC_KEY( type ) ?
932                         PSA_KEY_USAGE_VERIFY_HASH | PSA_KEY_USAGE_VERIFY_MESSAGE:
933                         PSA_KEY_USAGE_SIGN_HASH | PSA_KEY_USAGE_VERIFY_HASH |
934                         PSA_KEY_USAGE_SIGN_MESSAGE | PSA_KEY_USAGE_VERIFY_MESSAGE );
935         }
936         else if( PSA_ALG_IS_SIGN_MESSAGE( alg) )
937             return( PSA_KEY_TYPE_IS_PUBLIC_KEY( type ) ?
938                     PSA_KEY_USAGE_VERIFY_MESSAGE :
939                     PSA_KEY_USAGE_SIGN_MESSAGE | PSA_KEY_USAGE_VERIFY_MESSAGE );
940 
941         return( PSA_KEY_TYPE_IS_PUBLIC_KEY( type ) ?
942                 PSA_KEY_USAGE_VERIFY_HASH :
943                 PSA_KEY_USAGE_SIGN_HASH | PSA_KEY_USAGE_VERIFY_HASH );
944     }
945     else if( PSA_ALG_IS_CIPHER( alg ) || PSA_ALG_IS_AEAD( alg ) ||
946              PSA_ALG_IS_ASYMMETRIC_ENCRYPTION( alg ) )
947     {
948         return( PSA_KEY_TYPE_IS_PUBLIC_KEY( type ) ?
949                 PSA_KEY_USAGE_ENCRYPT :
950                 PSA_KEY_USAGE_ENCRYPT | PSA_KEY_USAGE_DECRYPT );
951     }
952     else if( PSA_ALG_IS_KEY_DERIVATION( alg ) ||
953              PSA_ALG_IS_KEY_AGREEMENT( alg ) )
954     {
955         return( PSA_KEY_USAGE_DERIVE );
956     }
957     else
958     {
959         return( 0 );
960     }
961 
962 }
963 
964 #endif /* MBEDTLS_PSA_CRYPTO_C */
965