1 /*
2  *  PSA crypto layer on top of Mbed TLS crypto
3  */
4 /*
5  *  Copyright The Mbed TLS Contributors
6  *  SPDX-License-Identifier: Apache-2.0
7  *
8  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
9  *  not use this file except in compliance with the License.
10  *  You may obtain a copy of the License at
11  *
12  *  http://www.apache.org/licenses/LICENSE-2.0
13  *
14  *  Unless required by applicable law or agreed to in writing, software
15  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  *  See the License for the specific language governing permissions and
18  *  limitations under the License.
19  */
20 
21 #include "common.h"
22 
23 #if defined(MBEDTLS_PSA_CRYPTO_C)
24 
25 #if defined(MBEDTLS_PSA_CRYPTO_CONFIG)
26 #include "check_crypto_config.h"
27 #endif
28 
29 #include "psa/crypto.h"
30 
31 #include "psa_crypto_cipher.h"
32 #include "psa_crypto_core.h"
33 #include "psa_crypto_invasive.h"
34 #include "psa_crypto_driver_wrappers.h"
35 #include "psa_crypto_ecp.h"
36 #include "psa_crypto_hash.h"
37 #include "psa_crypto_mac.h"
38 #include "psa_crypto_rsa.h"
39 #include "psa_crypto_ecp.h"
40 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
41 #include "psa_crypto_se.h"
42 #endif
43 #include "psa_crypto_slot_management.h"
44 /* Include internal declarations that are useful for implementing persistently
45  * stored keys. */
46 #include "psa_crypto_storage.h"
47 
48 #include "psa_crypto_random_impl.h"
49 
50 #include <assert.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include "mbedtls/platform.h"
54 #if !defined(MBEDTLS_PLATFORM_C)
55 #define mbedtls_calloc calloc
56 #define mbedtls_free   free
57 #endif
58 
59 #include "mbedtls/aes.h"
60 #include "mbedtls/asn1.h"
61 #include "mbedtls/asn1write.h"
62 #include "mbedtls/bignum.h"
63 #include "mbedtls/camellia.h"
64 #include "mbedtls/chacha20.h"
65 #include "mbedtls/chachapoly.h"
66 #include "mbedtls/cipher.h"
67 #include "mbedtls/ccm.h"
68 #include "mbedtls/cmac.h"
69 #include "mbedtls/des.h"
70 #include "mbedtls/ecdh.h"
71 #include "mbedtls/ecp.h"
72 #include "mbedtls/entropy.h"
73 #include "mbedtls/error.h"
74 #include "mbedtls/gcm.h"
75 #include "mbedtls/md5.h"
76 #include "mbedtls/md.h"
77 #include "md_wrap.h"
78 #include "mbedtls/pk.h"
79 #include "pk_wrap.h"
80 #include "mbedtls/platform_util.h"
81 #include "mbedtls/error.h"
82 #include "mbedtls/ripemd160.h"
83 #include "mbedtls/rsa.h"
84 #include "mbedtls/sha1.h"
85 #include "mbedtls/sha256.h"
86 #include "mbedtls/sha512.h"
87 
88 #define ARRAY_LENGTH( array ) ( sizeof( array ) / sizeof( *( array ) ) )
89 
90 /****************************************************************/
91 /* Global data, support functions and library management */
92 /****************************************************************/
93 
key_type_is_raw_bytes(psa_key_type_t type)94 static int key_type_is_raw_bytes( psa_key_type_t type )
95 {
96     return( PSA_KEY_TYPE_IS_UNSTRUCTURED( type ) );
97 }
98 
99 /* Values for psa_global_data_t::rng_state */
100 #define RNG_NOT_INITIALIZED 0
101 #define RNG_INITIALIZED 1
102 #define RNG_SEEDED 2
103 
104 typedef struct
105 {
106     mbedtls_psa_random_context_t rng;
107     unsigned initialized : 1;
108     unsigned rng_state : 2;
109 } psa_global_data_t;
110 
111 static psa_global_data_t global_data;
112 
113 #if !defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
114 mbedtls_psa_drbg_context_t *const mbedtls_psa_random_state =
115     &global_data.rng.drbg;
116 #endif
117 
118 #define GUARD_MODULE_INITIALIZED        \
119     if( global_data.initialized == 0 )  \
120         return( PSA_ERROR_BAD_STATE );
121 
mbedtls_to_psa_error(int ret)122 psa_status_t mbedtls_to_psa_error( int ret )
123 {
124     /* Mbed TLS error codes can combine a high-level error code and a
125      * low-level error code. The low-level error usually reflects the
126      * root cause better, so dispatch on that preferably. */
127     int low_level_ret = - ( -ret & 0x007f );
128     switch( low_level_ret != 0 ? low_level_ret : ret )
129     {
130         case 0:
131             return( PSA_SUCCESS );
132 
133         case MBEDTLS_ERR_AES_INVALID_KEY_LENGTH:
134         case MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH:
135             return( PSA_ERROR_NOT_SUPPORTED );
136         case MBEDTLS_ERR_ASN1_OUT_OF_DATA:
137         case MBEDTLS_ERR_ASN1_UNEXPECTED_TAG:
138         case MBEDTLS_ERR_ASN1_INVALID_LENGTH:
139         case MBEDTLS_ERR_ASN1_LENGTH_MISMATCH:
140         case MBEDTLS_ERR_ASN1_INVALID_DATA:
141             return( PSA_ERROR_INVALID_ARGUMENT );
142         case MBEDTLS_ERR_ASN1_ALLOC_FAILED:
143             return( PSA_ERROR_INSUFFICIENT_MEMORY );
144         case MBEDTLS_ERR_ASN1_BUF_TOO_SMALL:
145             return( PSA_ERROR_BUFFER_TOO_SMALL );
146 
147 #if defined(MBEDTLS_ERR_CAMELLIA_BAD_INPUT_DATA)
148         case MBEDTLS_ERR_CAMELLIA_BAD_INPUT_DATA:
149 #endif
150         case MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH:
151             return( PSA_ERROR_NOT_SUPPORTED );
152 
153         case MBEDTLS_ERR_CCM_BAD_INPUT:
154             return( PSA_ERROR_INVALID_ARGUMENT );
155         case MBEDTLS_ERR_CCM_AUTH_FAILED:
156             return( PSA_ERROR_INVALID_SIGNATURE );
157 
158         case MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA:
159             return( PSA_ERROR_INVALID_ARGUMENT );
160 
161         case MBEDTLS_ERR_CHACHAPOLY_BAD_STATE:
162             return( PSA_ERROR_BAD_STATE );
163         case MBEDTLS_ERR_CHACHAPOLY_AUTH_FAILED:
164             return( PSA_ERROR_INVALID_SIGNATURE );
165 
166         case MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE:
167             return( PSA_ERROR_NOT_SUPPORTED );
168         case MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA:
169             return( PSA_ERROR_INVALID_ARGUMENT );
170         case MBEDTLS_ERR_CIPHER_ALLOC_FAILED:
171             return( PSA_ERROR_INSUFFICIENT_MEMORY );
172         case MBEDTLS_ERR_CIPHER_INVALID_PADDING:
173             return( PSA_ERROR_INVALID_PADDING );
174         case MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED:
175             return( PSA_ERROR_INVALID_ARGUMENT );
176         case MBEDTLS_ERR_CIPHER_AUTH_FAILED:
177             return( PSA_ERROR_INVALID_SIGNATURE );
178         case MBEDTLS_ERR_CIPHER_INVALID_CONTEXT:
179             return( PSA_ERROR_CORRUPTION_DETECTED );
180 
181 #if !( defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG) ||      \
182        defined(MBEDTLS_PSA_HMAC_DRBG_MD_TYPE) )
183         /* Only check CTR_DRBG error codes if underlying mbedtls_xxx
184          * functions are passed a CTR_DRBG instance. */
185         case MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED:
186             return( PSA_ERROR_INSUFFICIENT_ENTROPY );
187         case MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG:
188         case MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG:
189             return( PSA_ERROR_NOT_SUPPORTED );
190         case MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR:
191             return( PSA_ERROR_INSUFFICIENT_ENTROPY );
192 #endif
193 
194         case MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH:
195             return( PSA_ERROR_NOT_SUPPORTED );
196 
197         case MBEDTLS_ERR_ENTROPY_NO_SOURCES_DEFINED:
198         case MBEDTLS_ERR_ENTROPY_NO_STRONG_SOURCE:
199         case MBEDTLS_ERR_ENTROPY_SOURCE_FAILED:
200             return( PSA_ERROR_INSUFFICIENT_ENTROPY );
201 
202         case MBEDTLS_ERR_GCM_AUTH_FAILED:
203             return( PSA_ERROR_INVALID_SIGNATURE );
204         case MBEDTLS_ERR_GCM_BUFFER_TOO_SMALL:
205             return( PSA_ERROR_BUFFER_TOO_SMALL );
206         case MBEDTLS_ERR_GCM_BAD_INPUT:
207             return( PSA_ERROR_INVALID_ARGUMENT );
208 
209 #if !defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG) &&        \
210     defined(MBEDTLS_PSA_HMAC_DRBG_MD_TYPE)
211         /* Only check HMAC_DRBG error codes if underlying mbedtls_xxx
212          * functions are passed a HMAC_DRBG instance. */
213         case MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED:
214             return( PSA_ERROR_INSUFFICIENT_ENTROPY );
215         case MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG:
216         case MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG:
217             return( PSA_ERROR_NOT_SUPPORTED );
218         case MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR:
219             return( PSA_ERROR_INSUFFICIENT_ENTROPY );
220 #endif
221 
222         case MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE:
223             return( PSA_ERROR_NOT_SUPPORTED );
224         case MBEDTLS_ERR_MD_BAD_INPUT_DATA:
225             return( PSA_ERROR_INVALID_ARGUMENT );
226         case MBEDTLS_ERR_MD_ALLOC_FAILED:
227             return( PSA_ERROR_INSUFFICIENT_MEMORY );
228         case MBEDTLS_ERR_MD_FILE_IO_ERROR:
229             return( PSA_ERROR_STORAGE_FAILURE );
230 
231         case MBEDTLS_ERR_MPI_FILE_IO_ERROR:
232             return( PSA_ERROR_STORAGE_FAILURE );
233         case MBEDTLS_ERR_MPI_BAD_INPUT_DATA:
234             return( PSA_ERROR_INVALID_ARGUMENT );
235         case MBEDTLS_ERR_MPI_INVALID_CHARACTER:
236             return( PSA_ERROR_INVALID_ARGUMENT );
237         case MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL:
238             return( PSA_ERROR_BUFFER_TOO_SMALL );
239         case MBEDTLS_ERR_MPI_NEGATIVE_VALUE:
240             return( PSA_ERROR_INVALID_ARGUMENT );
241         case MBEDTLS_ERR_MPI_DIVISION_BY_ZERO:
242             return( PSA_ERROR_INVALID_ARGUMENT );
243         case MBEDTLS_ERR_MPI_NOT_ACCEPTABLE:
244             return( PSA_ERROR_INVALID_ARGUMENT );
245         case MBEDTLS_ERR_MPI_ALLOC_FAILED:
246             return( PSA_ERROR_INSUFFICIENT_MEMORY );
247 
248         case MBEDTLS_ERR_PK_ALLOC_FAILED:
249             return( PSA_ERROR_INSUFFICIENT_MEMORY );
250         case MBEDTLS_ERR_PK_TYPE_MISMATCH:
251         case MBEDTLS_ERR_PK_BAD_INPUT_DATA:
252             return( PSA_ERROR_INVALID_ARGUMENT );
253         case MBEDTLS_ERR_PK_FILE_IO_ERROR:
254             return( PSA_ERROR_STORAGE_FAILURE );
255         case MBEDTLS_ERR_PK_KEY_INVALID_VERSION:
256         case MBEDTLS_ERR_PK_KEY_INVALID_FORMAT:
257             return( PSA_ERROR_INVALID_ARGUMENT );
258         case MBEDTLS_ERR_PK_UNKNOWN_PK_ALG:
259             return( PSA_ERROR_NOT_SUPPORTED );
260         case MBEDTLS_ERR_PK_PASSWORD_REQUIRED:
261         case MBEDTLS_ERR_PK_PASSWORD_MISMATCH:
262             return( PSA_ERROR_NOT_PERMITTED );
263         case MBEDTLS_ERR_PK_INVALID_PUBKEY:
264             return( PSA_ERROR_INVALID_ARGUMENT );
265         case MBEDTLS_ERR_PK_INVALID_ALG:
266         case MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE:
267         case MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE:
268             return( PSA_ERROR_NOT_SUPPORTED );
269         case MBEDTLS_ERR_PK_SIG_LEN_MISMATCH:
270             return( PSA_ERROR_INVALID_SIGNATURE );
271         case MBEDTLS_ERR_PK_BUFFER_TOO_SMALL:
272             return( PSA_ERROR_BUFFER_TOO_SMALL );
273 
274         case MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED:
275             return( PSA_ERROR_HARDWARE_FAILURE );
276         case MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED:
277             return( PSA_ERROR_NOT_SUPPORTED );
278 
279         case MBEDTLS_ERR_RSA_BAD_INPUT_DATA:
280             return( PSA_ERROR_INVALID_ARGUMENT );
281         case MBEDTLS_ERR_RSA_INVALID_PADDING:
282             return( PSA_ERROR_INVALID_PADDING );
283         case MBEDTLS_ERR_RSA_KEY_GEN_FAILED:
284             return( PSA_ERROR_HARDWARE_FAILURE );
285         case MBEDTLS_ERR_RSA_KEY_CHECK_FAILED:
286             return( PSA_ERROR_INVALID_ARGUMENT );
287         case MBEDTLS_ERR_RSA_PUBLIC_FAILED:
288         case MBEDTLS_ERR_RSA_PRIVATE_FAILED:
289             return( PSA_ERROR_CORRUPTION_DETECTED );
290         case MBEDTLS_ERR_RSA_VERIFY_FAILED:
291             return( PSA_ERROR_INVALID_SIGNATURE );
292         case MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE:
293             return( PSA_ERROR_BUFFER_TOO_SMALL );
294         case MBEDTLS_ERR_RSA_RNG_FAILED:
295             return( PSA_ERROR_INSUFFICIENT_ENTROPY );
296 
297         case MBEDTLS_ERR_ECP_BAD_INPUT_DATA:
298         case MBEDTLS_ERR_ECP_INVALID_KEY:
299             return( PSA_ERROR_INVALID_ARGUMENT );
300         case MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL:
301             return( PSA_ERROR_BUFFER_TOO_SMALL );
302         case MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE:
303             return( PSA_ERROR_NOT_SUPPORTED );
304         case MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH:
305         case MBEDTLS_ERR_ECP_VERIFY_FAILED:
306             return( PSA_ERROR_INVALID_SIGNATURE );
307         case MBEDTLS_ERR_ECP_ALLOC_FAILED:
308             return( PSA_ERROR_INSUFFICIENT_MEMORY );
309         case MBEDTLS_ERR_ECP_RANDOM_FAILED:
310             return( PSA_ERROR_INSUFFICIENT_ENTROPY );
311 
312         case MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED:
313             return( PSA_ERROR_CORRUPTION_DETECTED );
314 
315         default:
316             return( PSA_ERROR_GENERIC_ERROR );
317     }
318 }
319 
320 
321 
322 
323 /****************************************************************/
324 /* Key management */
325 /****************************************************************/
326 
327 /* For now the MBEDTLS_PSA_ACCEL_ guards are also used here since the
328  * current test driver in key_management.c is using this function
329  * when accelerators are used for ECC key pair and public key.
330  * Once that dependency is resolved these guards can be removed.
331  */
332 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) || \
333     defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY) || \
334     defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR) || \
335     defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_PUBLIC_KEY)
mbedtls_ecc_group_of_psa(psa_ecc_family_t curve,size_t bits,int bits_is_sloppy)336 mbedtls_ecp_group_id mbedtls_ecc_group_of_psa( psa_ecc_family_t curve,
337                                                size_t bits,
338                                                int bits_is_sloppy )
339 {
340     switch( curve )
341     {
342         case PSA_ECC_FAMILY_SECP_R1:
343             switch( bits )
344             {
345 #if defined(PSA_WANT_ECC_SECP_R1_192)
346                 case 192:
347                     return( MBEDTLS_ECP_DP_SECP192R1 );
348 #endif
349 #if defined(PSA_WANT_ECC_SECP_R1_224)
350                 case 224:
351                     return( MBEDTLS_ECP_DP_SECP224R1 );
352 #endif
353 #if defined(PSA_WANT_ECC_SECP_R1_256)
354                 case 256:
355                     return( MBEDTLS_ECP_DP_SECP256R1 );
356 #endif
357 #if defined(PSA_WANT_ECC_SECP_R1_384)
358                 case 384:
359                     return( MBEDTLS_ECP_DP_SECP384R1 );
360 #endif
361 #if defined(PSA_WANT_ECC_SECP_R1_521)
362                 case 521:
363                     return( MBEDTLS_ECP_DP_SECP521R1 );
364                 case 528:
365                     if( bits_is_sloppy )
366                         return( MBEDTLS_ECP_DP_SECP521R1 );
367                     break;
368 #endif
369             }
370             break;
371 
372         case PSA_ECC_FAMILY_BRAINPOOL_P_R1:
373             switch( bits )
374             {
375 #if defined(PSA_WANT_ECC_BRAINPOOL_P_R1_256)
376                 case 256:
377                     return( MBEDTLS_ECP_DP_BP256R1 );
378 #endif
379 #if defined(PSA_WANT_ECC_BRAINPOOL_P_R1_384)
380                 case 384:
381                     return( MBEDTLS_ECP_DP_BP384R1 );
382 #endif
383 #if defined(PSA_WANT_ECC_BRAINPOOL_P_R1_512)
384                 case 512:
385                     return( MBEDTLS_ECP_DP_BP512R1 );
386 #endif
387             }
388             break;
389 
390         case PSA_ECC_FAMILY_MONTGOMERY:
391             switch( bits )
392             {
393 #if defined(PSA_WANT_ECC_MONTGOMERY_255)
394                 case 255:
395                     return( MBEDTLS_ECP_DP_CURVE25519 );
396                 case 256:
397                     if( bits_is_sloppy )
398                         return( MBEDTLS_ECP_DP_CURVE25519 );
399                     break;
400 #endif
401 #if defined(PSA_WANT_ECC_MONTGOMERY_448)
402                 case 448:
403                     return( MBEDTLS_ECP_DP_CURVE448 );
404 #endif
405             }
406             break;
407 
408         case PSA_ECC_FAMILY_SECP_K1:
409             switch( bits )
410             {
411 #if defined(PSA_WANT_ECC_SECP_K1_192)
412                 case 192:
413                     return( MBEDTLS_ECP_DP_SECP192K1 );
414 #endif
415 #if defined(PSA_WANT_ECC_SECP_K1_224)
416                 case 224:
417                     return( MBEDTLS_ECP_DP_SECP224K1 );
418 #endif
419 #if defined(PSA_WANT_ECC_SECP_K1_256)
420                 case 256:
421                     return( MBEDTLS_ECP_DP_SECP256K1 );
422 #endif
423             }
424             break;
425     }
426 
427     (void) bits_is_sloppy;
428     return( MBEDTLS_ECP_DP_NONE );
429 }
430 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) ||
431         * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY) ||
432         * defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR) ||
433         * defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_PUBLIC_KEY) */
434 
psa_validate_unstructured_key_bit_size(psa_key_type_t type,size_t bits)435 psa_status_t psa_validate_unstructured_key_bit_size( psa_key_type_t type,
436                                                      size_t bits )
437 {
438     /* Check that the bit size is acceptable for the key type */
439     switch( type )
440     {
441         case PSA_KEY_TYPE_RAW_DATA:
442         case PSA_KEY_TYPE_HMAC:
443         case PSA_KEY_TYPE_DERIVE:
444             break;
445 #if defined(PSA_WANT_KEY_TYPE_AES)
446         case PSA_KEY_TYPE_AES:
447             if( bits != 128 && bits != 192 && bits != 256 )
448                 return( PSA_ERROR_INVALID_ARGUMENT );
449             break;
450 #endif
451 #if defined(PSA_WANT_KEY_TYPE_ARIA)
452         case PSA_KEY_TYPE_ARIA:
453             if( bits != 128 && bits != 192 && bits != 256 )
454                 return( PSA_ERROR_INVALID_ARGUMENT );
455             break;
456 #endif
457 #if defined(PSA_WANT_KEY_TYPE_CAMELLIA)
458         case PSA_KEY_TYPE_CAMELLIA:
459             if( bits != 128 && bits != 192 && bits != 256 )
460                 return( PSA_ERROR_INVALID_ARGUMENT );
461             break;
462 #endif
463 #if defined(PSA_WANT_KEY_TYPE_DES)
464         case PSA_KEY_TYPE_DES:
465             if( bits != 64 && bits != 128 && bits != 192 )
466                 return( PSA_ERROR_INVALID_ARGUMENT );
467             break;
468 #endif
469 #if defined(PSA_WANT_KEY_TYPE_CHACHA20)
470         case PSA_KEY_TYPE_CHACHA20:
471             if( bits != 256 )
472                 return( PSA_ERROR_INVALID_ARGUMENT );
473             break;
474 #endif
475         default:
476             return( PSA_ERROR_NOT_SUPPORTED );
477     }
478     if( bits % 8 != 0 )
479         return( PSA_ERROR_INVALID_ARGUMENT );
480 
481     return( PSA_SUCCESS );
482 }
483 
484 /** Check whether a given key type is valid for use with a given MAC algorithm
485  *
486  * Upon successful return of this function, the behavior of #PSA_MAC_LENGTH
487  * when called with the validated \p algorithm and \p key_type is well-defined.
488  *
489  * \param[in] algorithm     The specific MAC algorithm (can be wildcard).
490  * \param[in] key_type      The key type of the key to be used with the
491  *                          \p algorithm.
492  *
493  * \retval #PSA_SUCCESS
494  *         The \p key_type is valid for use with the \p algorithm
495  * \retval #PSA_ERROR_INVALID_ARGUMENT
496  *         The \p key_type is not valid for use with the \p algorithm
497  */
psa_mac_key_can_do(psa_algorithm_t algorithm,psa_key_type_t key_type)498 MBEDTLS_STATIC_TESTABLE psa_status_t psa_mac_key_can_do(
499     psa_algorithm_t algorithm,
500     psa_key_type_t key_type )
501 {
502     if( PSA_ALG_IS_HMAC( algorithm ) )
503     {
504         if( key_type == PSA_KEY_TYPE_HMAC )
505             return( PSA_SUCCESS );
506     }
507 
508     if( PSA_ALG_IS_BLOCK_CIPHER_MAC( algorithm ) )
509     {
510         /* Check that we're calling PSA_BLOCK_CIPHER_BLOCK_LENGTH with a cipher
511          * key. */
512         if( ( key_type & PSA_KEY_TYPE_CATEGORY_MASK ) ==
513             PSA_KEY_TYPE_CATEGORY_SYMMETRIC )
514         {
515             /* PSA_BLOCK_CIPHER_BLOCK_LENGTH returns 1 for stream ciphers and
516              * the block length (larger than 1) for block ciphers. */
517             if( PSA_BLOCK_CIPHER_BLOCK_LENGTH( key_type ) > 1 )
518                 return( PSA_SUCCESS );
519         }
520     }
521 
522     return( PSA_ERROR_INVALID_ARGUMENT );
523 }
524 
psa_allocate_buffer_to_slot(psa_key_slot_t * slot,size_t buffer_length)525 psa_status_t psa_allocate_buffer_to_slot( psa_key_slot_t *slot,
526                                           size_t buffer_length )
527 {
528     if( slot->key.data != NULL )
529         return( PSA_ERROR_ALREADY_EXISTS );
530 
531     slot->key.data = mbedtls_calloc( 1, buffer_length );
532     if( slot->key.data == NULL )
533         return( PSA_ERROR_INSUFFICIENT_MEMORY );
534 
535     slot->key.bytes = buffer_length;
536     return( PSA_SUCCESS );
537 }
538 
psa_copy_key_material_into_slot(psa_key_slot_t * slot,const uint8_t * data,size_t data_length)539 psa_status_t psa_copy_key_material_into_slot( psa_key_slot_t *slot,
540                                               const uint8_t* data,
541                                               size_t data_length )
542 {
543     psa_status_t status = psa_allocate_buffer_to_slot( slot,
544                                                        data_length );
545     if( status != PSA_SUCCESS )
546         return( status );
547 
548     memcpy( slot->key.data, data, data_length );
549     return( PSA_SUCCESS );
550 }
551 
psa_import_key_into_slot(const psa_key_attributes_t * attributes,const uint8_t * data,size_t data_length,uint8_t * key_buffer,size_t key_buffer_size,size_t * key_buffer_length,size_t * bits)552 psa_status_t psa_import_key_into_slot(
553     const psa_key_attributes_t *attributes,
554     const uint8_t *data, size_t data_length,
555     uint8_t *key_buffer, size_t key_buffer_size,
556     size_t *key_buffer_length, size_t *bits )
557 {
558     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
559     psa_key_type_t type = attributes->core.type;
560 
561     /* zero-length keys are never supported. */
562     if( data_length == 0 )
563         return( PSA_ERROR_NOT_SUPPORTED );
564 
565     if( key_type_is_raw_bytes( type ) )
566     {
567         *bits = PSA_BYTES_TO_BITS( data_length );
568 
569         status = psa_validate_unstructured_key_bit_size( attributes->core.type,
570                                                          *bits );
571         if( status != PSA_SUCCESS )
572             return( status );
573 
574         /* Copy the key material. */
575         memcpy( key_buffer, data, data_length );
576         *key_buffer_length = data_length;
577         (void)key_buffer_size;
578 
579         return( PSA_SUCCESS );
580     }
581     else if( PSA_KEY_TYPE_IS_ASYMMETRIC( type ) )
582     {
583 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) || \
584     defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY)
585         if( PSA_KEY_TYPE_IS_ECC( type ) )
586         {
587             return( mbedtls_psa_ecp_import_key( attributes,
588                                                 data, data_length,
589                                                 key_buffer, key_buffer_size,
590                                                 key_buffer_length,
591                                                 bits ) );
592         }
593 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) ||
594         * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY) */
595 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) || \
596     defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY)
597         if( PSA_KEY_TYPE_IS_RSA( type ) )
598         {
599             return( mbedtls_psa_rsa_import_key( attributes,
600                                                 data, data_length,
601                                                 key_buffer, key_buffer_size,
602                                                 key_buffer_length,
603                                                 bits ) );
604         }
605 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) ||
606         * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY) */
607     }
608 
609     return( PSA_ERROR_NOT_SUPPORTED );
610 }
611 
612 /** Calculate the intersection of two algorithm usage policies.
613  *
614  * Return 0 (which allows no operation) on incompatibility.
615  */
psa_key_policy_algorithm_intersection(psa_key_type_t key_type,psa_algorithm_t alg1,psa_algorithm_t alg2)616 static psa_algorithm_t psa_key_policy_algorithm_intersection(
617     psa_key_type_t key_type,
618     psa_algorithm_t alg1,
619     psa_algorithm_t alg2 )
620 {
621     /* Common case: both sides actually specify the same policy. */
622     if( alg1 == alg2 )
623         return( alg1 );
624     /* If the policies are from the same hash-and-sign family, check
625      * if one is a wildcard. If so the other has the specific algorithm. */
626     if( PSA_ALG_IS_SIGN_HASH( alg1 ) &&
627         PSA_ALG_IS_SIGN_HASH( alg2 ) &&
628         ( alg1 & ~PSA_ALG_HASH_MASK ) == ( alg2 & ~PSA_ALG_HASH_MASK ) )
629     {
630         if( PSA_ALG_SIGN_GET_HASH( alg1 ) == PSA_ALG_ANY_HASH )
631             return( alg2 );
632         if( PSA_ALG_SIGN_GET_HASH( alg2 ) == PSA_ALG_ANY_HASH )
633             return( alg1 );
634     }
635     /* If the policies are from the same AEAD family, check whether
636      * one of them is a minimum-tag-length wildcard. Calculate the most
637      * restrictive tag length. */
638     if( PSA_ALG_IS_AEAD( alg1 ) && PSA_ALG_IS_AEAD( alg2 ) &&
639         ( PSA_ALG_AEAD_WITH_SHORTENED_TAG( alg1, 0 ) ==
640           PSA_ALG_AEAD_WITH_SHORTENED_TAG( alg2, 0 ) ) )
641     {
642         size_t alg1_len = PSA_ALG_AEAD_GET_TAG_LENGTH( alg1 );
643         size_t alg2_len = PSA_ALG_AEAD_GET_TAG_LENGTH( alg2 );
644         size_t restricted_len = alg1_len > alg2_len ? alg1_len : alg2_len;
645 
646         /* If both are wildcards, return most restrictive wildcard */
647         if( ( ( alg1 & PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG ) != 0 ) &&
648             ( ( alg2 & PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG ) != 0 ) )
649         {
650             return( PSA_ALG_AEAD_WITH_AT_LEAST_THIS_LENGTH_TAG(
651                         alg1, restricted_len ) );
652         }
653         /* If only one is a wildcard, return specific algorithm if compatible. */
654         if( ( ( alg1 & PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG ) != 0 ) &&
655             ( alg1_len <= alg2_len ) )
656         {
657             return( alg2 );
658         }
659         if( ( ( alg2 & PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG ) != 0 ) &&
660             ( alg2_len <= alg1_len ) )
661         {
662             return( alg1 );
663         }
664     }
665     /* If the policies are from the same MAC family, check whether one
666      * of them is a minimum-MAC-length policy. Calculate the most
667      * restrictive tag length. */
668     if( PSA_ALG_IS_MAC( alg1 ) && PSA_ALG_IS_MAC( alg2 ) &&
669         ( PSA_ALG_FULL_LENGTH_MAC( alg1 ) ==
670           PSA_ALG_FULL_LENGTH_MAC( alg2 ) ) )
671     {
672         /* Validate the combination of key type and algorithm. Since the base
673          * algorithm of alg1 and alg2 are the same, we only need this once. */
674         if( PSA_SUCCESS != psa_mac_key_can_do( alg1, key_type ) )
675             return( 0 );
676 
677         /* Get the (exact or at-least) output lengths for both sides of the
678          * requested intersection. None of the currently supported algorithms
679          * have an output length dependent on the actual key size, so setting it
680          * to a bogus value of 0 is currently OK.
681          *
682          * Note that for at-least-this-length wildcard algorithms, the output
683          * length is set to the shortest allowed length, which allows us to
684          * calculate the most restrictive tag length for the intersection. */
685         size_t alg1_len = PSA_MAC_LENGTH( key_type, 0, alg1 );
686         size_t alg2_len = PSA_MAC_LENGTH( key_type, 0, alg2 );
687         size_t restricted_len = alg1_len > alg2_len ? alg1_len : alg2_len;
688 
689         /* If both are wildcards, return most restrictive wildcard */
690         if( ( ( alg1 & PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG ) != 0 ) &&
691             ( ( alg2 & PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG ) != 0 ) )
692         {
693             return( PSA_ALG_AT_LEAST_THIS_LENGTH_MAC( alg1, restricted_len ) );
694         }
695 
696         /* If only one is an at-least-this-length policy, the intersection would
697          * be the other (fixed-length) policy as long as said fixed length is
698          * equal to or larger than the shortest allowed length. */
699         if( ( alg1 & PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG ) != 0 )
700         {
701             return( ( alg1_len <= alg2_len ) ? alg2 : 0 );
702         }
703         if( ( alg2 & PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG ) != 0 )
704         {
705             return( ( alg2_len <= alg1_len ) ? alg1 : 0 );
706         }
707 
708         /* If none of them are wildcards, check whether they define the same tag
709          * length. This is still possible here when one is default-length and
710          * the other specific-length. Ensure to always return the
711          * specific-length version for the intersection. */
712         if( alg1_len == alg2_len )
713             return( PSA_ALG_TRUNCATED_MAC( alg1, alg1_len ) );
714     }
715     /* If the policies are incompatible, allow nothing. */
716     return( 0 );
717 }
718 
psa_key_algorithm_permits(psa_key_type_t key_type,psa_algorithm_t policy_alg,psa_algorithm_t requested_alg)719 static int psa_key_algorithm_permits( psa_key_type_t key_type,
720                                       psa_algorithm_t policy_alg,
721                                       psa_algorithm_t requested_alg )
722 {
723     /* Common case: the policy only allows requested_alg. */
724     if( requested_alg == policy_alg )
725         return( 1 );
726     /* If policy_alg is a hash-and-sign with a wildcard for the hash,
727      * and requested_alg is the same hash-and-sign family with any hash,
728      * then requested_alg is compliant with policy_alg. */
729     if( PSA_ALG_IS_SIGN_HASH( requested_alg ) &&
730         PSA_ALG_SIGN_GET_HASH( policy_alg ) == PSA_ALG_ANY_HASH )
731     {
732         return( ( policy_alg & ~PSA_ALG_HASH_MASK ) ==
733                 ( requested_alg & ~PSA_ALG_HASH_MASK ) );
734     }
735     /* If policy_alg is a wildcard AEAD algorithm of the same base as
736      * the requested algorithm, check the requested tag length to be
737      * equal-length or longer than the wildcard-specified length. */
738     if( PSA_ALG_IS_AEAD( policy_alg ) &&
739         PSA_ALG_IS_AEAD( requested_alg ) &&
740         ( PSA_ALG_AEAD_WITH_SHORTENED_TAG( policy_alg, 0 ) ==
741           PSA_ALG_AEAD_WITH_SHORTENED_TAG( requested_alg, 0 ) ) &&
742         ( ( policy_alg & PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG ) != 0 ) )
743     {
744         return( PSA_ALG_AEAD_GET_TAG_LENGTH( policy_alg ) <=
745                 PSA_ALG_AEAD_GET_TAG_LENGTH( requested_alg ) );
746     }
747     /* If policy_alg is a MAC algorithm of the same base as the requested
748      * algorithm, check whether their MAC lengths are compatible. */
749     if( PSA_ALG_IS_MAC( policy_alg ) &&
750         PSA_ALG_IS_MAC( requested_alg ) &&
751         ( PSA_ALG_FULL_LENGTH_MAC( policy_alg ) ==
752           PSA_ALG_FULL_LENGTH_MAC( requested_alg ) ) )
753     {
754         /* Validate the combination of key type and algorithm. Since the policy
755          * and requested algorithms are the same, we only need this once. */
756         if( PSA_SUCCESS != psa_mac_key_can_do( policy_alg, key_type ) )
757             return( 0 );
758 
759         /* Get both the requested output length for the algorithm which is to be
760          * verified, and the default output length for the base algorithm.
761          * Note that none of the currently supported algorithms have an output
762          * length dependent on actual key size, so setting it to a bogus value
763          * of 0 is currently OK. */
764         size_t requested_output_length = PSA_MAC_LENGTH(
765                                             key_type, 0, requested_alg );
766         size_t default_output_length = PSA_MAC_LENGTH(
767                                         key_type, 0,
768                                         PSA_ALG_FULL_LENGTH_MAC( requested_alg ) );
769 
770         /* If the policy is default-length, only allow an algorithm with
771          * a declared exact-length matching the default. */
772         if( PSA_MAC_TRUNCATED_LENGTH( policy_alg ) == 0 )
773             return( requested_output_length == default_output_length );
774 
775         /* If the requested algorithm is default-length, allow it if the policy
776          * length exactly matches the default length. */
777         if( PSA_MAC_TRUNCATED_LENGTH( requested_alg ) == 0 &&
778             PSA_MAC_TRUNCATED_LENGTH( policy_alg ) == default_output_length )
779         {
780             return( 1 );
781         }
782 
783         /* If policy_alg is an at-least-this-length wildcard MAC algorithm,
784          * check for the requested MAC length to be equal to or longer than the
785          * minimum allowed length. */
786         if( ( policy_alg & PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG ) != 0 )
787         {
788             return( PSA_MAC_TRUNCATED_LENGTH( policy_alg ) <=
789                     requested_output_length );
790         }
791     }
792     /* If policy_alg is a generic key agreement operation, then using it for
793      * a key derivation with that key agreement should also be allowed. This
794      * behaviour is expected to be defined in a future specification version. */
795     if( PSA_ALG_IS_RAW_KEY_AGREEMENT( policy_alg ) &&
796         PSA_ALG_IS_KEY_AGREEMENT( requested_alg ) )
797     {
798         return( PSA_ALG_KEY_AGREEMENT_GET_BASE( requested_alg ) ==
799                 policy_alg );
800     }
801     /* If it isn't explicitly permitted, it's forbidden. */
802     return( 0 );
803 }
804 
805 /** Test whether a policy permits an algorithm.
806  *
807  * The caller must test usage flags separately.
808  *
809  * \note This function requires providing the key type for which the policy is
810  *       being validated, since some algorithm policy definitions (e.g. MAC)
811  *       have different properties depending on what kind of cipher it is
812  *       combined with.
813  *
814  * \retval PSA_SUCCESS                  When \p alg is a specific algorithm
815  *                                      allowed by the \p policy.
816  * \retval PSA_ERROR_INVALID_ARGUMENT   When \p alg is not a specific algorithm
817  * \retval PSA_ERROR_NOT_PERMITTED      When \p alg is a specific algorithm, but
818  *                                      the \p policy does not allow it.
819  */
psa_key_policy_permits(const psa_key_policy_t * policy,psa_key_type_t key_type,psa_algorithm_t alg)820 static psa_status_t psa_key_policy_permits( const psa_key_policy_t *policy,
821                                             psa_key_type_t key_type,
822                                             psa_algorithm_t alg )
823 {
824     /* '0' is not a valid algorithm */
825     if( alg == 0 )
826         return( PSA_ERROR_INVALID_ARGUMENT );
827 
828     /* A requested algorithm cannot be a wildcard. */
829     if( PSA_ALG_IS_WILDCARD( alg ) )
830         return( PSA_ERROR_INVALID_ARGUMENT );
831 
832     if( psa_key_algorithm_permits( key_type, policy->alg, alg ) ||
833         psa_key_algorithm_permits( key_type, policy->alg2, alg ) )
834         return( PSA_SUCCESS );
835     else
836         return( PSA_ERROR_NOT_PERMITTED );
837 }
838 
839 /** Restrict a key policy based on a constraint.
840  *
841  * \note This function requires providing the key type for which the policy is
842  *       being restricted, since some algorithm policy definitions (e.g. MAC)
843  *       have different properties depending on what kind of cipher it is
844  *       combined with.
845  *
846  * \param[in] key_type      The key type for which to restrict the policy
847  * \param[in,out] policy    The policy to restrict.
848  * \param[in] constraint    The policy constraint to apply.
849  *
850  * \retval #PSA_SUCCESS
851  *         \c *policy contains the intersection of the original value of
852  *         \c *policy and \c *constraint.
853  * \retval #PSA_ERROR_INVALID_ARGUMENT
854  *         \c key_type, \c *policy and \c *constraint are incompatible.
855  *         \c *policy is unchanged.
856  */
psa_restrict_key_policy(psa_key_type_t key_type,psa_key_policy_t * policy,const psa_key_policy_t * constraint)857 static psa_status_t psa_restrict_key_policy(
858     psa_key_type_t key_type,
859     psa_key_policy_t *policy,
860     const psa_key_policy_t *constraint )
861 {
862     psa_algorithm_t intersection_alg =
863         psa_key_policy_algorithm_intersection( key_type, policy->alg,
864                                                constraint->alg );
865     psa_algorithm_t intersection_alg2 =
866         psa_key_policy_algorithm_intersection( key_type, policy->alg2,
867                                                constraint->alg2 );
868     if( intersection_alg == 0 && policy->alg != 0 && constraint->alg != 0 )
869         return( PSA_ERROR_INVALID_ARGUMENT );
870     if( intersection_alg2 == 0 && policy->alg2 != 0 && constraint->alg2 != 0 )
871         return( PSA_ERROR_INVALID_ARGUMENT );
872     policy->usage &= constraint->usage;
873     policy->alg = intersection_alg;
874     policy->alg2 = intersection_alg2;
875     return( PSA_SUCCESS );
876 }
877 
878 /** Get the description of a key given its identifier and policy constraints
879  *  and lock it.
880  *
881  * The key must have allow all the usage flags set in \p usage. If \p alg is
882  * nonzero, the key must allow operations with this algorithm. If \p alg is
883  * zero, the algorithm is not checked.
884  *
885  * In case of a persistent key, the function loads the description of the key
886  * into a key slot if not already done.
887  *
888  * On success, the returned key slot is locked. It is the responsibility of
889  * the caller to unlock the key slot when it does not access it anymore.
890  */
psa_get_and_lock_key_slot_with_policy(mbedtls_svc_key_id_t key,psa_key_slot_t ** p_slot,psa_key_usage_t usage,psa_algorithm_t alg)891 static psa_status_t psa_get_and_lock_key_slot_with_policy(
892     mbedtls_svc_key_id_t key,
893     psa_key_slot_t **p_slot,
894     psa_key_usage_t usage,
895     psa_algorithm_t alg )
896 {
897     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
898     psa_key_slot_t *slot;
899 
900     status = psa_get_and_lock_key_slot( key, p_slot );
901     if( status != PSA_SUCCESS )
902         return( status );
903     slot = *p_slot;
904 
905     /* Enforce that usage policy for the key slot contains all the flags
906      * required by the usage parameter. There is one exception: public
907      * keys can always be exported, so we treat public key objects as
908      * if they had the export flag. */
909     if( PSA_KEY_TYPE_IS_PUBLIC_KEY( slot->attr.type ) )
910         usage &= ~PSA_KEY_USAGE_EXPORT;
911 
912     if( ( slot->attr.policy.usage & usage ) != usage )
913     {
914         status = PSA_ERROR_NOT_PERMITTED;
915         goto error;
916     }
917 
918     /* Enforce that the usage policy permits the requested algortihm. */
919     if( alg != 0 )
920     {
921         status = psa_key_policy_permits( &slot->attr.policy,
922                                          slot->attr.type,
923                                          alg );
924         if( status != PSA_SUCCESS )
925             goto error;
926     }
927 
928     return( PSA_SUCCESS );
929 
930 error:
931     *p_slot = NULL;
932     psa_unlock_key_slot( slot );
933 
934     return( status );
935 }
936 
937 /** Get a key slot containing a transparent key and lock it.
938  *
939  * A transparent key is a key for which the key material is directly
940  * available, as opposed to a key in a secure element and/or to be used
941  * by a secure element.
942  *
943  * This is a temporary function that may be used instead of
944  * psa_get_and_lock_key_slot_with_policy() when there is no opaque key support
945  * for a cryptographic operation.
946  *
947  * On success, the returned key slot is locked. It is the responsibility of the
948  * caller to unlock the key slot when it does not access it anymore.
949  */
psa_get_and_lock_transparent_key_slot_with_policy(mbedtls_svc_key_id_t key,psa_key_slot_t ** p_slot,psa_key_usage_t usage,psa_algorithm_t alg)950 static psa_status_t psa_get_and_lock_transparent_key_slot_with_policy(
951     mbedtls_svc_key_id_t key,
952     psa_key_slot_t **p_slot,
953     psa_key_usage_t usage,
954     psa_algorithm_t alg )
955 {
956     psa_status_t status = psa_get_and_lock_key_slot_with_policy( key, p_slot,
957                                                                  usage, alg );
958     if( status != PSA_SUCCESS )
959         return( status );
960 
961     if( psa_key_lifetime_is_external( (*p_slot)->attr.lifetime ) )
962     {
963         psa_unlock_key_slot( *p_slot );
964         *p_slot = NULL;
965         return( PSA_ERROR_NOT_SUPPORTED );
966     }
967 
968     return( PSA_SUCCESS );
969 }
970 
psa_remove_key_data_from_memory(psa_key_slot_t * slot)971 psa_status_t psa_remove_key_data_from_memory( psa_key_slot_t *slot )
972 {
973     /* Data pointer will always be either a valid pointer or NULL in an
974      * initialized slot, so we can just free it. */
975     if( slot->key.data != NULL )
976         mbedtls_platform_zeroize( slot->key.data, slot->key.bytes);
977 
978     mbedtls_free( slot->key.data );
979     slot->key.data = NULL;
980     slot->key.bytes = 0;
981 
982     return( PSA_SUCCESS );
983 }
984 
985 /** Completely wipe a slot in memory, including its policy.
986  * Persistent storage is not affected. */
psa_wipe_key_slot(psa_key_slot_t * slot)987 psa_status_t psa_wipe_key_slot( psa_key_slot_t *slot )
988 {
989     psa_status_t status = psa_remove_key_data_from_memory( slot );
990 
991    /*
992     * As the return error code may not be handled in case of multiple errors,
993     * do our best to report an unexpected lock counter. Assert with
994     * MBEDTLS_TEST_HOOK_TEST_ASSERT that the lock counter is equal to one:
995     * if the MBEDTLS_TEST_HOOKS configuration option is enabled and the
996     * function is called as part of the execution of a test suite, the
997     * execution of the test suite is stopped in error if the assertion fails.
998     */
999     if( slot->lock_count != 1 )
1000     {
1001         MBEDTLS_TEST_HOOK_TEST_ASSERT( slot->lock_count == 1 );
1002         status = PSA_ERROR_CORRUPTION_DETECTED;
1003     }
1004 
1005     /* Multipart operations may still be using the key. This is safe
1006      * because all multipart operation objects are independent from
1007      * the key slot: if they need to access the key after the setup
1008      * phase, they have a copy of the key. Note that this means that
1009      * key material can linger until all operations are completed. */
1010     /* At this point, key material and other type-specific content has
1011      * been wiped. Clear remaining metadata. We can call memset and not
1012      * zeroize because the metadata is not particularly sensitive. */
1013     memset( slot, 0, sizeof( *slot ) );
1014     return( status );
1015 }
1016 
psa_destroy_key(mbedtls_svc_key_id_t key)1017 psa_status_t psa_destroy_key( mbedtls_svc_key_id_t key )
1018 {
1019     psa_key_slot_t *slot;
1020     psa_status_t status; /* status of the last operation */
1021     psa_status_t overall_status = PSA_SUCCESS;
1022 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1023     psa_se_drv_table_entry_t *driver;
1024 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1025 
1026     if( mbedtls_svc_key_id_is_null( key ) )
1027         return( PSA_SUCCESS );
1028 
1029     /*
1030      * Get the description of the key in a key slot. In case of a persistent
1031      * key, this will load the key description from persistent memory if not
1032      * done yet. We cannot avoid this loading as without it we don't know if
1033      * the key is operated by an SE or not and this information is needed by
1034      * the current implementation.
1035      */
1036     status = psa_get_and_lock_key_slot( key, &slot );
1037     if( status != PSA_SUCCESS )
1038         return( status );
1039 
1040     /*
1041      * If the key slot containing the key description is under access by the
1042      * library (apart from the present access), the key cannot be destroyed
1043      * yet. For the time being, just return in error. Eventually (to be
1044      * implemented), the key should be destroyed when all accesses have
1045      * stopped.
1046      */
1047     if( slot->lock_count > 1 )
1048     {
1049        psa_unlock_key_slot( slot );
1050        return( PSA_ERROR_GENERIC_ERROR );
1051     }
1052 
1053     if( PSA_KEY_LIFETIME_IS_READ_ONLY( slot->attr.lifetime ) )
1054     {
1055         /* Refuse the destruction of a read-only key (which may or may not work
1056          * if we attempt it, depending on whether the key is merely read-only
1057          * by policy or actually physically read-only).
1058          * Just do the best we can, which is to wipe the copy in memory
1059          * (done in this function's cleanup code). */
1060         overall_status = PSA_ERROR_NOT_PERMITTED;
1061         goto exit;
1062     }
1063 
1064 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1065     driver = psa_get_se_driver_entry( slot->attr.lifetime );
1066     if( driver != NULL )
1067     {
1068         /* For a key in a secure element, we need to do three things:
1069          * remove the key file in internal storage, destroy the
1070          * key inside the secure element, and update the driver's
1071          * persistent data. Start a transaction that will encompass these
1072          * three actions. */
1073         psa_crypto_prepare_transaction( PSA_CRYPTO_TRANSACTION_DESTROY_KEY );
1074         psa_crypto_transaction.key.lifetime = slot->attr.lifetime;
1075         psa_crypto_transaction.key.slot = psa_key_slot_get_slot_number( slot );
1076         psa_crypto_transaction.key.id = slot->attr.id;
1077         status = psa_crypto_save_transaction( );
1078         if( status != PSA_SUCCESS )
1079         {
1080             (void) psa_crypto_stop_transaction( );
1081             /* We should still try to destroy the key in the secure
1082              * element and the key metadata in storage. This is especially
1083              * important if the error is that the storage is full.
1084              * But how to do it exactly without risking an inconsistent
1085              * state after a reset?
1086              * https://github.com/ARMmbed/mbed-crypto/issues/215
1087              */
1088             overall_status = status;
1089             goto exit;
1090         }
1091 
1092         status = psa_destroy_se_key( driver,
1093                                      psa_key_slot_get_slot_number( slot ) );
1094         if( overall_status == PSA_SUCCESS )
1095             overall_status = status;
1096     }
1097 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1098 
1099 #if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C)
1100     if( ! PSA_KEY_LIFETIME_IS_VOLATILE( slot->attr.lifetime ) )
1101     {
1102         status = psa_destroy_persistent_key( slot->attr.id );
1103         if( overall_status == PSA_SUCCESS )
1104             overall_status = status;
1105 
1106         /* TODO: other slots may have a copy of the same key. We should
1107          * invalidate them.
1108          * https://github.com/ARMmbed/mbed-crypto/issues/214
1109          */
1110     }
1111 #endif /* defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) */
1112 
1113 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1114     if( driver != NULL )
1115     {
1116         status = psa_save_se_persistent_data( driver );
1117         if( overall_status == PSA_SUCCESS )
1118             overall_status = status;
1119         status = psa_crypto_stop_transaction( );
1120         if( overall_status == PSA_SUCCESS )
1121             overall_status = status;
1122     }
1123 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1124 
1125 exit:
1126     status = psa_wipe_key_slot( slot );
1127     /* Prioritize CORRUPTION_DETECTED from wiping over a storage error */
1128     if( status != PSA_SUCCESS )
1129         overall_status = status;
1130     return( overall_status );
1131 }
1132 
1133 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) || \
1134     defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY)
psa_get_rsa_public_exponent(const mbedtls_rsa_context * rsa,psa_key_attributes_t * attributes)1135 static psa_status_t psa_get_rsa_public_exponent(
1136     const mbedtls_rsa_context *rsa,
1137     psa_key_attributes_t *attributes )
1138 {
1139     mbedtls_mpi mpi;
1140     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1141     uint8_t *buffer = NULL;
1142     size_t buflen;
1143     mbedtls_mpi_init( &mpi );
1144 
1145     ret = mbedtls_rsa_export( rsa, NULL, NULL, NULL, NULL, &mpi );
1146     if( ret != 0 )
1147         goto exit;
1148     if( mbedtls_mpi_cmp_int( &mpi, 65537 ) == 0 )
1149     {
1150         /* It's the default value, which is reported as an empty string,
1151          * so there's nothing to do. */
1152         goto exit;
1153     }
1154 
1155     buflen = mbedtls_mpi_size( &mpi );
1156     buffer = mbedtls_calloc( 1, buflen );
1157     if( buffer == NULL )
1158     {
1159         ret = MBEDTLS_ERR_MPI_ALLOC_FAILED;
1160         goto exit;
1161     }
1162     ret = mbedtls_mpi_write_binary( &mpi, buffer, buflen );
1163     if( ret != 0 )
1164         goto exit;
1165     attributes->domain_parameters = buffer;
1166     attributes->domain_parameters_size = buflen;
1167 
1168 exit:
1169     mbedtls_mpi_free( &mpi );
1170     if( ret != 0 )
1171         mbedtls_free( buffer );
1172     return( mbedtls_to_psa_error( ret ) );
1173 }
1174 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) ||
1175         * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY) */
1176 
1177 /** Retrieve all the publicly-accessible attributes of a key.
1178  */
psa_get_key_attributes(mbedtls_svc_key_id_t key,psa_key_attributes_t * attributes)1179 psa_status_t psa_get_key_attributes( mbedtls_svc_key_id_t key,
1180                                      psa_key_attributes_t *attributes )
1181 {
1182     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
1183     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
1184     psa_key_slot_t *slot;
1185 
1186     psa_reset_key_attributes( attributes );
1187 
1188     status = psa_get_and_lock_key_slot_with_policy( key, &slot, 0, 0 );
1189     if( status != PSA_SUCCESS )
1190         return( status );
1191 
1192     attributes->core = slot->attr;
1193     attributes->core.flags &= ( MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY |
1194                                 MBEDTLS_PSA_KA_MASK_DUAL_USE );
1195 
1196 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1197     if( psa_get_se_driver_entry( slot->attr.lifetime ) != NULL )
1198         psa_set_key_slot_number( attributes,
1199                                  psa_key_slot_get_slot_number( slot ) );
1200 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1201 
1202     switch( slot->attr.type )
1203     {
1204 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) || \
1205     defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY)
1206         case PSA_KEY_TYPE_RSA_KEY_PAIR:
1207         case PSA_KEY_TYPE_RSA_PUBLIC_KEY:
1208             /* TODO: reporting the public exponent for opaque keys
1209              * is not yet implemented.
1210              * https://github.com/ARMmbed/mbed-crypto/issues/216
1211              */
1212             if( ! psa_key_lifetime_is_external( slot->attr.lifetime ) )
1213             {
1214                 mbedtls_rsa_context *rsa = NULL;
1215 
1216                 status = mbedtls_psa_rsa_load_representation(
1217                              slot->attr.type,
1218                              slot->key.data,
1219                              slot->key.bytes,
1220                              &rsa );
1221                 if( status != PSA_SUCCESS )
1222                     break;
1223 
1224                 status = psa_get_rsa_public_exponent( rsa,
1225                                                       attributes );
1226                 mbedtls_rsa_free( rsa );
1227                 mbedtls_free( rsa );
1228             }
1229             break;
1230 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) ||
1231         * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY) */
1232         default:
1233             /* Nothing else to do. */
1234             break;
1235     }
1236 
1237     if( status != PSA_SUCCESS )
1238         psa_reset_key_attributes( attributes );
1239 
1240     unlock_status = psa_unlock_key_slot( slot );
1241 
1242     return( ( status == PSA_SUCCESS ) ? unlock_status : status );
1243 }
1244 
1245 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
psa_get_key_slot_number(const psa_key_attributes_t * attributes,psa_key_slot_number_t * slot_number)1246 psa_status_t psa_get_key_slot_number(
1247     const psa_key_attributes_t *attributes,
1248     psa_key_slot_number_t *slot_number )
1249 {
1250     if( attributes->core.flags & MBEDTLS_PSA_KA_FLAG_HAS_SLOT_NUMBER )
1251     {
1252         *slot_number = attributes->slot_number;
1253         return( PSA_SUCCESS );
1254     }
1255     else
1256         return( PSA_ERROR_INVALID_ARGUMENT );
1257 }
1258 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1259 
psa_export_key_buffer_internal(const uint8_t * key_buffer,size_t key_buffer_size,uint8_t * data,size_t data_size,size_t * data_length)1260 static psa_status_t psa_export_key_buffer_internal( const uint8_t *key_buffer,
1261                                                     size_t key_buffer_size,
1262                                                     uint8_t *data,
1263                                                     size_t data_size,
1264                                                     size_t *data_length )
1265 {
1266     if( key_buffer_size > data_size )
1267         return( PSA_ERROR_BUFFER_TOO_SMALL );
1268     memcpy( data, key_buffer, key_buffer_size );
1269     memset( data + key_buffer_size, 0,
1270             data_size - key_buffer_size );
1271     *data_length = key_buffer_size;
1272     return( PSA_SUCCESS );
1273 }
1274 
psa_export_key_internal(const psa_key_attributes_t * attributes,const uint8_t * key_buffer,size_t key_buffer_size,uint8_t * data,size_t data_size,size_t * data_length)1275 psa_status_t psa_export_key_internal(
1276     const psa_key_attributes_t *attributes,
1277     const uint8_t *key_buffer, size_t key_buffer_size,
1278     uint8_t *data, size_t data_size, size_t *data_length )
1279 {
1280     psa_key_type_t type = attributes->core.type;
1281 
1282     if( key_type_is_raw_bytes( type ) ||
1283         PSA_KEY_TYPE_IS_RSA( type )   ||
1284         PSA_KEY_TYPE_IS_ECC( type )      )
1285     {
1286         return( psa_export_key_buffer_internal(
1287                     key_buffer, key_buffer_size,
1288                     data, data_size, data_length ) );
1289     }
1290     else
1291     {
1292         /* This shouldn't happen in the reference implementation, but
1293            it is valid for a special-purpose implementation to omit
1294            support for exporting certain key types. */
1295         return( PSA_ERROR_NOT_SUPPORTED );
1296     }
1297 }
1298 
psa_export_key(mbedtls_svc_key_id_t key,uint8_t * data,size_t data_size,size_t * data_length)1299 psa_status_t psa_export_key( mbedtls_svc_key_id_t key,
1300                              uint8_t *data,
1301                              size_t data_size,
1302                              size_t *data_length )
1303 {
1304     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
1305     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
1306     psa_key_slot_t *slot;
1307 
1308     /* Reject a zero-length output buffer now, since this can never be a
1309      * valid key representation. This way we know that data must be a valid
1310      * pointer and we can do things like memset(data, ..., data_size). */
1311     if( data_size == 0 )
1312         return( PSA_ERROR_BUFFER_TOO_SMALL );
1313 
1314     /* Set the key to empty now, so that even when there are errors, we always
1315      * set data_length to a value between 0 and data_size. On error, setting
1316      * the key to empty is a good choice because an empty key representation is
1317      * unlikely to be accepted anywhere. */
1318     *data_length = 0;
1319 
1320     /* Export requires the EXPORT flag. There is an exception for public keys,
1321      * which don't require any flag, but
1322      * psa_get_and_lock_key_slot_with_policy() takes care of this.
1323      */
1324     status = psa_get_and_lock_key_slot_with_policy( key, &slot,
1325                                                     PSA_KEY_USAGE_EXPORT, 0 );
1326     if( status != PSA_SUCCESS )
1327         return( status );
1328 
1329     psa_key_attributes_t attributes = {
1330         .core = slot->attr
1331     };
1332     status = psa_driver_wrapper_export_key( &attributes,
1333                  slot->key.data, slot->key.bytes,
1334                  data, data_size, data_length );
1335 
1336     unlock_status = psa_unlock_key_slot( slot );
1337 
1338     return( ( status == PSA_SUCCESS ) ? unlock_status : status );
1339 }
1340 
psa_export_public_key_internal(const psa_key_attributes_t * attributes,const uint8_t * key_buffer,size_t key_buffer_size,uint8_t * data,size_t data_size,size_t * data_length)1341 psa_status_t psa_export_public_key_internal(
1342     const psa_key_attributes_t *attributes,
1343     const uint8_t *key_buffer,
1344     size_t key_buffer_size,
1345     uint8_t *data,
1346     size_t data_size,
1347     size_t *data_length )
1348 {
1349     psa_key_type_t type = attributes->core.type;
1350 
1351     if( PSA_KEY_TYPE_IS_RSA( type ) || PSA_KEY_TYPE_IS_ECC( type ) )
1352     {
1353         if( PSA_KEY_TYPE_IS_PUBLIC_KEY( type ) )
1354         {
1355             /* Exporting public -> public */
1356             return( psa_export_key_buffer_internal(
1357                         key_buffer, key_buffer_size,
1358                         data, data_size, data_length ) );
1359         }
1360 
1361         if( PSA_KEY_TYPE_IS_RSA( type ) )
1362         {
1363 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) || \
1364     defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY)
1365             return( mbedtls_psa_rsa_export_public_key( attributes,
1366                                                        key_buffer,
1367                                                        key_buffer_size,
1368                                                        data,
1369                                                        data_size,
1370                                                        data_length ) );
1371 #else
1372             /* We don't know how to convert a private RSA key to public. */
1373             return( PSA_ERROR_NOT_SUPPORTED );
1374 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) ||
1375         * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY) */
1376         }
1377         else
1378         {
1379 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) || \
1380     defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY)
1381             return( mbedtls_psa_ecp_export_public_key( attributes,
1382                                                        key_buffer,
1383                                                        key_buffer_size,
1384                                                        data,
1385                                                        data_size,
1386                                                        data_length ) );
1387 #else
1388             /* We don't know how to convert a private ECC key to public */
1389             return( PSA_ERROR_NOT_SUPPORTED );
1390 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) ||
1391         * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY) */
1392         }
1393     }
1394     else
1395     {
1396         /* This shouldn't happen in the reference implementation, but
1397            it is valid for a special-purpose implementation to omit
1398            support for exporting certain key types. */
1399         return( PSA_ERROR_NOT_SUPPORTED );
1400     }
1401 }
1402 
psa_export_public_key(mbedtls_svc_key_id_t key,uint8_t * data,size_t data_size,size_t * data_length)1403 psa_status_t psa_export_public_key( mbedtls_svc_key_id_t key,
1404                                     uint8_t *data,
1405                                     size_t data_size,
1406                                     size_t *data_length )
1407 {
1408     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
1409     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
1410     psa_key_slot_t *slot;
1411 
1412     /* Reject a zero-length output buffer now, since this can never be a
1413      * valid key representation. This way we know that data must be a valid
1414      * pointer and we can do things like memset(data, ..., data_size). */
1415     if( data_size == 0 )
1416         return( PSA_ERROR_BUFFER_TOO_SMALL );
1417 
1418     /* Set the key to empty now, so that even when there are errors, we always
1419      * set data_length to a value between 0 and data_size. On error, setting
1420      * the key to empty is a good choice because an empty key representation is
1421      * unlikely to be accepted anywhere. */
1422     *data_length = 0;
1423 
1424     /* Exporting a public key doesn't require a usage flag. */
1425     status = psa_get_and_lock_key_slot_with_policy( key, &slot, 0, 0 );
1426     if( status != PSA_SUCCESS )
1427         return( status );
1428 
1429     if( ! PSA_KEY_TYPE_IS_ASYMMETRIC( slot->attr.type ) )
1430     {
1431          status = PSA_ERROR_INVALID_ARGUMENT;
1432          goto exit;
1433     }
1434 
1435     psa_key_attributes_t attributes = {
1436         .core = slot->attr
1437     };
1438     status = psa_driver_wrapper_export_public_key(
1439         &attributes, slot->key.data, slot->key.bytes,
1440         data, data_size, data_length );
1441 
1442 exit:
1443     unlock_status = psa_unlock_key_slot( slot );
1444 
1445     return( ( status == PSA_SUCCESS ) ? unlock_status : status );
1446 }
1447 
1448 #if defined(static_assert)
1449 static_assert( ( MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY & MBEDTLS_PSA_KA_MASK_DUAL_USE ) == 0,
1450                "One or more key attribute flag is listed as both external-only and dual-use" );
1451 static_assert( ( PSA_KA_MASK_INTERNAL_ONLY & MBEDTLS_PSA_KA_MASK_DUAL_USE ) == 0,
1452                "One or more key attribute flag is listed as both internal-only and dual-use" );
1453 static_assert( ( PSA_KA_MASK_INTERNAL_ONLY & MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY ) == 0,
1454                "One or more key attribute flag is listed as both internal-only and external-only" );
1455 #endif
1456 
1457 /** Validate that a key policy is internally well-formed.
1458  *
1459  * This function only rejects invalid policies. It does not validate the
1460  * consistency of the policy with respect to other attributes of the key
1461  * such as the key type.
1462  */
psa_validate_key_policy(const psa_key_policy_t * policy)1463 static psa_status_t psa_validate_key_policy( const psa_key_policy_t *policy )
1464 {
1465     if( ( policy->usage & ~( PSA_KEY_USAGE_EXPORT |
1466                              PSA_KEY_USAGE_COPY |
1467                              PSA_KEY_USAGE_ENCRYPT |
1468                              PSA_KEY_USAGE_DECRYPT |
1469                              PSA_KEY_USAGE_SIGN_MESSAGE |
1470                              PSA_KEY_USAGE_VERIFY_MESSAGE |
1471                              PSA_KEY_USAGE_SIGN_HASH |
1472                              PSA_KEY_USAGE_VERIFY_HASH |
1473                              PSA_KEY_USAGE_VERIFY_DERIVATION |
1474                              PSA_KEY_USAGE_DERIVE ) ) != 0 )
1475         return( PSA_ERROR_INVALID_ARGUMENT );
1476 
1477     return( PSA_SUCCESS );
1478 }
1479 
1480 /** Validate the internal consistency of key attributes.
1481  *
1482  * This function only rejects invalid attribute values. If does not
1483  * validate the consistency of the attributes with any key data that may
1484  * be involved in the creation of the key.
1485  *
1486  * Call this function early in the key creation process.
1487  *
1488  * \param[in] attributes    Key attributes for the new key.
1489  * \param[out] p_drv        On any return, the driver for the key, if any.
1490  *                          NULL for a transparent key.
1491  *
1492  */
psa_validate_key_attributes(const psa_key_attributes_t * attributes,psa_se_drv_table_entry_t ** p_drv)1493 static psa_status_t psa_validate_key_attributes(
1494     const psa_key_attributes_t *attributes,
1495     psa_se_drv_table_entry_t **p_drv )
1496 {
1497     psa_status_t status = PSA_ERROR_INVALID_ARGUMENT;
1498     psa_key_lifetime_t lifetime = psa_get_key_lifetime( attributes );
1499     mbedtls_svc_key_id_t key = psa_get_key_id( attributes );
1500 
1501     status = psa_validate_key_location( lifetime, p_drv );
1502     if( status != PSA_SUCCESS )
1503         return( status );
1504 
1505     status = psa_validate_key_persistence( lifetime );
1506     if( status != PSA_SUCCESS )
1507         return( status );
1508 
1509     if ( PSA_KEY_LIFETIME_IS_VOLATILE( lifetime ) )
1510     {
1511         if( MBEDTLS_SVC_KEY_ID_GET_KEY_ID( key ) != 0 )
1512             return( PSA_ERROR_INVALID_ARGUMENT );
1513     }
1514     else
1515     {
1516         if( !psa_is_valid_key_id( psa_get_key_id( attributes ), 0 ) )
1517             return( PSA_ERROR_INVALID_ARGUMENT );
1518     }
1519 
1520     status = psa_validate_key_policy( &attributes->core.policy );
1521     if( status != PSA_SUCCESS )
1522         return( status );
1523 
1524     /* Refuse to create overly large keys.
1525      * Note that this doesn't trigger on import if the attributes don't
1526      * explicitly specify a size (so psa_get_key_bits returns 0), so
1527      * psa_import_key() needs its own checks. */
1528     if( psa_get_key_bits( attributes ) > PSA_MAX_KEY_BITS )
1529         return( PSA_ERROR_NOT_SUPPORTED );
1530 
1531     /* Reject invalid flags. These should not be reachable through the API. */
1532     if( attributes->core.flags & ~ ( MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY |
1533                                      MBEDTLS_PSA_KA_MASK_DUAL_USE ) )
1534         return( PSA_ERROR_INVALID_ARGUMENT );
1535 
1536     return( PSA_SUCCESS );
1537 }
1538 
1539 /** Prepare a key slot to receive key material.
1540  *
1541  * This function allocates a key slot and sets its metadata.
1542  *
1543  * If this function fails, call psa_fail_key_creation().
1544  *
1545  * This function is intended to be used as follows:
1546  * -# Call psa_start_key_creation() to allocate a key slot, prepare
1547  *    it with the specified attributes, and in case of a volatile key assign it
1548  *    a volatile key identifier.
1549  * -# Populate the slot with the key material.
1550  * -# Call psa_finish_key_creation() to finalize the creation of the slot.
1551  * In case of failure at any step, stop the sequence and call
1552  * psa_fail_key_creation().
1553  *
1554  * On success, the key slot is locked. It is the responsibility of the caller
1555  * to unlock the key slot when it does not access it anymore.
1556  *
1557  * \param method            An identification of the calling function.
1558  * \param[in] attributes    Key attributes for the new key.
1559  * \param[out] p_slot       On success, a pointer to the prepared slot.
1560  * \param[out] p_drv        On any return, the driver for the key, if any.
1561  *                          NULL for a transparent key.
1562  *
1563  * \retval #PSA_SUCCESS
1564  *         The key slot is ready to receive key material.
1565  * \return If this function fails, the key slot is an invalid state.
1566  *         You must call psa_fail_key_creation() to wipe and free the slot.
1567  */
psa_start_key_creation(psa_key_creation_method_t method,const psa_key_attributes_t * attributes,psa_key_slot_t ** p_slot,psa_se_drv_table_entry_t ** p_drv)1568 static psa_status_t psa_start_key_creation(
1569     psa_key_creation_method_t method,
1570     const psa_key_attributes_t *attributes,
1571     psa_key_slot_t **p_slot,
1572     psa_se_drv_table_entry_t **p_drv )
1573 {
1574     psa_status_t status;
1575     psa_key_id_t volatile_key_id;
1576     psa_key_slot_t *slot;
1577 
1578     (void) method;
1579     *p_drv = NULL;
1580 
1581     status = psa_validate_key_attributes( attributes, p_drv );
1582     if( status != PSA_SUCCESS )
1583         return( status );
1584 
1585     status = psa_get_empty_key_slot( &volatile_key_id, p_slot );
1586     if( status != PSA_SUCCESS )
1587         return( status );
1588     slot = *p_slot;
1589 
1590     /* We're storing the declared bit-size of the key. It's up to each
1591      * creation mechanism to verify that this information is correct.
1592      * It's automatically correct for mechanisms that use the bit-size as
1593      * an input (generate, device) but not for those where the bit-size
1594      * is optional (import, copy). In case of a volatile key, assign it the
1595      * volatile key identifier associated to the slot returned to contain its
1596      * definition. */
1597 
1598     slot->attr = attributes->core;
1599     if( PSA_KEY_LIFETIME_IS_VOLATILE( slot->attr.lifetime ) )
1600     {
1601 #if !defined(MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER)
1602         slot->attr.id = volatile_key_id;
1603 #else
1604         slot->attr.id.key_id = volatile_key_id;
1605 #endif
1606     }
1607 
1608     /* Erase external-only flags from the internal copy. To access
1609      * external-only flags, query `attributes`. Thanks to the check
1610      * in psa_validate_key_attributes(), this leaves the dual-use
1611      * flags and any internal flag that psa_get_empty_key_slot()
1612      * may have set. */
1613     slot->attr.flags &= ~MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY;
1614 
1615 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1616     /* For a key in a secure element, we need to do three things
1617      * when creating or registering a persistent key:
1618      * create the key file in internal storage, create the
1619      * key inside the secure element, and update the driver's
1620      * persistent data. This is done by starting a transaction that will
1621      * encompass these three actions.
1622      * For registering a volatile key, we just need to find an appropriate
1623      * slot number inside the SE. Since the key is designated volatile, creating
1624      * a transaction is not required. */
1625     /* The first thing to do is to find a slot number for the new key.
1626      * We save the slot number in persistent storage as part of the
1627      * transaction data. It will be needed to recover if the power
1628      * fails during the key creation process, to clean up on the secure
1629      * element side after restarting. Obtaining a slot number from the
1630      * secure element driver updates its persistent state, but we do not yet
1631      * save the driver's persistent state, so that if the power fails,
1632      * we can roll back to a state where the key doesn't exist. */
1633     if( *p_drv != NULL )
1634     {
1635         psa_key_slot_number_t slot_number;
1636         status = psa_find_se_slot_for_key( attributes, method, *p_drv,
1637                                            &slot_number );
1638         if( status != PSA_SUCCESS )
1639             return( status );
1640 
1641         if( ! PSA_KEY_LIFETIME_IS_VOLATILE( attributes->core.lifetime ) )
1642         {
1643             psa_crypto_prepare_transaction( PSA_CRYPTO_TRANSACTION_CREATE_KEY );
1644             psa_crypto_transaction.key.lifetime = slot->attr.lifetime;
1645             psa_crypto_transaction.key.slot = slot_number;
1646             psa_crypto_transaction.key.id = slot->attr.id;
1647             status = psa_crypto_save_transaction( );
1648             if( status != PSA_SUCCESS )
1649             {
1650                 (void) psa_crypto_stop_transaction( );
1651                 return( status );
1652             }
1653         }
1654 
1655         status = psa_copy_key_material_into_slot(
1656             slot, (uint8_t *)( &slot_number ), sizeof( slot_number ) );
1657     }
1658 
1659     if( *p_drv == NULL && method == PSA_KEY_CREATION_REGISTER )
1660     {
1661         /* Key registration only makes sense with a secure element. */
1662         return( PSA_ERROR_INVALID_ARGUMENT );
1663     }
1664 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1665 
1666     return( PSA_SUCCESS );
1667 }
1668 
1669 /** Finalize the creation of a key once its key material has been set.
1670  *
1671  * This entails writing the key to persistent storage.
1672  *
1673  * If this function fails, call psa_fail_key_creation().
1674  * See the documentation of psa_start_key_creation() for the intended use
1675  * of this function.
1676  *
1677  * If the finalization succeeds, the function unlocks the key slot (it was
1678  * locked by psa_start_key_creation()) and the key slot cannot be accessed
1679  * anymore as part of the key creation process.
1680  *
1681  * \param[in,out] slot  Pointer to the slot with key material.
1682  * \param[in] driver    The secure element driver for the key,
1683  *                      or NULL for a transparent key.
1684  * \param[out] key      On success, identifier of the key. Note that the
1685  *                      key identifier is also stored in the key slot.
1686  *
1687  * \retval #PSA_SUCCESS
1688  *         The key was successfully created.
1689  * \retval #PSA_ERROR_INSUFFICIENT_MEMORY
1690  * \retval #PSA_ERROR_INSUFFICIENT_STORAGE
1691  * \retval #PSA_ERROR_ALREADY_EXISTS
1692  * \retval #PSA_ERROR_DATA_INVALID
1693  * \retval #PSA_ERROR_DATA_CORRUPT
1694  * \retval #PSA_ERROR_STORAGE_FAILURE
1695  *
1696  * \return If this function fails, the key slot is an invalid state.
1697  *         You must call psa_fail_key_creation() to wipe and free the slot.
1698  */
psa_finish_key_creation(psa_key_slot_t * slot,psa_se_drv_table_entry_t * driver,mbedtls_svc_key_id_t * key)1699 static psa_status_t psa_finish_key_creation(
1700     psa_key_slot_t *slot,
1701     psa_se_drv_table_entry_t *driver,
1702     mbedtls_svc_key_id_t *key)
1703 {
1704     psa_status_t status = PSA_SUCCESS;
1705     (void) slot;
1706     (void) driver;
1707 
1708 #if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C)
1709     if( ! PSA_KEY_LIFETIME_IS_VOLATILE( slot->attr.lifetime ) )
1710     {
1711 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1712         if( driver != NULL )
1713         {
1714             psa_se_key_data_storage_t data;
1715             psa_key_slot_number_t slot_number =
1716                 psa_key_slot_get_slot_number( slot ) ;
1717 
1718 #if defined(static_assert)
1719             static_assert( sizeof( slot_number ) ==
1720                            sizeof( data.slot_number ),
1721                            "Slot number size does not match psa_se_key_data_storage_t" );
1722 #endif
1723             memcpy( &data.slot_number, &slot_number, sizeof( slot_number ) );
1724             status = psa_save_persistent_key( &slot->attr,
1725                                               (uint8_t*) &data,
1726                                               sizeof( data ) );
1727         }
1728         else
1729 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1730         {
1731             /* Key material is saved in export representation in the slot, so
1732              * just pass the slot buffer for storage. */
1733             status = psa_save_persistent_key( &slot->attr,
1734                                               slot->key.data,
1735                                               slot->key.bytes );
1736         }
1737     }
1738 #endif /* defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) */
1739 
1740 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1741     /* Finish the transaction for a key creation. This does not
1742      * happen when registering an existing key. Detect this case
1743      * by checking whether a transaction is in progress (actual
1744      * creation of a persistent key in a secure element requires a transaction,
1745      * but registration or volatile key creation doesn't use one). */
1746     if( driver != NULL &&
1747         psa_crypto_transaction.unknown.type == PSA_CRYPTO_TRANSACTION_CREATE_KEY )
1748     {
1749         status = psa_save_se_persistent_data( driver );
1750         if( status != PSA_SUCCESS )
1751         {
1752             psa_destroy_persistent_key( slot->attr.id );
1753             return( status );
1754         }
1755         status = psa_crypto_stop_transaction( );
1756     }
1757 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1758 
1759     if( status == PSA_SUCCESS )
1760     {
1761         *key = slot->attr.id;
1762         status = psa_unlock_key_slot( slot );
1763         if( status != PSA_SUCCESS )
1764             *key = MBEDTLS_SVC_KEY_ID_INIT;
1765     }
1766 
1767     return( status );
1768 }
1769 
1770 /** Abort the creation of a key.
1771  *
1772  * You may call this function after calling psa_start_key_creation(),
1773  * or after psa_finish_key_creation() fails. In other circumstances, this
1774  * function may not clean up persistent storage.
1775  * See the documentation of psa_start_key_creation() for the intended use
1776  * of this function.
1777  *
1778  * \param[in,out] slot  Pointer to the slot with key material.
1779  * \param[in] driver    The secure element driver for the key,
1780  *                      or NULL for a transparent key.
1781  */
psa_fail_key_creation(psa_key_slot_t * slot,psa_se_drv_table_entry_t * driver)1782 static void psa_fail_key_creation( psa_key_slot_t *slot,
1783                                    psa_se_drv_table_entry_t *driver )
1784 {
1785     (void) driver;
1786 
1787     if( slot == NULL )
1788         return;
1789 
1790 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1791     /* TODO: If the key has already been created in the secure
1792      * element, and the failure happened later (when saving metadata
1793      * to internal storage), we need to destroy the key in the secure
1794      * element.
1795      * https://github.com/ARMmbed/mbed-crypto/issues/217
1796      */
1797 
1798     /* Abort the ongoing transaction if any (there may not be one if
1799      * the creation process failed before starting one, or if the
1800      * key creation is a registration of a key in a secure element).
1801      * Earlier functions must already have done what it takes to undo any
1802      * partial creation. All that's left is to update the transaction data
1803      * itself. */
1804     (void) psa_crypto_stop_transaction( );
1805 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1806 
1807     psa_wipe_key_slot( slot );
1808 }
1809 
1810 /** Validate optional attributes during key creation.
1811  *
1812  * Some key attributes are optional during key creation. If they are
1813  * specified in the attributes structure, check that they are consistent
1814  * with the data in the slot.
1815  *
1816  * This function should be called near the end of key creation, after
1817  * the slot in memory is fully populated but before saving persistent data.
1818  */
psa_validate_optional_attributes(const psa_key_slot_t * slot,const psa_key_attributes_t * attributes)1819 static psa_status_t psa_validate_optional_attributes(
1820     const psa_key_slot_t *slot,
1821     const psa_key_attributes_t *attributes )
1822 {
1823     if( attributes->core.type != 0 )
1824     {
1825         if( attributes->core.type != slot->attr.type )
1826             return( PSA_ERROR_INVALID_ARGUMENT );
1827     }
1828 
1829     if( attributes->domain_parameters_size != 0 )
1830     {
1831 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) || \
1832     defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY)
1833         if( PSA_KEY_TYPE_IS_RSA( slot->attr.type ) )
1834         {
1835             mbedtls_rsa_context *rsa = NULL;
1836             mbedtls_mpi actual, required;
1837             int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1838 
1839             psa_status_t status = mbedtls_psa_rsa_load_representation(
1840                                       slot->attr.type,
1841                                       slot->key.data,
1842                                       slot->key.bytes,
1843                                       &rsa );
1844             if( status != PSA_SUCCESS )
1845                 return( status );
1846 
1847             mbedtls_mpi_init( &actual );
1848             mbedtls_mpi_init( &required );
1849             ret = mbedtls_rsa_export( rsa,
1850                                       NULL, NULL, NULL, NULL, &actual );
1851             mbedtls_rsa_free( rsa );
1852             mbedtls_free( rsa );
1853             if( ret != 0 )
1854                 goto rsa_exit;
1855             ret = mbedtls_mpi_read_binary( &required,
1856                                            attributes->domain_parameters,
1857                                            attributes->domain_parameters_size );
1858             if( ret != 0 )
1859                 goto rsa_exit;
1860             if( mbedtls_mpi_cmp_mpi( &actual, &required ) != 0 )
1861                 ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1862         rsa_exit:
1863             mbedtls_mpi_free( &actual );
1864             mbedtls_mpi_free( &required );
1865             if( ret != 0)
1866                 return( mbedtls_to_psa_error( ret ) );
1867         }
1868         else
1869 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) ||
1870         * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY) */
1871         {
1872             return( PSA_ERROR_INVALID_ARGUMENT );
1873         }
1874     }
1875 
1876     if( attributes->core.bits != 0 )
1877     {
1878         if( attributes->core.bits != slot->attr.bits )
1879             return( PSA_ERROR_INVALID_ARGUMENT );
1880     }
1881 
1882     return( PSA_SUCCESS );
1883 }
1884 
psa_import_key(const psa_key_attributes_t * attributes,const uint8_t * data,size_t data_length,mbedtls_svc_key_id_t * key)1885 psa_status_t psa_import_key( const psa_key_attributes_t *attributes,
1886                              const uint8_t *data,
1887                              size_t data_length,
1888                              mbedtls_svc_key_id_t *key )
1889 {
1890     psa_status_t status;
1891     psa_key_slot_t *slot = NULL;
1892     psa_se_drv_table_entry_t *driver = NULL;
1893     size_t bits;
1894     size_t storage_size = data_length;
1895 
1896     *key = MBEDTLS_SVC_KEY_ID_INIT;
1897 
1898     /* Reject zero-length symmetric keys (including raw data key objects).
1899      * This also rejects any key which might be encoded as an empty string,
1900      * which is never valid. */
1901     if( data_length == 0 )
1902         return( PSA_ERROR_INVALID_ARGUMENT );
1903 
1904     /* Ensure that the bytes-to-bits conversion cannot overflow. */
1905     if( data_length > SIZE_MAX / 8 )
1906         return( PSA_ERROR_NOT_SUPPORTED );
1907 
1908     status = psa_start_key_creation( PSA_KEY_CREATION_IMPORT, attributes,
1909                                      &slot, &driver );
1910     if( status != PSA_SUCCESS )
1911         goto exit;
1912 
1913     /* In the case of a transparent key or an opaque key stored in local
1914      * storage ( thus not in the case of importing a key in a secure element
1915      * with storage ( MBEDTLS_PSA_CRYPTO_SE_C ) ),we have to allocate a
1916      * buffer to hold the imported key material. */
1917     if( slot->key.data == NULL )
1918     {
1919         if( psa_key_lifetime_is_external( attributes->core.lifetime ) )
1920         {
1921             status = psa_driver_wrapper_get_key_buffer_size_from_key_data(
1922                          attributes, data, data_length, &storage_size );
1923             if( status != PSA_SUCCESS )
1924                 goto exit;
1925         }
1926         status = psa_allocate_buffer_to_slot( slot, storage_size );
1927         if( status != PSA_SUCCESS )
1928             goto exit;
1929     }
1930 
1931     bits = slot->attr.bits;
1932     status = psa_driver_wrapper_import_key( attributes,
1933                                             data, data_length,
1934                                             slot->key.data,
1935                                             slot->key.bytes,
1936                                             &slot->key.bytes, &bits );
1937     if( status != PSA_SUCCESS )
1938         goto exit;
1939 
1940     if( slot->attr.bits == 0 )
1941         slot->attr.bits = (psa_key_bits_t) bits;
1942     else if( bits != slot->attr.bits )
1943     {
1944         status = PSA_ERROR_INVALID_ARGUMENT;
1945         goto exit;
1946     }
1947 
1948     /* Enforce a size limit, and in particular ensure that the bit
1949      * size fits in its representation type.*/
1950     if( bits > PSA_MAX_KEY_BITS )
1951     {
1952         status = PSA_ERROR_NOT_SUPPORTED;
1953         goto exit;
1954     }
1955     status = psa_validate_optional_attributes( slot, attributes );
1956     if( status != PSA_SUCCESS )
1957         goto exit;
1958 
1959     status = psa_finish_key_creation( slot, driver, key );
1960 exit:
1961     if( status != PSA_SUCCESS )
1962         psa_fail_key_creation( slot, driver );
1963 
1964     return( status );
1965 }
1966 
1967 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
mbedtls_psa_register_se_key(const psa_key_attributes_t * attributes)1968 psa_status_t mbedtls_psa_register_se_key(
1969     const psa_key_attributes_t *attributes )
1970 {
1971     psa_status_t status;
1972     psa_key_slot_t *slot = NULL;
1973     psa_se_drv_table_entry_t *driver = NULL;
1974     mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
1975 
1976     /* Leaving attributes unspecified is not currently supported.
1977      * It could make sense to query the key type and size from the
1978      * secure element, but not all secure elements support this
1979      * and the driver HAL doesn't currently support it. */
1980     if( psa_get_key_type( attributes ) == PSA_KEY_TYPE_NONE )
1981         return( PSA_ERROR_NOT_SUPPORTED );
1982     if( psa_get_key_bits( attributes ) == 0 )
1983         return( PSA_ERROR_NOT_SUPPORTED );
1984 
1985     status = psa_start_key_creation( PSA_KEY_CREATION_REGISTER, attributes,
1986                                      &slot, &driver );
1987     if( status != PSA_SUCCESS )
1988         goto exit;
1989 
1990     status = psa_finish_key_creation( slot, driver, &key );
1991 
1992 exit:
1993     if( status != PSA_SUCCESS )
1994         psa_fail_key_creation( slot, driver );
1995 
1996     /* Registration doesn't keep the key in RAM. */
1997     psa_close_key( key );
1998     return( status );
1999 }
2000 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
2001 
psa_copy_key(mbedtls_svc_key_id_t source_key,const psa_key_attributes_t * specified_attributes,mbedtls_svc_key_id_t * target_key)2002 psa_status_t psa_copy_key( mbedtls_svc_key_id_t source_key,
2003                            const psa_key_attributes_t *specified_attributes,
2004                            mbedtls_svc_key_id_t *target_key )
2005 {
2006     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2007     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
2008     psa_key_slot_t *source_slot = NULL;
2009     psa_key_slot_t *target_slot = NULL;
2010     psa_key_attributes_t actual_attributes = *specified_attributes;
2011     psa_se_drv_table_entry_t *driver = NULL;
2012     size_t storage_size = 0;
2013 
2014     *target_key = MBEDTLS_SVC_KEY_ID_INIT;
2015 
2016     status = psa_get_and_lock_key_slot_with_policy(
2017                  source_key, &source_slot, PSA_KEY_USAGE_COPY, 0 );
2018     if( status != PSA_SUCCESS )
2019         goto exit;
2020 
2021     status = psa_validate_optional_attributes( source_slot,
2022                                                specified_attributes );
2023     if( status != PSA_SUCCESS )
2024         goto exit;
2025 
2026     /* The target key type and number of bits have been validated by
2027      * psa_validate_optional_attributes() to be either equal to zero or
2028      * equal to the ones of the source key. So it is safe to inherit
2029      * them from the source key now."
2030      * */
2031     actual_attributes.core.bits = source_slot->attr.bits;
2032     actual_attributes.core.type = source_slot->attr.type;
2033 
2034 
2035     status = psa_restrict_key_policy( source_slot->attr.type,
2036                                       &actual_attributes.core.policy,
2037                                       &source_slot->attr.policy );
2038     if( status != PSA_SUCCESS )
2039         goto exit;
2040 
2041     status = psa_start_key_creation( PSA_KEY_CREATION_COPY, &actual_attributes,
2042                                      &target_slot, &driver );
2043     if( status != PSA_SUCCESS )
2044         goto exit;
2045     if( PSA_KEY_LIFETIME_GET_LOCATION( target_slot->attr.lifetime ) !=
2046         PSA_KEY_LIFETIME_GET_LOCATION( source_slot->attr.lifetime ) )
2047     {
2048         /*
2049          * If the source and target keys are stored in different locations,
2050          * the source key would need to be exported as plaintext and re-imported
2051          * in the other location. This has security implications which have not
2052          * been fully mapped. For now, this can be achieved through
2053          * appropriate API invocations from the application, if needed.
2054          * */
2055         status = PSA_ERROR_NOT_SUPPORTED;
2056         goto exit;
2057     }
2058     /*
2059      * When the source and target keys are within the same location,
2060      * - For transparent keys it is a blind copy without any driver invocation,
2061      * - For opaque keys this translates to an invocation of the drivers'
2062      *   copy_key entry point through the dispatch layer.
2063      * */
2064     if( psa_key_lifetime_is_external( actual_attributes.core.lifetime ) )
2065     {
2066         status = psa_driver_wrapper_get_key_buffer_size( &actual_attributes,
2067                                                          &storage_size );
2068         if( status != PSA_SUCCESS )
2069             goto exit;
2070 
2071         status = psa_allocate_buffer_to_slot( target_slot, storage_size );
2072         if( status != PSA_SUCCESS )
2073             goto exit;
2074 
2075         status = psa_driver_wrapper_copy_key( &actual_attributes,
2076                                               source_slot->key.data,
2077                                               source_slot->key.bytes,
2078                                               target_slot->key.data,
2079                                               target_slot->key.bytes,
2080                                               &target_slot->key.bytes );
2081         if( status != PSA_SUCCESS )
2082             goto exit;
2083     }
2084     else
2085     {
2086        status = psa_copy_key_material_into_slot( target_slot,
2087                                                  source_slot->key.data,
2088                                                  source_slot->key.bytes );
2089         if( status != PSA_SUCCESS )
2090             goto exit;
2091     }
2092     status = psa_finish_key_creation( target_slot, driver, target_key );
2093 exit:
2094     if( status != PSA_SUCCESS )
2095         psa_fail_key_creation( target_slot, driver );
2096 
2097     unlock_status = psa_unlock_key_slot( source_slot );
2098 
2099     return( ( status == PSA_SUCCESS ) ? unlock_status : status );
2100 }
2101 
2102 
2103 
2104 /****************************************************************/
2105 /* Message digests */
2106 /****************************************************************/
2107 
psa_hash_abort(psa_hash_operation_t * operation)2108 psa_status_t psa_hash_abort( psa_hash_operation_t *operation )
2109 {
2110     /* Aborting a non-active operation is allowed */
2111     if( operation->id == 0 )
2112         return( PSA_SUCCESS );
2113 
2114     psa_status_t status = psa_driver_wrapper_hash_abort( operation );
2115     operation->id = 0;
2116 
2117     return( status );
2118 }
2119 
psa_hash_setup(psa_hash_operation_t * operation,psa_algorithm_t alg)2120 psa_status_t psa_hash_setup( psa_hash_operation_t *operation,
2121                              psa_algorithm_t alg )
2122 {
2123     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2124 
2125     /* A context must be freshly initialized before it can be set up. */
2126     if( operation->id != 0 )
2127     {
2128         status = PSA_ERROR_BAD_STATE;
2129         goto exit;
2130     }
2131 
2132     if( !PSA_ALG_IS_HASH( alg ) )
2133     {
2134         status = PSA_ERROR_INVALID_ARGUMENT;
2135         goto exit;
2136     }
2137 
2138     /* Ensure all of the context is zeroized, since PSA_HASH_OPERATION_INIT only
2139      * directly zeroes the int-sized dummy member of the context union. */
2140     memset( &operation->ctx, 0, sizeof( operation->ctx ) );
2141 
2142     status = psa_driver_wrapper_hash_setup( operation, alg );
2143 
2144 exit:
2145     if( status != PSA_SUCCESS )
2146         psa_hash_abort( operation );
2147 
2148     return status;
2149 }
2150 
psa_hash_update(psa_hash_operation_t * operation,const uint8_t * input,size_t input_length)2151 psa_status_t psa_hash_update( psa_hash_operation_t *operation,
2152                               const uint8_t *input,
2153                               size_t input_length )
2154 {
2155     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2156 
2157     if( operation->id == 0 )
2158     {
2159         status = PSA_ERROR_BAD_STATE;
2160         goto exit;
2161     }
2162 
2163     /* Don't require hash implementations to behave correctly on a
2164      * zero-length input, which may have an invalid pointer. */
2165     if( input_length == 0 )
2166         return( PSA_SUCCESS );
2167 
2168     status = psa_driver_wrapper_hash_update( operation, input, input_length );
2169 
2170 exit:
2171     if( status != PSA_SUCCESS )
2172         psa_hash_abort( operation );
2173 
2174     return( status );
2175 }
2176 
psa_hash_finish(psa_hash_operation_t * operation,uint8_t * hash,size_t hash_size,size_t * hash_length)2177 psa_status_t psa_hash_finish( psa_hash_operation_t *operation,
2178                               uint8_t *hash,
2179                               size_t hash_size,
2180                               size_t *hash_length )
2181 {
2182     *hash_length = 0;
2183     if( operation->id == 0 )
2184         return( PSA_ERROR_BAD_STATE );
2185 
2186     psa_status_t status = psa_driver_wrapper_hash_finish(
2187                             operation, hash, hash_size, hash_length );
2188     psa_hash_abort( operation );
2189     return( status );
2190 }
2191 
psa_hash_verify(psa_hash_operation_t * operation,const uint8_t * hash,size_t hash_length)2192 psa_status_t psa_hash_verify( psa_hash_operation_t *operation,
2193                               const uint8_t *hash,
2194                               size_t hash_length )
2195 {
2196     uint8_t actual_hash[MBEDTLS_MD_MAX_SIZE];
2197     size_t actual_hash_length;
2198     psa_status_t status = psa_hash_finish(
2199                             operation,
2200                             actual_hash, sizeof( actual_hash ),
2201                             &actual_hash_length );
2202 
2203     if( status != PSA_SUCCESS )
2204         goto exit;
2205 
2206     if( actual_hash_length != hash_length )
2207     {
2208         status = PSA_ERROR_INVALID_SIGNATURE;
2209         goto exit;
2210     }
2211 
2212     if( mbedtls_psa_safer_memcmp( hash, actual_hash, actual_hash_length ) != 0 )
2213         status = PSA_ERROR_INVALID_SIGNATURE;
2214 
2215 exit:
2216     if( status != PSA_SUCCESS )
2217         psa_hash_abort(operation);
2218 
2219     return( status );
2220 }
2221 
psa_hash_compute(psa_algorithm_t alg,const uint8_t * input,size_t input_length,uint8_t * hash,size_t hash_size,size_t * hash_length)2222 psa_status_t psa_hash_compute( psa_algorithm_t alg,
2223                                const uint8_t *input, size_t input_length,
2224                                uint8_t *hash, size_t hash_size,
2225                                size_t *hash_length )
2226 {
2227     *hash_length = 0;
2228     if( !PSA_ALG_IS_HASH( alg ) )
2229         return( PSA_ERROR_INVALID_ARGUMENT );
2230 
2231     return( psa_driver_wrapper_hash_compute( alg, input, input_length,
2232                                              hash, hash_size, hash_length ) );
2233 }
2234 
psa_hash_compare(psa_algorithm_t alg,const uint8_t * input,size_t input_length,const uint8_t * hash,size_t hash_length)2235 psa_status_t psa_hash_compare( psa_algorithm_t alg,
2236                                const uint8_t *input, size_t input_length,
2237                                const uint8_t *hash, size_t hash_length )
2238 {
2239     uint8_t actual_hash[MBEDTLS_MD_MAX_SIZE];
2240     size_t actual_hash_length;
2241 
2242     if( !PSA_ALG_IS_HASH( alg ) )
2243         return( PSA_ERROR_INVALID_ARGUMENT );
2244 
2245     psa_status_t status = psa_driver_wrapper_hash_compute(
2246                             alg, input, input_length,
2247                             actual_hash, sizeof(actual_hash),
2248                             &actual_hash_length );
2249     if( status != PSA_SUCCESS )
2250         return( status );
2251     if( actual_hash_length != hash_length )
2252         return( PSA_ERROR_INVALID_SIGNATURE );
2253     if( mbedtls_psa_safer_memcmp( hash, actual_hash, actual_hash_length ) != 0 )
2254         return( PSA_ERROR_INVALID_SIGNATURE );
2255     return( PSA_SUCCESS );
2256 }
2257 
psa_hash_clone(const psa_hash_operation_t * source_operation,psa_hash_operation_t * target_operation)2258 psa_status_t psa_hash_clone( const psa_hash_operation_t *source_operation,
2259                              psa_hash_operation_t *target_operation )
2260 {
2261     if( source_operation->id == 0 ||
2262         target_operation->id != 0 )
2263     {
2264         return( PSA_ERROR_BAD_STATE );
2265     }
2266 
2267     psa_status_t status = psa_driver_wrapper_hash_clone( source_operation,
2268                                                          target_operation );
2269     if( status != PSA_SUCCESS )
2270         psa_hash_abort( target_operation );
2271 
2272     return( status );
2273 }
2274 
2275 
2276 /****************************************************************/
2277 /* MAC */
2278 /****************************************************************/
2279 
psa_mac_abort(psa_mac_operation_t * operation)2280 psa_status_t psa_mac_abort( psa_mac_operation_t *operation )
2281 {
2282     /* Aborting a non-active operation is allowed */
2283     if( operation->id == 0 )
2284         return( PSA_SUCCESS );
2285 
2286     psa_status_t status = psa_driver_wrapper_mac_abort( operation );
2287     operation->mac_size = 0;
2288     operation->is_sign = 0;
2289     operation->id = 0;
2290 
2291     return( status );
2292 }
2293 
psa_mac_finalize_alg_and_key_validation(psa_algorithm_t alg,const psa_key_attributes_t * attributes,uint8_t * mac_size)2294 static psa_status_t psa_mac_finalize_alg_and_key_validation(
2295     psa_algorithm_t alg,
2296     const psa_key_attributes_t *attributes,
2297     uint8_t *mac_size )
2298 {
2299     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2300     psa_key_type_t key_type = psa_get_key_type( attributes );
2301     size_t key_bits = psa_get_key_bits( attributes );
2302 
2303     if( ! PSA_ALG_IS_MAC( alg ) )
2304         return( PSA_ERROR_INVALID_ARGUMENT );
2305 
2306     /* Validate the combination of key type and algorithm */
2307     status = psa_mac_key_can_do( alg, key_type );
2308     if( status != PSA_SUCCESS )
2309         return( status );
2310 
2311     /* Get the output length for the algorithm and key combination */
2312     *mac_size = PSA_MAC_LENGTH( key_type, key_bits, alg );
2313 
2314     if( *mac_size < 4 )
2315     {
2316         /* A very short MAC is too short for security since it can be
2317          * brute-forced. Ancient protocols with 32-bit MACs do exist,
2318          * so we make this our minimum, even though 32 bits is still
2319          * too small for security. */
2320         return( PSA_ERROR_NOT_SUPPORTED );
2321     }
2322 
2323     if( *mac_size > PSA_MAC_LENGTH( key_type, key_bits,
2324                                     PSA_ALG_FULL_LENGTH_MAC( alg ) ) )
2325     {
2326         /* It's impossible to "truncate" to a larger length than the full length
2327          * of the algorithm. */
2328         return( PSA_ERROR_INVALID_ARGUMENT );
2329     }
2330 
2331     return( PSA_SUCCESS );
2332 }
2333 
psa_mac_setup(psa_mac_operation_t * operation,mbedtls_svc_key_id_t key,psa_algorithm_t alg,int is_sign)2334 static psa_status_t psa_mac_setup( psa_mac_operation_t *operation,
2335                                    mbedtls_svc_key_id_t key,
2336                                    psa_algorithm_t alg,
2337                                    int is_sign )
2338 {
2339     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2340     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
2341     psa_key_slot_t *slot = NULL;
2342 
2343     /* A context must be freshly initialized before it can be set up. */
2344     if( operation->id != 0 )
2345     {
2346         status = PSA_ERROR_BAD_STATE;
2347         goto exit;
2348     }
2349 
2350     status = psa_get_and_lock_key_slot_with_policy(
2351                  key,
2352                  &slot,
2353                  is_sign ? PSA_KEY_USAGE_SIGN_MESSAGE : PSA_KEY_USAGE_VERIFY_MESSAGE,
2354                  alg );
2355     if( status != PSA_SUCCESS )
2356         goto exit;
2357 
2358     psa_key_attributes_t attributes = {
2359         .core = slot->attr
2360     };
2361 
2362     status = psa_mac_finalize_alg_and_key_validation( alg, &attributes,
2363                                                       &operation->mac_size );
2364     if( status != PSA_SUCCESS )
2365         goto exit;
2366 
2367     operation->is_sign = is_sign;
2368     /* Dispatch the MAC setup call with validated input */
2369     if( is_sign )
2370     {
2371         status = psa_driver_wrapper_mac_sign_setup( operation,
2372                                                     &attributes,
2373                                                     slot->key.data,
2374                                                     slot->key.bytes,
2375                                                     alg );
2376     }
2377     else
2378     {
2379         status = psa_driver_wrapper_mac_verify_setup( operation,
2380                                                       &attributes,
2381                                                       slot->key.data,
2382                                                       slot->key.bytes,
2383                                                       alg );
2384     }
2385 
2386 exit:
2387     if( status != PSA_SUCCESS )
2388         psa_mac_abort( operation );
2389 
2390     unlock_status = psa_unlock_key_slot( slot );
2391 
2392     return( ( status == PSA_SUCCESS ) ? unlock_status : status );
2393 }
2394 
psa_mac_sign_setup(psa_mac_operation_t * operation,mbedtls_svc_key_id_t key,psa_algorithm_t alg)2395 psa_status_t psa_mac_sign_setup( psa_mac_operation_t *operation,
2396                                  mbedtls_svc_key_id_t key,
2397                                  psa_algorithm_t alg )
2398 {
2399     return( psa_mac_setup( operation, key, alg, 1 ) );
2400 }
2401 
psa_mac_verify_setup(psa_mac_operation_t * operation,mbedtls_svc_key_id_t key,psa_algorithm_t alg)2402 psa_status_t psa_mac_verify_setup( psa_mac_operation_t *operation,
2403                                    mbedtls_svc_key_id_t key,
2404                                    psa_algorithm_t alg )
2405 {
2406     return( psa_mac_setup( operation, key, alg, 0 ) );
2407 }
2408 
psa_mac_update(psa_mac_operation_t * operation,const uint8_t * input,size_t input_length)2409 psa_status_t psa_mac_update( psa_mac_operation_t *operation,
2410                              const uint8_t *input,
2411                              size_t input_length )
2412 {
2413     if( operation->id == 0 )
2414         return( PSA_ERROR_BAD_STATE );
2415 
2416     /* Don't require hash implementations to behave correctly on a
2417      * zero-length input, which may have an invalid pointer. */
2418     if( input_length == 0 )
2419         return( PSA_SUCCESS );
2420 
2421     psa_status_t status = psa_driver_wrapper_mac_update( operation,
2422                                                          input, input_length );
2423     if( status != PSA_SUCCESS )
2424         psa_mac_abort( operation );
2425 
2426     return( status );
2427 }
2428 
psa_mac_sign_finish(psa_mac_operation_t * operation,uint8_t * mac,size_t mac_size,size_t * mac_length)2429 psa_status_t psa_mac_sign_finish( psa_mac_operation_t *operation,
2430                                   uint8_t *mac,
2431                                   size_t mac_size,
2432                                   size_t *mac_length )
2433 {
2434     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2435     psa_status_t abort_status = PSA_ERROR_CORRUPTION_DETECTED;
2436 
2437     if( operation->id == 0 )
2438     {
2439         status = PSA_ERROR_BAD_STATE;
2440         goto exit;
2441     }
2442 
2443     if( ! operation->is_sign )
2444     {
2445         status = PSA_ERROR_BAD_STATE;
2446         goto exit;
2447     }
2448 
2449     /* Sanity check. This will guarantee that mac_size != 0 (and so mac != NULL)
2450      * once all the error checks are done. */
2451     if( operation->mac_size == 0 )
2452     {
2453         status = PSA_ERROR_BAD_STATE;
2454         goto exit;
2455     }
2456 
2457     if( mac_size < operation->mac_size )
2458     {
2459         status = PSA_ERROR_BUFFER_TOO_SMALL;
2460         goto exit;
2461     }
2462 
2463     status = psa_driver_wrapper_mac_sign_finish( operation,
2464                                                  mac, operation->mac_size,
2465                                                  mac_length );
2466 
2467 exit:
2468     /* In case of success, set the potential excess room in the output buffer
2469      * to an invalid value, to avoid potentially leaking a longer MAC.
2470      * In case of error, set the output length and content to a safe default,
2471      * such that in case the caller misses an error check, the output would be
2472      * an unachievable MAC.
2473      */
2474     if( status != PSA_SUCCESS )
2475     {
2476         *mac_length = mac_size;
2477         operation->mac_size = 0;
2478     }
2479 
2480     if( mac_size > operation->mac_size )
2481         memset( &mac[operation->mac_size], '!',
2482                 mac_size - operation->mac_size );
2483 
2484     abort_status = psa_mac_abort( operation );
2485 
2486     return( status == PSA_SUCCESS ? abort_status : status );
2487 }
2488 
psa_mac_verify_finish(psa_mac_operation_t * operation,const uint8_t * mac,size_t mac_length)2489 psa_status_t psa_mac_verify_finish( psa_mac_operation_t *operation,
2490                                     const uint8_t *mac,
2491                                     size_t mac_length )
2492 {
2493     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2494     psa_status_t abort_status = PSA_ERROR_CORRUPTION_DETECTED;
2495 
2496     if( operation->id == 0 )
2497     {
2498         status = PSA_ERROR_BAD_STATE;
2499         goto exit;
2500     }
2501 
2502     if( operation->is_sign )
2503     {
2504         status = PSA_ERROR_BAD_STATE;
2505         goto exit;
2506     }
2507 
2508     if( operation->mac_size != mac_length )
2509     {
2510         status = PSA_ERROR_INVALID_SIGNATURE;
2511         goto exit;
2512     }
2513 
2514     status = psa_driver_wrapper_mac_verify_finish( operation,
2515                                                    mac, mac_length );
2516 
2517 exit:
2518     abort_status = psa_mac_abort( operation );
2519 
2520     return( status == PSA_SUCCESS ? abort_status : status );
2521 }
2522 
psa_mac_compute_internal(mbedtls_svc_key_id_t key,psa_algorithm_t alg,const uint8_t * input,size_t input_length,uint8_t * mac,size_t mac_size,size_t * mac_length,int is_sign)2523 static psa_status_t psa_mac_compute_internal( mbedtls_svc_key_id_t key,
2524                                               psa_algorithm_t alg,
2525                                               const uint8_t *input,
2526                                               size_t input_length,
2527                                               uint8_t *mac,
2528                                               size_t mac_size,
2529                                               size_t *mac_length,
2530                                               int is_sign )
2531 {
2532     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2533     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
2534     psa_key_slot_t *slot;
2535     uint8_t operation_mac_size = 0;
2536 
2537     status = psa_get_and_lock_key_slot_with_policy(
2538                  key,
2539                  &slot,
2540                  is_sign ? PSA_KEY_USAGE_SIGN_MESSAGE : PSA_KEY_USAGE_VERIFY_MESSAGE,
2541                  alg );
2542     if( status != PSA_SUCCESS )
2543         goto exit;
2544 
2545     psa_key_attributes_t attributes = {
2546         .core = slot->attr
2547     };
2548 
2549     status = psa_mac_finalize_alg_and_key_validation( alg, &attributes,
2550                                                       &operation_mac_size );
2551     if( status != PSA_SUCCESS )
2552         goto exit;
2553 
2554     if( mac_size < operation_mac_size )
2555     {
2556         status = PSA_ERROR_BUFFER_TOO_SMALL;
2557         goto exit;
2558     }
2559 
2560     status = psa_driver_wrapper_mac_compute(
2561                  &attributes,
2562                  slot->key.data, slot->key.bytes,
2563                  alg,
2564                  input, input_length,
2565                  mac, operation_mac_size, mac_length );
2566 
2567 exit:
2568     /* In case of success, set the potential excess room in the output buffer
2569      * to an invalid value, to avoid potentially leaking a longer MAC.
2570      * In case of error, set the output length and content to a safe default,
2571      * such that in case the caller misses an error check, the output would be
2572      * an unachievable MAC.
2573      */
2574     if( status != PSA_SUCCESS )
2575     {
2576         *mac_length = mac_size;
2577         operation_mac_size = 0;
2578     }
2579     if( mac_size > operation_mac_size )
2580         memset( &mac[operation_mac_size], '!', mac_size - operation_mac_size );
2581 
2582     unlock_status = psa_unlock_key_slot( slot );
2583 
2584     return( ( status == PSA_SUCCESS ) ? unlock_status : status );
2585 }
2586 
psa_mac_compute(mbedtls_svc_key_id_t key,psa_algorithm_t alg,const uint8_t * input,size_t input_length,uint8_t * mac,size_t mac_size,size_t * mac_length)2587 psa_status_t psa_mac_compute( mbedtls_svc_key_id_t key,
2588                               psa_algorithm_t alg,
2589                               const uint8_t *input,
2590                               size_t input_length,
2591                               uint8_t *mac,
2592                               size_t mac_size,
2593                               size_t *mac_length)
2594 {
2595     return( psa_mac_compute_internal( key, alg,
2596                                       input, input_length,
2597                                       mac, mac_size, mac_length, 1 ) );
2598 }
2599 
psa_mac_verify(mbedtls_svc_key_id_t key,psa_algorithm_t alg,const uint8_t * input,size_t input_length,const uint8_t * mac,size_t mac_length)2600 psa_status_t psa_mac_verify( mbedtls_svc_key_id_t key,
2601                              psa_algorithm_t alg,
2602                              const uint8_t *input,
2603                              size_t input_length,
2604                              const uint8_t *mac,
2605                              size_t mac_length)
2606 {
2607     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2608     uint8_t actual_mac[PSA_MAC_MAX_SIZE];
2609     size_t actual_mac_length;
2610 
2611     status = psa_mac_compute_internal( key, alg,
2612                                        input, input_length,
2613                                        actual_mac, sizeof( actual_mac ),
2614                                        &actual_mac_length, 0 );
2615     if( status != PSA_SUCCESS )
2616         goto exit;
2617 
2618     if( mac_length != actual_mac_length )
2619     {
2620         status = PSA_ERROR_INVALID_SIGNATURE;
2621         goto exit;
2622     }
2623     if( mbedtls_psa_safer_memcmp( mac, actual_mac, actual_mac_length ) != 0 )
2624     {
2625         status = PSA_ERROR_INVALID_SIGNATURE;
2626         goto exit;
2627     }
2628 
2629 exit:
2630     mbedtls_platform_zeroize( actual_mac, sizeof( actual_mac ) );
2631 
2632     return ( status );
2633 }
2634 
2635 /****************************************************************/
2636 /* Asymmetric cryptography */
2637 /****************************************************************/
2638 
psa_sign_verify_check_alg(int input_is_message,psa_algorithm_t alg)2639 static psa_status_t psa_sign_verify_check_alg( int input_is_message,
2640                                                psa_algorithm_t alg )
2641 {
2642     if( input_is_message )
2643     {
2644         if( ! PSA_ALG_IS_SIGN_MESSAGE( alg ) )
2645             return( PSA_ERROR_INVALID_ARGUMENT );
2646 
2647         if ( PSA_ALG_IS_SIGN_HASH( alg ) )
2648         {
2649             if( ! PSA_ALG_IS_HASH( PSA_ALG_SIGN_GET_HASH( alg ) ) )
2650                 return( PSA_ERROR_INVALID_ARGUMENT );
2651         }
2652     }
2653     else
2654     {
2655         if( ! PSA_ALG_IS_SIGN_HASH( alg ) )
2656             return( PSA_ERROR_INVALID_ARGUMENT );
2657     }
2658 
2659     return( PSA_SUCCESS );
2660 }
2661 
psa_sign_internal(mbedtls_svc_key_id_t key,int input_is_message,psa_algorithm_t alg,const uint8_t * input,size_t input_length,uint8_t * signature,size_t signature_size,size_t * signature_length)2662 static psa_status_t psa_sign_internal( mbedtls_svc_key_id_t key,
2663                                        int input_is_message,
2664                                        psa_algorithm_t alg,
2665                                        const uint8_t * input,
2666                                        size_t input_length,
2667                                        uint8_t * signature,
2668                                        size_t signature_size,
2669                                        size_t * signature_length )
2670 {
2671     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2672     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
2673     psa_key_slot_t *slot;
2674 
2675     *signature_length = 0;
2676 
2677     status = psa_sign_verify_check_alg( input_is_message, alg );
2678     if( status != PSA_SUCCESS )
2679         return status;
2680 
2681     /* Immediately reject a zero-length signature buffer. This guarantees
2682      * that signature must be a valid pointer. (On the other hand, the input
2683      * buffer can in principle be empty since it doesn't actually have
2684      * to be a hash.) */
2685     if( signature_size == 0 )
2686         return( PSA_ERROR_BUFFER_TOO_SMALL );
2687 
2688     status = psa_get_and_lock_key_slot_with_policy(
2689                 key, &slot,
2690                 input_is_message ? PSA_KEY_USAGE_SIGN_MESSAGE :
2691                                    PSA_KEY_USAGE_SIGN_HASH,
2692                 alg );
2693 
2694     if( status != PSA_SUCCESS )
2695         goto exit;
2696 
2697     if( ! PSA_KEY_TYPE_IS_KEY_PAIR( slot->attr.type ) )
2698     {
2699         status = PSA_ERROR_INVALID_ARGUMENT;
2700         goto exit;
2701     }
2702 
2703     psa_key_attributes_t attributes = {
2704       .core = slot->attr
2705     };
2706 
2707     if( input_is_message )
2708     {
2709         status = psa_driver_wrapper_sign_message(
2710             &attributes, slot->key.data, slot->key.bytes,
2711             alg, input, input_length,
2712             signature, signature_size, signature_length );
2713     }
2714     else
2715     {
2716 
2717         status = psa_driver_wrapper_sign_hash(
2718             &attributes, slot->key.data, slot->key.bytes,
2719             alg, input, input_length,
2720             signature, signature_size, signature_length );
2721     }
2722 
2723 
2724 exit:
2725     /* Fill the unused part of the output buffer (the whole buffer on error,
2726      * the trailing part on success) with something that isn't a valid signature
2727      * (barring an attack on the signature and deliberately-crafted input),
2728      * in case the caller doesn't check the return status properly. */
2729     if( status == PSA_SUCCESS )
2730         memset( signature + *signature_length, '!',
2731                 signature_size - *signature_length );
2732     else
2733         memset( signature, '!', signature_size );
2734     /* If signature_size is 0 then we have nothing to do. We must not call
2735      * memset because signature may be NULL in this case. */
2736 
2737     unlock_status = psa_unlock_key_slot( slot );
2738 
2739     return( ( status == PSA_SUCCESS ) ? unlock_status : status );
2740 }
2741 
psa_verify_internal(mbedtls_svc_key_id_t key,int input_is_message,psa_algorithm_t alg,const uint8_t * input,size_t input_length,const uint8_t * signature,size_t signature_length)2742 static psa_status_t psa_verify_internal( mbedtls_svc_key_id_t key,
2743                                          int input_is_message,
2744                                          psa_algorithm_t alg,
2745                                          const uint8_t * input,
2746                                          size_t input_length,
2747                                          const uint8_t * signature,
2748                                          size_t signature_length )
2749 {
2750     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2751     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
2752     psa_key_slot_t *slot;
2753 
2754     status = psa_sign_verify_check_alg( input_is_message, alg );
2755     if( status != PSA_SUCCESS )
2756         return status;
2757 
2758     status = psa_get_and_lock_key_slot_with_policy(
2759                 key, &slot,
2760                 input_is_message ? PSA_KEY_USAGE_VERIFY_MESSAGE :
2761                                    PSA_KEY_USAGE_VERIFY_HASH,
2762                 alg );
2763 
2764     if( status != PSA_SUCCESS )
2765         return( status );
2766 
2767     psa_key_attributes_t attributes = {
2768       .core = slot->attr
2769     };
2770 
2771     if( input_is_message )
2772     {
2773         status = psa_driver_wrapper_verify_message(
2774             &attributes, slot->key.data, slot->key.bytes,
2775             alg, input, input_length,
2776             signature, signature_length );
2777     }
2778     else
2779     {
2780         status = psa_driver_wrapper_verify_hash(
2781             &attributes, slot->key.data, slot->key.bytes,
2782             alg, input, input_length,
2783             signature, signature_length );
2784     }
2785 
2786     unlock_status = psa_unlock_key_slot( slot );
2787 
2788     return( ( status == PSA_SUCCESS ) ? unlock_status : status );
2789 
2790 }
2791 
psa_sign_message_builtin(const psa_key_attributes_t * attributes,const uint8_t * key_buffer,size_t key_buffer_size,psa_algorithm_t alg,const uint8_t * input,size_t input_length,uint8_t * signature,size_t signature_size,size_t * signature_length)2792 psa_status_t psa_sign_message_builtin(
2793     const psa_key_attributes_t *attributes,
2794     const uint8_t *key_buffer,
2795     size_t key_buffer_size,
2796     psa_algorithm_t alg,
2797     const uint8_t *input,
2798     size_t input_length,
2799     uint8_t *signature,
2800     size_t signature_size,
2801     size_t *signature_length )
2802 {
2803     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2804 
2805     if ( PSA_ALG_IS_SIGN_HASH( alg ) )
2806     {
2807         size_t hash_length;
2808         uint8_t hash[PSA_HASH_MAX_SIZE];
2809 
2810         status = psa_driver_wrapper_hash_compute(
2811                     PSA_ALG_SIGN_GET_HASH( alg ),
2812                     input, input_length,
2813                     hash, sizeof( hash ), &hash_length );
2814 
2815         if( status != PSA_SUCCESS )
2816             return status;
2817 
2818         return psa_driver_wrapper_sign_hash(
2819                     attributes, key_buffer, key_buffer_size,
2820                     alg, hash, hash_length,
2821                     signature, signature_size, signature_length );
2822     }
2823 
2824     return( PSA_ERROR_NOT_SUPPORTED );
2825 }
2826 
psa_sign_message(mbedtls_svc_key_id_t key,psa_algorithm_t alg,const uint8_t * input,size_t input_length,uint8_t * signature,size_t signature_size,size_t * signature_length)2827 psa_status_t psa_sign_message( mbedtls_svc_key_id_t key,
2828                                psa_algorithm_t alg,
2829                                const uint8_t * input,
2830                                size_t input_length,
2831                                uint8_t * signature,
2832                                size_t signature_size,
2833                                size_t * signature_length )
2834 {
2835     return psa_sign_internal(
2836         key, 1, alg, input, input_length,
2837         signature, signature_size, signature_length );
2838 }
2839 
psa_verify_message_builtin(const psa_key_attributes_t * attributes,const uint8_t * key_buffer,size_t key_buffer_size,psa_algorithm_t alg,const uint8_t * input,size_t input_length,const uint8_t * signature,size_t signature_length)2840 psa_status_t psa_verify_message_builtin(
2841     const psa_key_attributes_t *attributes,
2842     const uint8_t *key_buffer,
2843     size_t key_buffer_size,
2844     psa_algorithm_t alg,
2845     const uint8_t *input,
2846     size_t input_length,
2847     const uint8_t *signature,
2848     size_t signature_length )
2849 {
2850     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2851 
2852     if ( PSA_ALG_IS_SIGN_HASH( alg ) )
2853     {
2854         size_t hash_length;
2855         uint8_t hash[PSA_HASH_MAX_SIZE];
2856 
2857         status = psa_driver_wrapper_hash_compute(
2858                     PSA_ALG_SIGN_GET_HASH( alg ),
2859                     input, input_length,
2860                     hash, sizeof( hash ), &hash_length );
2861 
2862         if( status != PSA_SUCCESS )
2863             return status;
2864 
2865         return psa_driver_wrapper_verify_hash(
2866                     attributes, key_buffer, key_buffer_size,
2867                     alg, hash, hash_length,
2868                     signature, signature_length );
2869     }
2870 
2871     return( PSA_ERROR_NOT_SUPPORTED );
2872 }
2873 
psa_verify_message(mbedtls_svc_key_id_t key,psa_algorithm_t alg,const uint8_t * input,size_t input_length,const uint8_t * signature,size_t signature_length)2874 psa_status_t psa_verify_message( mbedtls_svc_key_id_t key,
2875                                  psa_algorithm_t alg,
2876                                  const uint8_t * input,
2877                                  size_t input_length,
2878                                  const uint8_t * signature,
2879                                  size_t signature_length )
2880 {
2881     return psa_verify_internal(
2882         key, 1, alg, input, input_length,
2883         signature, signature_length );
2884 }
2885 
psa_sign_hash_builtin(const psa_key_attributes_t * attributes,const uint8_t * key_buffer,size_t key_buffer_size,psa_algorithm_t alg,const uint8_t * hash,size_t hash_length,uint8_t * signature,size_t signature_size,size_t * signature_length)2886 psa_status_t psa_sign_hash_builtin(
2887     const psa_key_attributes_t *attributes,
2888     const uint8_t *key_buffer, size_t key_buffer_size,
2889     psa_algorithm_t alg, const uint8_t *hash, size_t hash_length,
2890     uint8_t *signature, size_t signature_size, size_t *signature_length )
2891 {
2892     if( attributes->core.type == PSA_KEY_TYPE_RSA_KEY_PAIR )
2893     {
2894         if( PSA_ALG_IS_RSA_PKCS1V15_SIGN( alg ) ||
2895             PSA_ALG_IS_RSA_PSS( alg) )
2896         {
2897 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) || \
2898     defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS)
2899             return( mbedtls_psa_rsa_sign_hash(
2900                         attributes,
2901                         key_buffer, key_buffer_size,
2902                         alg, hash, hash_length,
2903                         signature, signature_size, signature_length ) );
2904 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) ||
2905         * defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS) */
2906         }
2907         else
2908         {
2909             return( PSA_ERROR_INVALID_ARGUMENT );
2910         }
2911     }
2912     else
2913     if( PSA_KEY_TYPE_IS_ECC( attributes->core.type ) )
2914     {
2915         if( PSA_ALG_IS_ECDSA( alg ) )
2916         {
2917 #if defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
2918     defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)
2919             return( mbedtls_psa_ecdsa_sign_hash(
2920                         attributes,
2921                         key_buffer, key_buffer_size,
2922                         alg, hash, hash_length,
2923                         signature, signature_size, signature_length ) );
2924 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
2925         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) */
2926         }
2927         else
2928         {
2929             return( PSA_ERROR_INVALID_ARGUMENT );
2930         }
2931     }
2932 
2933     (void)key_buffer;
2934     (void)key_buffer_size;
2935     (void)hash;
2936     (void)hash_length;
2937     (void)signature;
2938     (void)signature_size;
2939     (void)signature_length;
2940 
2941     return( PSA_ERROR_NOT_SUPPORTED );
2942 }
2943 
psa_sign_hash(mbedtls_svc_key_id_t key,psa_algorithm_t alg,const uint8_t * hash,size_t hash_length,uint8_t * signature,size_t signature_size,size_t * signature_length)2944 psa_status_t psa_sign_hash( mbedtls_svc_key_id_t key,
2945                             psa_algorithm_t alg,
2946                             const uint8_t *hash,
2947                             size_t hash_length,
2948                             uint8_t *signature,
2949                             size_t signature_size,
2950                             size_t *signature_length )
2951 {
2952     return psa_sign_internal(
2953         key, 0, alg, hash, hash_length,
2954         signature, signature_size, signature_length );
2955 }
2956 
psa_verify_hash_builtin(const psa_key_attributes_t * attributes,const uint8_t * key_buffer,size_t key_buffer_size,psa_algorithm_t alg,const uint8_t * hash,size_t hash_length,const uint8_t * signature,size_t signature_length)2957 psa_status_t psa_verify_hash_builtin(
2958     const psa_key_attributes_t *attributes,
2959     const uint8_t *key_buffer, size_t key_buffer_size,
2960     psa_algorithm_t alg, const uint8_t *hash, size_t hash_length,
2961     const uint8_t *signature, size_t signature_length )
2962 {
2963     if( PSA_KEY_TYPE_IS_RSA( attributes->core.type ) )
2964     {
2965         if( PSA_ALG_IS_RSA_PKCS1V15_SIGN( alg ) ||
2966             PSA_ALG_IS_RSA_PSS( alg) )
2967         {
2968 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) || \
2969     defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS)
2970             return( mbedtls_psa_rsa_verify_hash(
2971                         attributes,
2972                         key_buffer, key_buffer_size,
2973                         alg, hash, hash_length,
2974                         signature, signature_length ) );
2975 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) ||
2976         * defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS) */
2977         }
2978         else
2979         {
2980             return( PSA_ERROR_INVALID_ARGUMENT );
2981         }
2982     }
2983     else
2984     if( PSA_KEY_TYPE_IS_ECC( attributes->core.type ) )
2985     {
2986         if( PSA_ALG_IS_ECDSA( alg ) )
2987         {
2988 #if defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
2989     defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)
2990             return( mbedtls_psa_ecdsa_verify_hash(
2991                         attributes,
2992                         key_buffer, key_buffer_size,
2993                         alg, hash, hash_length,
2994                         signature, signature_length ) );
2995 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
2996         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) */
2997         }
2998         else
2999         {
3000             return( PSA_ERROR_INVALID_ARGUMENT );
3001         }
3002     }
3003 
3004     (void)key_buffer;
3005     (void)key_buffer_size;
3006     (void)hash;
3007     (void)hash_length;
3008     (void)signature;
3009     (void)signature_length;
3010 
3011     return( PSA_ERROR_NOT_SUPPORTED );
3012 }
3013 
psa_verify_hash(mbedtls_svc_key_id_t key,psa_algorithm_t alg,const uint8_t * hash,size_t hash_length,const uint8_t * signature,size_t signature_length)3014 psa_status_t psa_verify_hash( mbedtls_svc_key_id_t key,
3015                               psa_algorithm_t alg,
3016                               const uint8_t *hash,
3017                               size_t hash_length,
3018                               const uint8_t *signature,
3019                               size_t signature_length )
3020 {
3021     return psa_verify_internal(
3022         key, 0, alg, hash, hash_length,
3023         signature, signature_length );
3024 }
3025 
3026 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
psa_rsa_oaep_set_padding_mode(psa_algorithm_t alg,mbedtls_rsa_context * rsa)3027 static int psa_rsa_oaep_set_padding_mode( psa_algorithm_t alg,
3028                                           mbedtls_rsa_context *rsa )
3029 {
3030     psa_algorithm_t hash_alg = PSA_ALG_RSA_OAEP_GET_HASH( alg );
3031     const mbedtls_md_info_t *md_info = mbedtls_md_info_from_psa( hash_alg );
3032     mbedtls_md_type_t md_alg = mbedtls_md_get_type( md_info );
3033 
3034     return( mbedtls_rsa_set_padding( rsa, MBEDTLS_RSA_PKCS_V21, md_alg ) );
3035 }
3036 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP) */
3037 
psa_asymmetric_encrypt(mbedtls_svc_key_id_t key,psa_algorithm_t alg,const uint8_t * input,size_t input_length,const uint8_t * salt,size_t salt_length,uint8_t * output,size_t output_size,size_t * output_length)3038 psa_status_t psa_asymmetric_encrypt( mbedtls_svc_key_id_t key,
3039                                      psa_algorithm_t alg,
3040                                      const uint8_t *input,
3041                                      size_t input_length,
3042                                      const uint8_t *salt,
3043                                      size_t salt_length,
3044                                      uint8_t *output,
3045                                      size_t output_size,
3046                                      size_t *output_length )
3047 {
3048     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3049     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
3050     psa_key_slot_t *slot;
3051 
3052     (void) input;
3053     (void) input_length;
3054     (void) salt;
3055     (void) output;
3056     (void) output_size;
3057 
3058     *output_length = 0;
3059 
3060     if( ! PSA_ALG_IS_RSA_OAEP( alg ) && salt_length != 0 )
3061         return( PSA_ERROR_INVALID_ARGUMENT );
3062 
3063     status = psa_get_and_lock_transparent_key_slot_with_policy(
3064                  key, &slot, PSA_KEY_USAGE_ENCRYPT, alg );
3065     if( status != PSA_SUCCESS )
3066         return( status );
3067     if( ! ( PSA_KEY_TYPE_IS_PUBLIC_KEY( slot->attr.type ) ||
3068             PSA_KEY_TYPE_IS_KEY_PAIR( slot->attr.type ) ) )
3069     {
3070         status = PSA_ERROR_INVALID_ARGUMENT;
3071         goto exit;
3072     }
3073 
3074 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT) || \
3075     defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
3076     if( PSA_KEY_TYPE_IS_RSA( slot->attr.type ) )
3077     {
3078         mbedtls_rsa_context *rsa = NULL;
3079         status = mbedtls_psa_rsa_load_representation( slot->attr.type,
3080                                                       slot->key.data,
3081                                                       slot->key.bytes,
3082                                                       &rsa );
3083         if( status != PSA_SUCCESS )
3084             goto rsa_exit;
3085 
3086         if( output_size < mbedtls_rsa_get_len( rsa ) )
3087         {
3088             status = PSA_ERROR_BUFFER_TOO_SMALL;
3089             goto rsa_exit;
3090         }
3091 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT)
3092         if( alg == PSA_ALG_RSA_PKCS1V15_CRYPT )
3093         {
3094             status = mbedtls_to_psa_error(
3095                     mbedtls_rsa_pkcs1_encrypt( rsa,
3096                                                mbedtls_psa_get_random,
3097                                                MBEDTLS_PSA_RANDOM_STATE,
3098                                                input_length,
3099                                                input,
3100                                                output ) );
3101         }
3102         else
3103 #endif /* MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT */
3104 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
3105         if( PSA_ALG_IS_RSA_OAEP( alg ) )
3106         {
3107             status = mbedtls_to_psa_error(
3108                          psa_rsa_oaep_set_padding_mode( alg, rsa ) );
3109             if( status != PSA_SUCCESS )
3110                 goto rsa_exit;
3111 
3112             status = mbedtls_to_psa_error(
3113                 mbedtls_rsa_rsaes_oaep_encrypt( rsa,
3114                                                 mbedtls_psa_get_random,
3115                                                 MBEDTLS_PSA_RANDOM_STATE,
3116                                                 salt, salt_length,
3117                                                 input_length,
3118                                                 input,
3119                                                 output ) );
3120         }
3121         else
3122 #endif /* MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP */
3123         {
3124             status = PSA_ERROR_INVALID_ARGUMENT;
3125             goto rsa_exit;
3126         }
3127 rsa_exit:
3128         if( status == PSA_SUCCESS )
3129             *output_length = mbedtls_rsa_get_len( rsa );
3130 
3131         mbedtls_rsa_free( rsa );
3132         mbedtls_free( rsa );
3133     }
3134     else
3135 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT) ||
3136         * defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP) */
3137     {
3138         status = PSA_ERROR_NOT_SUPPORTED;
3139     }
3140 
3141 exit:
3142     unlock_status = psa_unlock_key_slot( slot );
3143 
3144     return( ( status == PSA_SUCCESS ) ? unlock_status : status );
3145 }
3146 
psa_asymmetric_decrypt(mbedtls_svc_key_id_t key,psa_algorithm_t alg,const uint8_t * input,size_t input_length,const uint8_t * salt,size_t salt_length,uint8_t * output,size_t output_size,size_t * output_length)3147 psa_status_t psa_asymmetric_decrypt( mbedtls_svc_key_id_t key,
3148                                      psa_algorithm_t alg,
3149                                      const uint8_t *input,
3150                                      size_t input_length,
3151                                      const uint8_t *salt,
3152                                      size_t salt_length,
3153                                      uint8_t *output,
3154                                      size_t output_size,
3155                                      size_t *output_length )
3156 {
3157     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3158     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
3159     psa_key_slot_t *slot;
3160 
3161     (void) input;
3162     (void) input_length;
3163     (void) salt;
3164     (void) output;
3165     (void) output_size;
3166 
3167     *output_length = 0;
3168 
3169     if( ! PSA_ALG_IS_RSA_OAEP( alg ) && salt_length != 0 )
3170         return( PSA_ERROR_INVALID_ARGUMENT );
3171 
3172     status = psa_get_and_lock_transparent_key_slot_with_policy(
3173                  key, &slot, PSA_KEY_USAGE_DECRYPT, alg );
3174     if( status != PSA_SUCCESS )
3175         return( status );
3176     if( ! PSA_KEY_TYPE_IS_KEY_PAIR( slot->attr.type ) )
3177     {
3178         status = PSA_ERROR_INVALID_ARGUMENT;
3179         goto exit;
3180     }
3181 
3182 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT) || \
3183     defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
3184     if( slot->attr.type == PSA_KEY_TYPE_RSA_KEY_PAIR )
3185     {
3186         mbedtls_rsa_context *rsa = NULL;
3187         status = mbedtls_psa_rsa_load_representation( slot->attr.type,
3188                                                       slot->key.data,
3189                                                       slot->key.bytes,
3190                                                       &rsa );
3191         if( status != PSA_SUCCESS )
3192             goto exit;
3193 
3194         if( input_length != mbedtls_rsa_get_len( rsa ) )
3195         {
3196             status = PSA_ERROR_INVALID_ARGUMENT;
3197             goto rsa_exit;
3198         }
3199 
3200 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT)
3201         if( alg == PSA_ALG_RSA_PKCS1V15_CRYPT )
3202         {
3203             status = mbedtls_to_psa_error(
3204                 mbedtls_rsa_pkcs1_decrypt( rsa,
3205                                            mbedtls_psa_get_random,
3206                                            MBEDTLS_PSA_RANDOM_STATE,
3207                                            output_length,
3208                                            input,
3209                                            output,
3210                                            output_size ) );
3211         }
3212         else
3213 #endif /* MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT */
3214 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
3215         if( PSA_ALG_IS_RSA_OAEP( alg ) )
3216         {
3217             status = mbedtls_to_psa_error(
3218                          psa_rsa_oaep_set_padding_mode( alg, rsa ) );
3219             if( status != PSA_SUCCESS )
3220                 goto rsa_exit;
3221 
3222             status = mbedtls_to_psa_error(
3223                 mbedtls_rsa_rsaes_oaep_decrypt( rsa,
3224                                                 mbedtls_psa_get_random,
3225                                                 MBEDTLS_PSA_RANDOM_STATE,
3226                                                 salt, salt_length,
3227                                                 output_length,
3228                                                 input,
3229                                                 output,
3230                                                 output_size ) );
3231         }
3232         else
3233 #endif /* MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP */
3234         {
3235             status = PSA_ERROR_INVALID_ARGUMENT;
3236         }
3237 
3238 rsa_exit:
3239         mbedtls_rsa_free( rsa );
3240         mbedtls_free( rsa );
3241     }
3242     else
3243 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT) ||
3244         * defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP) */
3245     {
3246         status = PSA_ERROR_NOT_SUPPORTED;
3247     }
3248 
3249 exit:
3250     unlock_status = psa_unlock_key_slot( slot );
3251 
3252     return( ( status == PSA_SUCCESS ) ? unlock_status : status );
3253 }
3254 
3255 
3256 
3257 /****************************************************************/
3258 /* Symmetric cryptography */
3259 /****************************************************************/
3260 
psa_cipher_setup(psa_cipher_operation_t * operation,mbedtls_svc_key_id_t key,psa_algorithm_t alg,mbedtls_operation_t cipher_operation)3261 static psa_status_t psa_cipher_setup( psa_cipher_operation_t *operation,
3262                                       mbedtls_svc_key_id_t key,
3263                                       psa_algorithm_t alg,
3264                                       mbedtls_operation_t cipher_operation )
3265 {
3266     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3267     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
3268     psa_key_slot_t *slot = NULL;
3269     psa_key_usage_t usage = ( cipher_operation == MBEDTLS_ENCRYPT ?
3270                               PSA_KEY_USAGE_ENCRYPT :
3271                               PSA_KEY_USAGE_DECRYPT );
3272 
3273     /* A context must be freshly initialized before it can be set up. */
3274     if( operation->id != 0 )
3275     {
3276         status = PSA_ERROR_BAD_STATE;
3277         goto exit;
3278     }
3279 
3280     if( ! PSA_ALG_IS_CIPHER( alg ) )
3281     {
3282         status = PSA_ERROR_INVALID_ARGUMENT;
3283         goto exit;
3284     }
3285 
3286     status = psa_get_and_lock_key_slot_with_policy( key, &slot, usage, alg );
3287     if( status != PSA_SUCCESS )
3288         goto exit;
3289 
3290     /* Initialize the operation struct members, except for id. The id member
3291      * is used to indicate to psa_cipher_abort that there are resources to free,
3292      * so we only set it (in the driver wrapper) after resources have been
3293      * allocated/initialized. */
3294     operation->iv_set = 0;
3295     if( alg == PSA_ALG_ECB_NO_PADDING )
3296         operation->iv_required = 0;
3297     else
3298         operation->iv_required = 1;
3299     operation->default_iv_length = PSA_CIPHER_IV_LENGTH( slot->attr.type, alg );
3300 
3301     psa_key_attributes_t attributes = {
3302       .core = slot->attr
3303     };
3304 
3305     /* Try doing the operation through a driver before using software fallback. */
3306     if( cipher_operation == MBEDTLS_ENCRYPT )
3307         status = psa_driver_wrapper_cipher_encrypt_setup( operation,
3308                                                           &attributes,
3309                                                           slot->key.data,
3310                                                           slot->key.bytes,
3311                                                           alg );
3312     else
3313         status = psa_driver_wrapper_cipher_decrypt_setup( operation,
3314                                                           &attributes,
3315                                                           slot->key.data,
3316                                                           slot->key.bytes,
3317                                                           alg );
3318 
3319 exit:
3320     if( status != PSA_SUCCESS )
3321         psa_cipher_abort( operation );
3322 
3323     unlock_status = psa_unlock_key_slot( slot );
3324 
3325     return( ( status == PSA_SUCCESS ) ? unlock_status : status );
3326 }
3327 
psa_cipher_encrypt_setup(psa_cipher_operation_t * operation,mbedtls_svc_key_id_t key,psa_algorithm_t alg)3328 psa_status_t psa_cipher_encrypt_setup( psa_cipher_operation_t *operation,
3329                                        mbedtls_svc_key_id_t key,
3330                                        psa_algorithm_t alg )
3331 {
3332     return( psa_cipher_setup( operation, key, alg, MBEDTLS_ENCRYPT ) );
3333 }
3334 
psa_cipher_decrypt_setup(psa_cipher_operation_t * operation,mbedtls_svc_key_id_t key,psa_algorithm_t alg)3335 psa_status_t psa_cipher_decrypt_setup( psa_cipher_operation_t *operation,
3336                                        mbedtls_svc_key_id_t key,
3337                                        psa_algorithm_t alg )
3338 {
3339     return( psa_cipher_setup( operation, key, alg, MBEDTLS_DECRYPT ) );
3340 }
3341 
psa_cipher_generate_iv(psa_cipher_operation_t * operation,uint8_t * iv,size_t iv_size,size_t * iv_length)3342 psa_status_t psa_cipher_generate_iv( psa_cipher_operation_t *operation,
3343                                      uint8_t *iv,
3344                                      size_t iv_size,
3345                                      size_t *iv_length )
3346 {
3347     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3348 
3349     *iv_length = 0;
3350 
3351     if( operation->id == 0 )
3352     {
3353         status = PSA_ERROR_BAD_STATE;
3354         goto exit;
3355     }
3356 
3357     if( operation->iv_set || ! operation->iv_required )
3358     {
3359         status = PSA_ERROR_BAD_STATE;
3360         goto exit;
3361     }
3362 
3363     if( iv_size < operation->default_iv_length )
3364     {
3365         status = PSA_ERROR_BUFFER_TOO_SMALL;
3366         goto exit;
3367     }
3368 
3369     status = psa_generate_random( iv, operation->default_iv_length );
3370     if( status != PSA_SUCCESS )
3371         goto exit;
3372 
3373     status = psa_driver_wrapper_cipher_set_iv( operation,
3374                                                iv,
3375                                                operation->default_iv_length );
3376 
3377 exit:
3378     if( status == PSA_SUCCESS )
3379     {
3380         operation->iv_set = 1;
3381         *iv_length = operation->default_iv_length;
3382     }
3383     else
3384         psa_cipher_abort( operation );
3385 
3386     return( status );
3387 }
3388 
psa_cipher_set_iv(psa_cipher_operation_t * operation,const uint8_t * iv,size_t iv_length)3389 psa_status_t psa_cipher_set_iv( psa_cipher_operation_t *operation,
3390                                 const uint8_t *iv,
3391                                 size_t iv_length )
3392 {
3393     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3394 
3395     if( operation->id == 0 )
3396     {
3397         status = PSA_ERROR_BAD_STATE;
3398         goto exit;
3399     }
3400 
3401     if( operation->iv_set || ! operation->iv_required )
3402     {
3403         status = PSA_ERROR_BAD_STATE;
3404         goto exit;
3405     }
3406 
3407     if( iv_length > PSA_CIPHER_IV_MAX_SIZE )
3408     {
3409         status = PSA_ERROR_INVALID_ARGUMENT;
3410         goto exit;
3411     }
3412 
3413     status = psa_driver_wrapper_cipher_set_iv( operation,
3414                                                iv,
3415                                                iv_length );
3416 
3417 exit:
3418     if( status == PSA_SUCCESS )
3419         operation->iv_set = 1;
3420     else
3421         psa_cipher_abort( operation );
3422     return( status );
3423 }
3424 
psa_cipher_update(psa_cipher_operation_t * operation,const uint8_t * input,size_t input_length,uint8_t * output,size_t output_size,size_t * output_length)3425 psa_status_t psa_cipher_update( psa_cipher_operation_t *operation,
3426                                 const uint8_t *input,
3427                                 size_t input_length,
3428                                 uint8_t *output,
3429                                 size_t output_size,
3430                                 size_t *output_length )
3431 {
3432     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3433 
3434     if( operation->id == 0 )
3435     {
3436         status = PSA_ERROR_BAD_STATE;
3437         goto exit;
3438     }
3439 
3440     if( operation->iv_required && ! operation->iv_set )
3441     {
3442         status = PSA_ERROR_BAD_STATE;
3443         goto exit;
3444     }
3445 
3446     status = psa_driver_wrapper_cipher_update( operation,
3447                                                input,
3448                                                input_length,
3449                                                output,
3450                                                output_size,
3451                                                output_length );
3452 
3453 exit:
3454     if( status != PSA_SUCCESS )
3455         psa_cipher_abort( operation );
3456 
3457     return( status );
3458 }
3459 
psa_cipher_finish(psa_cipher_operation_t * operation,uint8_t * output,size_t output_size,size_t * output_length)3460 psa_status_t psa_cipher_finish( psa_cipher_operation_t *operation,
3461                                 uint8_t *output,
3462                                 size_t output_size,
3463                                 size_t *output_length )
3464 {
3465     psa_status_t status = PSA_ERROR_GENERIC_ERROR;
3466 
3467     if( operation->id == 0 )
3468     {
3469         status = PSA_ERROR_BAD_STATE;
3470         goto exit;
3471     }
3472 
3473     if( operation->iv_required && ! operation->iv_set )
3474     {
3475         status = PSA_ERROR_BAD_STATE;
3476         goto exit;
3477     }
3478 
3479     status = psa_driver_wrapper_cipher_finish( operation,
3480                                                output,
3481                                                output_size,
3482                                                output_length );
3483 
3484 exit:
3485     if( status == PSA_SUCCESS )
3486         return( psa_cipher_abort( operation ) );
3487     else
3488     {
3489         *output_length = 0;
3490         (void) psa_cipher_abort( operation );
3491 
3492         return( status );
3493     }
3494 }
3495 
psa_cipher_abort(psa_cipher_operation_t * operation)3496 psa_status_t psa_cipher_abort( psa_cipher_operation_t *operation )
3497 {
3498     if( operation->id == 0 )
3499     {
3500         /* The object has (apparently) been initialized but it is not (yet)
3501          * in use. It's ok to call abort on such an object, and there's
3502          * nothing to do. */
3503         return( PSA_SUCCESS );
3504     }
3505 
3506     psa_driver_wrapper_cipher_abort( operation );
3507 
3508     operation->id = 0;
3509     operation->iv_set = 0;
3510     operation->iv_required = 0;
3511 
3512     return( PSA_SUCCESS );
3513 }
3514 
psa_cipher_encrypt(mbedtls_svc_key_id_t key,psa_algorithm_t alg,const uint8_t * input,size_t input_length,uint8_t * output,size_t output_size,size_t * output_length)3515 psa_status_t psa_cipher_encrypt( mbedtls_svc_key_id_t key,
3516                                  psa_algorithm_t alg,
3517                                  const uint8_t *input,
3518                                  size_t input_length,
3519                                  uint8_t *output,
3520                                  size_t output_size,
3521                                  size_t *output_length )
3522 {
3523     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3524     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
3525     psa_key_slot_t *slot;
3526     psa_key_type_t key_type;
3527     size_t iv_length;
3528 
3529     *output_length = 0;
3530 
3531     if( ! PSA_ALG_IS_CIPHER( alg ) )
3532         return( PSA_ERROR_INVALID_ARGUMENT );
3533 
3534     status = psa_get_and_lock_key_slot_with_policy( key, &slot,
3535                                                     PSA_KEY_USAGE_ENCRYPT,
3536                                                     alg );
3537     if( status != PSA_SUCCESS )
3538         return( status );
3539 
3540     psa_key_attributes_t attributes = {
3541       .core = slot->attr
3542     };
3543 
3544     key_type = slot->attr.type;
3545     iv_length = PSA_CIPHER_IV_LENGTH( key_type, alg );
3546 
3547     if( iv_length > 0 )
3548     {
3549         if( output_size < iv_length )
3550         {
3551             status = PSA_ERROR_BUFFER_TOO_SMALL;
3552             goto exit;
3553         }
3554 
3555         status = psa_generate_random( output, iv_length );
3556         if( status != PSA_SUCCESS )
3557             goto exit;
3558     }
3559 
3560     status = psa_driver_wrapper_cipher_encrypt(
3561         &attributes, slot->key.data, slot->key.bytes,
3562         alg, input, input_length,
3563         output, output_size, output_length );
3564 
3565 exit:
3566     unlock_status = psa_unlock_key_slot( slot );
3567 
3568     return( ( status == PSA_SUCCESS ) ? unlock_status : status );
3569 }
3570 
psa_cipher_decrypt(mbedtls_svc_key_id_t key,psa_algorithm_t alg,const uint8_t * input,size_t input_length,uint8_t * output,size_t output_size,size_t * output_length)3571 psa_status_t psa_cipher_decrypt( mbedtls_svc_key_id_t key,
3572                                  psa_algorithm_t alg,
3573                                  const uint8_t *input,
3574                                  size_t input_length,
3575                                  uint8_t *output,
3576                                  size_t output_size,
3577                                  size_t *output_length )
3578 {
3579     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3580     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
3581     psa_key_slot_t *slot;
3582 
3583     *output_length = 0;
3584 
3585     if( ! PSA_ALG_IS_CIPHER( alg ) )
3586         return( PSA_ERROR_INVALID_ARGUMENT );
3587 
3588     status = psa_get_and_lock_key_slot_with_policy( key, &slot,
3589                                                     PSA_KEY_USAGE_DECRYPT,
3590                                                     alg );
3591     if( status != PSA_SUCCESS )
3592         return( status );
3593 
3594     psa_key_attributes_t attributes = {
3595       .core = slot->attr
3596     };
3597 
3598     if( alg == PSA_ALG_CCM_STAR_NO_TAG && input_length < PSA_BLOCK_CIPHER_BLOCK_LENGTH( slot->attr.type ) )
3599     {
3600         status = PSA_ERROR_INVALID_ARGUMENT;
3601         goto exit;
3602     }
3603     else if ( input_length < PSA_CIPHER_IV_LENGTH( slot->attr.type, alg ) )
3604     {
3605         status = PSA_ERROR_INVALID_ARGUMENT;
3606         goto exit;
3607     }
3608 
3609     status = psa_driver_wrapper_cipher_decrypt(
3610         &attributes, slot->key.data, slot->key.bytes,
3611         alg, input, input_length,
3612         output, output_size, output_length );
3613 
3614 exit:
3615     unlock_status = psa_unlock_key_slot( slot );
3616 
3617     return( ( status == PSA_SUCCESS ) ? unlock_status : status );
3618 }
3619 
3620 
3621 /****************************************************************/
3622 /* AEAD */
3623 /****************************************************************/
3624 
3625 /* Helper function to get the base algorithm from its variants. */
psa_aead_get_base_algorithm(psa_algorithm_t alg)3626 static psa_algorithm_t psa_aead_get_base_algorithm( psa_algorithm_t alg )
3627 {
3628     return PSA_ALG_AEAD_WITH_DEFAULT_LENGTH_TAG( alg );
3629 }
3630 
3631 /* Helper function to perform common nonce length checks. */
psa_aead_check_nonce_length(psa_algorithm_t alg,size_t nonce_length)3632 static psa_status_t psa_aead_check_nonce_length( psa_algorithm_t alg,
3633                                                  size_t nonce_length )
3634 {
3635     psa_algorithm_t base_alg = psa_aead_get_base_algorithm( alg );
3636 
3637     switch(base_alg)
3638     {
3639 #if defined(PSA_WANT_ALG_GCM)
3640         case PSA_ALG_GCM:
3641             /* Not checking max nonce size here as GCM spec allows almost
3642             * arbitrarily large nonces. Please note that we do not generally
3643             * recommend the usage of nonces of greater length than
3644             * PSA_AEAD_NONCE_MAX_SIZE, as large nonces are hashed to a shorter
3645             * size, which can then lead to collisions if you encrypt a very
3646             * large number of messages.*/
3647             if( nonce_length != 0 )
3648                 return( PSA_SUCCESS );
3649             break;
3650 #endif /* PSA_WANT_ALG_GCM */
3651 #if defined(PSA_WANT_ALG_CCM)
3652         case PSA_ALG_CCM:
3653             if( nonce_length >= 7 && nonce_length <= 13 )
3654                 return( PSA_SUCCESS );
3655             break;
3656 #endif /* PSA_WANT_ALG_CCM */
3657 #if defined(PSA_WANT_ALG_CHACHA20_POLY1305)
3658         case PSA_ALG_CHACHA20_POLY1305:
3659             if( nonce_length == 12 )
3660                 return( PSA_SUCCESS );
3661             break;
3662 #endif /* PSA_WANT_ALG_CHACHA20_POLY1305 */
3663         default:
3664             break;
3665     }
3666 
3667     return( PSA_ERROR_NOT_SUPPORTED );
3668 }
3669 
psa_aead_encrypt(mbedtls_svc_key_id_t key,psa_algorithm_t alg,const uint8_t * nonce,size_t nonce_length,const uint8_t * additional_data,size_t additional_data_length,const uint8_t * plaintext,size_t plaintext_length,uint8_t * ciphertext,size_t ciphertext_size,size_t * ciphertext_length)3670 psa_status_t psa_aead_encrypt( mbedtls_svc_key_id_t key,
3671                                psa_algorithm_t alg,
3672                                const uint8_t *nonce,
3673                                size_t nonce_length,
3674                                const uint8_t *additional_data,
3675                                size_t additional_data_length,
3676                                const uint8_t *plaintext,
3677                                size_t plaintext_length,
3678                                uint8_t *ciphertext,
3679                                size_t ciphertext_size,
3680                                size_t *ciphertext_length )
3681 {
3682     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3683     psa_key_slot_t *slot;
3684 
3685     *ciphertext_length = 0;
3686 
3687     if( !PSA_ALG_IS_AEAD( alg ) || PSA_ALG_IS_WILDCARD( alg ) )
3688         return( PSA_ERROR_NOT_SUPPORTED );
3689 
3690     status = psa_get_and_lock_key_slot_with_policy(
3691                  key, &slot, PSA_KEY_USAGE_ENCRYPT, alg );
3692     if( status != PSA_SUCCESS )
3693         return( status );
3694 
3695     psa_key_attributes_t attributes = {
3696       .core = slot->attr
3697     };
3698 
3699     status = psa_aead_check_nonce_length( alg, nonce_length );
3700     if( status != PSA_SUCCESS )
3701         goto exit;
3702 
3703     status = psa_driver_wrapper_aead_encrypt(
3704         &attributes, slot->key.data, slot->key.bytes,
3705         alg,
3706         nonce, nonce_length,
3707         additional_data, additional_data_length,
3708         plaintext, plaintext_length,
3709         ciphertext, ciphertext_size, ciphertext_length );
3710 
3711     if( status != PSA_SUCCESS && ciphertext_size != 0 )
3712         memset( ciphertext, 0, ciphertext_size );
3713 
3714 exit:
3715     psa_unlock_key_slot( slot );
3716 
3717     return( status );
3718 }
3719 
psa_aead_decrypt(mbedtls_svc_key_id_t key,psa_algorithm_t alg,const uint8_t * nonce,size_t nonce_length,const uint8_t * additional_data,size_t additional_data_length,const uint8_t * ciphertext,size_t ciphertext_length,uint8_t * plaintext,size_t plaintext_size,size_t * plaintext_length)3720 psa_status_t psa_aead_decrypt( mbedtls_svc_key_id_t key,
3721                                psa_algorithm_t alg,
3722                                const uint8_t *nonce,
3723                                size_t nonce_length,
3724                                const uint8_t *additional_data,
3725                                size_t additional_data_length,
3726                                const uint8_t *ciphertext,
3727                                size_t ciphertext_length,
3728                                uint8_t *plaintext,
3729                                size_t plaintext_size,
3730                                size_t *plaintext_length )
3731 {
3732     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3733     psa_key_slot_t *slot;
3734 
3735     *plaintext_length = 0;
3736 
3737     if( !PSA_ALG_IS_AEAD( alg ) || PSA_ALG_IS_WILDCARD( alg ) )
3738         return( PSA_ERROR_NOT_SUPPORTED );
3739 
3740     status = psa_get_and_lock_key_slot_with_policy(
3741                  key, &slot, PSA_KEY_USAGE_DECRYPT, alg );
3742     if( status != PSA_SUCCESS )
3743         return( status );
3744 
3745     psa_key_attributes_t attributes = {
3746       .core = slot->attr
3747     };
3748 
3749     status = psa_aead_check_nonce_length( alg, nonce_length );
3750     if( status != PSA_SUCCESS )
3751         goto exit;
3752 
3753     status = psa_driver_wrapper_aead_decrypt(
3754         &attributes, slot->key.data, slot->key.bytes,
3755         alg,
3756         nonce, nonce_length,
3757         additional_data, additional_data_length,
3758         ciphertext, ciphertext_length,
3759         plaintext, plaintext_size, plaintext_length );
3760 
3761     if( status != PSA_SUCCESS && plaintext_size != 0 )
3762         memset( plaintext, 0, plaintext_size );
3763 
3764 exit:
3765     psa_unlock_key_slot( slot );
3766 
3767     return( status );
3768 }
3769 
3770 /* Set the key for a multipart authenticated operation. */
psa_aead_setup(psa_aead_operation_t * operation,int is_encrypt,mbedtls_svc_key_id_t key,psa_algorithm_t alg)3771 static psa_status_t psa_aead_setup( psa_aead_operation_t *operation,
3772                                     int is_encrypt,
3773                                     mbedtls_svc_key_id_t key,
3774                                     psa_algorithm_t alg )
3775 {
3776     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3777     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
3778     psa_key_slot_t *slot = NULL;
3779     psa_key_usage_t key_usage = 0;
3780 
3781     if( !PSA_ALG_IS_AEAD( alg ) || PSA_ALG_IS_WILDCARD( alg ) )
3782     {
3783         status = PSA_ERROR_INVALID_ARGUMENT;
3784         goto exit;
3785     }
3786 
3787     if( operation->id != 0 )
3788     {
3789         status = PSA_ERROR_BAD_STATE;
3790         goto exit;
3791     }
3792 
3793     if( operation->nonce_set || operation->lengths_set ||
3794         operation->ad_started || operation->body_started )
3795     {
3796         status = PSA_ERROR_BAD_STATE;
3797         goto exit;
3798     }
3799 
3800     if( is_encrypt )
3801         key_usage = PSA_KEY_USAGE_ENCRYPT;
3802     else
3803         key_usage = PSA_KEY_USAGE_DECRYPT;
3804 
3805     status = psa_get_and_lock_key_slot_with_policy( key, &slot, key_usage,
3806                                                     alg );
3807     if( status != PSA_SUCCESS )
3808         goto exit;
3809 
3810     psa_key_attributes_t attributes = {
3811         .core = slot->attr
3812     };
3813 
3814     if( is_encrypt )
3815         status = psa_driver_wrapper_aead_encrypt_setup( operation,
3816                                                         &attributes,
3817                                                         slot->key.data,
3818                                                         slot->key.bytes,
3819                                                         alg );
3820     else
3821         status = psa_driver_wrapper_aead_decrypt_setup( operation,
3822                                                         &attributes,
3823                                                         slot->key.data,
3824                                                         slot->key.bytes,
3825                                                         alg );
3826     if( status != PSA_SUCCESS )
3827         goto exit;
3828 
3829     operation->key_type = psa_get_key_type( &attributes );
3830 
3831 exit:
3832     unlock_status = psa_unlock_key_slot( slot );
3833 
3834     if( status == PSA_SUCCESS )
3835     {
3836         status = unlock_status;
3837         operation->alg = psa_aead_get_base_algorithm( alg );
3838         operation->is_encrypt = is_encrypt;
3839     }
3840     else
3841         psa_aead_abort( operation );
3842 
3843     return( status );
3844 }
3845 
3846 /* Set the key for a multipart authenticated encryption operation. */
psa_aead_encrypt_setup(psa_aead_operation_t * operation,mbedtls_svc_key_id_t key,psa_algorithm_t alg)3847 psa_status_t psa_aead_encrypt_setup( psa_aead_operation_t *operation,
3848                                      mbedtls_svc_key_id_t key,
3849                                      psa_algorithm_t alg )
3850 {
3851     return( psa_aead_setup( operation, 1, key, alg ) );
3852 }
3853 
3854 /* Set the key for a multipart authenticated decryption operation. */
psa_aead_decrypt_setup(psa_aead_operation_t * operation,mbedtls_svc_key_id_t key,psa_algorithm_t alg)3855 psa_status_t psa_aead_decrypt_setup( psa_aead_operation_t *operation,
3856                                      mbedtls_svc_key_id_t key,
3857                                      psa_algorithm_t alg )
3858 {
3859     return( psa_aead_setup( operation, 0, key, alg ) );
3860 }
3861 
3862 /* Generate a random nonce / IV for multipart AEAD operation */
psa_aead_generate_nonce(psa_aead_operation_t * operation,uint8_t * nonce,size_t nonce_size,size_t * nonce_length)3863 psa_status_t psa_aead_generate_nonce( psa_aead_operation_t *operation,
3864                                       uint8_t *nonce,
3865                                       size_t nonce_size,
3866                                       size_t *nonce_length )
3867 {
3868     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3869     size_t required_nonce_size;
3870 
3871     *nonce_length = 0;
3872 
3873     if( operation->id == 0 )
3874     {
3875         status = PSA_ERROR_BAD_STATE;
3876         goto exit;
3877     }
3878 
3879     if( operation->nonce_set || !operation->is_encrypt )
3880     {
3881         status = PSA_ERROR_BAD_STATE;
3882         goto exit;
3883     }
3884 
3885     required_nonce_size = PSA_AEAD_NONCE_LENGTH( operation->key_type,
3886                                                  operation->alg );
3887     if( nonce_size < required_nonce_size )
3888     {
3889         status = PSA_ERROR_BUFFER_TOO_SMALL;
3890         goto exit;
3891     }
3892 
3893     status = psa_generate_random( nonce, required_nonce_size );
3894     if( status != PSA_SUCCESS )
3895         goto exit;
3896 
3897     status = psa_aead_set_nonce( operation, nonce, required_nonce_size );
3898 
3899 exit:
3900     if( status == PSA_SUCCESS )
3901         *nonce_length = required_nonce_size;
3902     else
3903         psa_aead_abort( operation );
3904 
3905     return( status );
3906 }
3907 
3908 /* Set the nonce for a multipart authenticated encryption or decryption
3909    operation.*/
psa_aead_set_nonce(psa_aead_operation_t * operation,const uint8_t * nonce,size_t nonce_length)3910 psa_status_t psa_aead_set_nonce( psa_aead_operation_t *operation,
3911                                  const uint8_t *nonce,
3912                                  size_t nonce_length )
3913 {
3914     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3915 
3916     if( operation->id == 0 )
3917     {
3918         status = PSA_ERROR_BAD_STATE;
3919         goto exit;
3920     }
3921 
3922     if( operation->nonce_set )
3923     {
3924         status = PSA_ERROR_BAD_STATE;
3925         goto exit;
3926     }
3927 
3928     status = psa_aead_check_nonce_length( operation->alg, nonce_length );
3929     if( status != PSA_SUCCESS )
3930     {
3931         status = PSA_ERROR_INVALID_ARGUMENT;
3932         goto exit;
3933     }
3934 
3935     status = psa_driver_wrapper_aead_set_nonce( operation, nonce,
3936                                                 nonce_length );
3937 
3938 exit:
3939     if( status == PSA_SUCCESS )
3940         operation->nonce_set = 1;
3941     else
3942         psa_aead_abort( operation );
3943 
3944     return( status );
3945 }
3946 
3947 /* Declare the lengths of the message and additional data for multipart AEAD. */
psa_aead_set_lengths(psa_aead_operation_t * operation,size_t ad_length,size_t plaintext_length)3948 psa_status_t psa_aead_set_lengths( psa_aead_operation_t *operation,
3949                                    size_t ad_length,
3950                                    size_t plaintext_length )
3951 {
3952     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3953 
3954     if( operation->id == 0 )
3955     {
3956         status = PSA_ERROR_BAD_STATE;
3957         goto exit;
3958     }
3959 
3960     if( operation->lengths_set || operation->ad_started ||
3961         operation->body_started )
3962     {
3963         status = PSA_ERROR_BAD_STATE;
3964         goto exit;
3965     }
3966 
3967     switch(operation->alg)
3968     {
3969 #if defined(PSA_WANT_ALG_GCM)
3970         case PSA_ALG_GCM:
3971             /* Lengths can only be too large for GCM if size_t is bigger than 32
3972             * bits. Without the guard this code will generate warnings on 32bit
3973             * builds. */
3974 #if SIZE_MAX > UINT32_MAX
3975             if( (( uint64_t ) ad_length ) >> 61 != 0 ||
3976                 (( uint64_t ) plaintext_length ) > 0xFFFFFFFE0ull )
3977             {
3978                 status = PSA_ERROR_INVALID_ARGUMENT;
3979                 goto exit;
3980             }
3981 #endif
3982             break;
3983 #endif /* PSA_WANT_ALG_GCM */
3984 #if defined(PSA_WANT_ALG_CCM)
3985         case PSA_ALG_CCM:
3986             if( ad_length > 0xFF00 )
3987             {
3988                 status = PSA_ERROR_INVALID_ARGUMENT;
3989                 goto exit;
3990             }
3991             break;
3992 #endif /* PSA_WANT_ALG_CCM */
3993 #if defined(PSA_WANT_ALG_CHACHA20_POLY1305)
3994         case PSA_ALG_CHACHA20_POLY1305:
3995             /* No length restrictions for ChaChaPoly. */
3996             break;
3997 #endif /* PSA_WANT_ALG_CHACHA20_POLY1305 */
3998         default:
3999             break;
4000     }
4001 
4002     status = psa_driver_wrapper_aead_set_lengths( operation, ad_length,
4003                                                   plaintext_length );
4004 
4005 exit:
4006     if( status == PSA_SUCCESS )
4007     {
4008         operation->ad_remaining = ad_length;
4009         operation->body_remaining = plaintext_length;
4010         operation->lengths_set = 1;
4011     }
4012     else
4013         psa_aead_abort( operation );
4014 
4015     return( status );
4016 }
4017 
4018 /* Pass additional data to an active multipart AEAD operation. */
psa_aead_update_ad(psa_aead_operation_t * operation,const uint8_t * input,size_t input_length)4019 psa_status_t psa_aead_update_ad( psa_aead_operation_t *operation,
4020                                  const uint8_t *input,
4021                                  size_t input_length )
4022 {
4023     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4024 
4025     if( operation->id == 0 )
4026     {
4027         status = PSA_ERROR_BAD_STATE;
4028         goto exit;
4029     }
4030 
4031     if( !operation->nonce_set || operation->body_started )
4032     {
4033         status = PSA_ERROR_BAD_STATE;
4034         goto exit;
4035     }
4036 
4037     if( operation->lengths_set )
4038     {
4039         if( operation->ad_remaining < input_length )
4040         {
4041             status = PSA_ERROR_INVALID_ARGUMENT;
4042             goto exit;
4043         }
4044 
4045         operation->ad_remaining -= input_length;
4046     }
4047 
4048     status = psa_driver_wrapper_aead_update_ad( operation, input,
4049                                                 input_length );
4050 
4051 exit:
4052     if( status == PSA_SUCCESS )
4053         operation->ad_started = 1;
4054     else
4055         psa_aead_abort( operation );
4056 
4057     return( status );
4058 }
4059 
4060 /* Encrypt or decrypt a message fragment in an active multipart AEAD
4061    operation.*/
psa_aead_update(psa_aead_operation_t * operation,const uint8_t * input,size_t input_length,uint8_t * output,size_t output_size,size_t * output_length)4062 psa_status_t psa_aead_update( psa_aead_operation_t *operation,
4063                               const uint8_t *input,
4064                               size_t input_length,
4065                               uint8_t *output,
4066                               size_t output_size,
4067                               size_t *output_length )
4068 {
4069     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4070 
4071     *output_length = 0;
4072 
4073     if( operation->id == 0 )
4074     {
4075         status = PSA_ERROR_BAD_STATE;
4076         goto exit;
4077     }
4078 
4079     if( !operation->nonce_set )
4080     {
4081         status = PSA_ERROR_BAD_STATE;
4082         goto exit;
4083     }
4084 
4085     if( operation->lengths_set )
4086     {
4087         /* Additional data length was supplied, but not all the additional
4088            data was supplied.*/
4089         if( operation->ad_remaining != 0 )
4090         {
4091             status = PSA_ERROR_INVALID_ARGUMENT;
4092             goto exit;
4093         }
4094 
4095         /* Too much data provided. */
4096         if( operation->body_remaining < input_length )
4097         {
4098             status = PSA_ERROR_INVALID_ARGUMENT;
4099             goto exit;
4100         }
4101 
4102         operation->body_remaining -= input_length;
4103     }
4104 
4105     status = psa_driver_wrapper_aead_update( operation, input, input_length,
4106                                              output, output_size,
4107                                              output_length );
4108 
4109 exit:
4110     if( status == PSA_SUCCESS )
4111         operation->body_started = 1;
4112     else
4113         psa_aead_abort( operation );
4114 
4115     return( status );
4116 }
4117 
psa_aead_final_checks(const psa_aead_operation_t * operation)4118 static psa_status_t psa_aead_final_checks( const psa_aead_operation_t *operation )
4119 {
4120     if( operation->id == 0 || !operation->nonce_set )
4121         return( PSA_ERROR_BAD_STATE );
4122 
4123     if( operation->lengths_set && ( operation->ad_remaining != 0 ||
4124                                    operation->body_remaining != 0 ) )
4125         return( PSA_ERROR_INVALID_ARGUMENT );
4126 
4127     return( PSA_SUCCESS );
4128 }
4129 
4130 /* Finish encrypting a message in a multipart AEAD operation. */
psa_aead_finish(psa_aead_operation_t * operation,uint8_t * ciphertext,size_t ciphertext_size,size_t * ciphertext_length,uint8_t * tag,size_t tag_size,size_t * tag_length)4131 psa_status_t psa_aead_finish( psa_aead_operation_t *operation,
4132                               uint8_t *ciphertext,
4133                               size_t ciphertext_size,
4134                               size_t *ciphertext_length,
4135                               uint8_t *tag,
4136                               size_t tag_size,
4137                               size_t *tag_length )
4138 {
4139     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4140 
4141     *ciphertext_length = 0;
4142     *tag_length = tag_size;
4143 
4144     status = psa_aead_final_checks( operation );
4145     if( status != PSA_SUCCESS )
4146         goto exit;
4147 
4148     if( !operation->is_encrypt )
4149     {
4150         status = PSA_ERROR_BAD_STATE;
4151         goto exit;
4152     }
4153 
4154     status = psa_driver_wrapper_aead_finish( operation, ciphertext,
4155                                              ciphertext_size,
4156                                              ciphertext_length,
4157                                              tag, tag_size, tag_length );
4158 
4159 exit:
4160     /* In case the operation fails and the user fails to check for failure or
4161      * the zero tag size, make sure the tag is set to something implausible.
4162      * Even if the operation succeeds, make sure we clear the rest of the
4163      * buffer to prevent potential leakage of anything previously placed in
4164      * the same buffer.*/
4165     if( tag != NULL )
4166     {
4167         if( status != PSA_SUCCESS )
4168             memset( tag, '!', tag_size );
4169         else if( *tag_length < tag_size )
4170             memset( tag + *tag_length, '!', ( tag_size - *tag_length ) );
4171     }
4172 
4173     psa_aead_abort( operation );
4174 
4175     return( status );
4176 }
4177 
4178 /* Finish authenticating and decrypting a message in a multipart AEAD
4179    operation.*/
psa_aead_verify(psa_aead_operation_t * operation,uint8_t * plaintext,size_t plaintext_size,size_t * plaintext_length,const uint8_t * tag,size_t tag_length)4180 psa_status_t psa_aead_verify( psa_aead_operation_t *operation,
4181                               uint8_t *plaintext,
4182                               size_t plaintext_size,
4183                               size_t *plaintext_length,
4184                               const uint8_t *tag,
4185                               size_t tag_length )
4186 {
4187     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4188 
4189     *plaintext_length = 0;
4190 
4191     status = psa_aead_final_checks( operation );
4192     if( status != PSA_SUCCESS )
4193         goto exit;
4194 
4195     if( operation->is_encrypt )
4196     {
4197         status = PSA_ERROR_BAD_STATE;
4198         goto exit;
4199     }
4200 
4201     status = psa_driver_wrapper_aead_verify( operation, plaintext,
4202                                              plaintext_size,
4203                                              plaintext_length,
4204                                              tag, tag_length );
4205 
4206 exit:
4207     psa_aead_abort( operation );
4208 
4209     return( status );
4210 }
4211 
4212 /* Abort an AEAD operation. */
psa_aead_abort(psa_aead_operation_t * operation)4213 psa_status_t psa_aead_abort( psa_aead_operation_t *operation )
4214 {
4215     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4216 
4217     if( operation->id == 0 )
4218     {
4219         /* The object has (apparently) been initialized but it is not (yet)
4220          * in use. It's ok to call abort on such an object, and there's
4221          * nothing to do. */
4222         return( PSA_SUCCESS );
4223     }
4224 
4225     status = psa_driver_wrapper_aead_abort( operation );
4226 
4227     memset( operation, 0, sizeof( *operation ) );
4228 
4229     return( status );
4230 }
4231 
4232 /****************************************************************/
4233 /* Generators */
4234 /****************************************************************/
4235 
4236 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF) || \
4237     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
4238     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
4239 #define AT_LEAST_ONE_BUILTIN_KDF
4240 #endif /* At least one builtin KDF */
4241 
4242 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF) || \
4243     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
4244     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
psa_key_derivation_start_hmac(psa_mac_operation_t * operation,psa_algorithm_t hash_alg,const uint8_t * hmac_key,size_t hmac_key_length)4245 static psa_status_t psa_key_derivation_start_hmac(
4246     psa_mac_operation_t *operation,
4247     psa_algorithm_t hash_alg,
4248     const uint8_t *hmac_key,
4249     size_t hmac_key_length )
4250 {
4251     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4252     psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
4253     psa_set_key_type( &attributes, PSA_KEY_TYPE_HMAC );
4254     psa_set_key_bits( &attributes, PSA_BYTES_TO_BITS( hmac_key_length ) );
4255     psa_set_key_usage_flags( &attributes, PSA_KEY_USAGE_SIGN_HASH );
4256 
4257     operation->is_sign = 1;
4258     operation->mac_size = PSA_HASH_LENGTH( hash_alg );
4259 
4260     status = psa_driver_wrapper_mac_sign_setup( operation,
4261                                                 &attributes,
4262                                                 hmac_key, hmac_key_length,
4263                                                 PSA_ALG_HMAC( hash_alg ) );
4264 
4265     psa_reset_key_attributes( &attributes );
4266     return( status );
4267 }
4268 #endif /* KDF algorithms reliant on HMAC */
4269 
4270 #define HKDF_STATE_INIT 0 /* no input yet */
4271 #define HKDF_STATE_STARTED 1 /* got salt */
4272 #define HKDF_STATE_KEYED 2 /* got key */
4273 #define HKDF_STATE_OUTPUT 3 /* output started */
4274 
psa_key_derivation_get_kdf_alg(const psa_key_derivation_operation_t * operation)4275 static psa_algorithm_t psa_key_derivation_get_kdf_alg(
4276     const psa_key_derivation_operation_t *operation )
4277 {
4278     if ( PSA_ALG_IS_KEY_AGREEMENT( operation->alg ) )
4279         return( PSA_ALG_KEY_AGREEMENT_GET_KDF( operation->alg ) );
4280     else
4281         return( operation->alg );
4282 }
4283 
psa_key_derivation_abort(psa_key_derivation_operation_t * operation)4284 psa_status_t psa_key_derivation_abort( psa_key_derivation_operation_t *operation )
4285 {
4286     psa_status_t status = PSA_SUCCESS;
4287     psa_algorithm_t kdf_alg = psa_key_derivation_get_kdf_alg( operation );
4288     if( kdf_alg == 0 )
4289     {
4290         /* The object has (apparently) been initialized but it is not
4291          * in use. It's ok to call abort on such an object, and there's
4292          * nothing to do. */
4293     }
4294     else
4295 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF)
4296     if( PSA_ALG_IS_HKDF( kdf_alg ) )
4297     {
4298         mbedtls_free( operation->ctx.hkdf.info );
4299         status = psa_mac_abort( &operation->ctx.hkdf.hmac );
4300     }
4301     else
4302 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF */
4303 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
4304     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
4305     if( PSA_ALG_IS_TLS12_PRF( kdf_alg ) ||
4306              /* TLS-1.2 PSK-to-MS KDF uses the same core as TLS-1.2 PRF */
4307              PSA_ALG_IS_TLS12_PSK_TO_MS( kdf_alg ) )
4308     {
4309         if( operation->ctx.tls12_prf.secret != NULL )
4310         {
4311             mbedtls_platform_zeroize( operation->ctx.tls12_prf.secret,
4312                                       operation->ctx.tls12_prf.secret_length );
4313             mbedtls_free( operation->ctx.tls12_prf.secret );
4314         }
4315 
4316         if( operation->ctx.tls12_prf.seed != NULL )
4317         {
4318             mbedtls_platform_zeroize( operation->ctx.tls12_prf.seed,
4319                                       operation->ctx.tls12_prf.seed_length );
4320             mbedtls_free( operation->ctx.tls12_prf.seed );
4321         }
4322 
4323         if( operation->ctx.tls12_prf.label != NULL )
4324         {
4325             mbedtls_platform_zeroize( operation->ctx.tls12_prf.label,
4326                                       operation->ctx.tls12_prf.label_length );
4327             mbedtls_free( operation->ctx.tls12_prf.label );
4328         }
4329 
4330         status = PSA_SUCCESS;
4331 
4332         /* We leave the fields Ai and output_block to be erased safely by the
4333          * mbedtls_platform_zeroize() in the end of this function. */
4334     }
4335     else
4336 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) ||
4337         * defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS) */
4338     {
4339         status = PSA_ERROR_BAD_STATE;
4340     }
4341     mbedtls_platform_zeroize( operation, sizeof( *operation ) );
4342     return( status );
4343 }
4344 
psa_key_derivation_get_capacity(const psa_key_derivation_operation_t * operation,size_t * capacity)4345 psa_status_t psa_key_derivation_get_capacity(const psa_key_derivation_operation_t *operation,
4346                                         size_t *capacity)
4347 {
4348     if( operation->alg == 0 )
4349     {
4350         /* This is a blank key derivation operation. */
4351         return( PSA_ERROR_BAD_STATE );
4352     }
4353 
4354     *capacity = operation->capacity;
4355     return( PSA_SUCCESS );
4356 }
4357 
psa_key_derivation_set_capacity(psa_key_derivation_operation_t * operation,size_t capacity)4358 psa_status_t psa_key_derivation_set_capacity( psa_key_derivation_operation_t *operation,
4359                                          size_t capacity )
4360 {
4361     if( operation->alg == 0 )
4362         return( PSA_ERROR_BAD_STATE );
4363     if( capacity > operation->capacity )
4364         return( PSA_ERROR_INVALID_ARGUMENT );
4365     operation->capacity = capacity;
4366     return( PSA_SUCCESS );
4367 }
4368 
4369 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF)
4370 /* Read some bytes from an HKDF-based operation. This performs a chunk
4371  * of the expand phase of the HKDF algorithm. */
psa_key_derivation_hkdf_read(psa_hkdf_key_derivation_t * hkdf,psa_algorithm_t hash_alg,uint8_t * output,size_t output_length)4372 static psa_status_t psa_key_derivation_hkdf_read( psa_hkdf_key_derivation_t *hkdf,
4373                                                   psa_algorithm_t hash_alg,
4374                                                   uint8_t *output,
4375                                                   size_t output_length )
4376 {
4377     uint8_t hash_length = PSA_HASH_LENGTH( hash_alg );
4378     size_t hmac_output_length;
4379     psa_status_t status;
4380 
4381     if( hkdf->state < HKDF_STATE_KEYED || ! hkdf->info_set )
4382         return( PSA_ERROR_BAD_STATE );
4383     hkdf->state = HKDF_STATE_OUTPUT;
4384 
4385     while( output_length != 0 )
4386     {
4387         /* Copy what remains of the current block */
4388         uint8_t n = hash_length - hkdf->offset_in_block;
4389         if( n > output_length )
4390             n = (uint8_t) output_length;
4391         memcpy( output, hkdf->output_block + hkdf->offset_in_block, n );
4392         output += n;
4393         output_length -= n;
4394         hkdf->offset_in_block += n;
4395         if( output_length == 0 )
4396             break;
4397         /* We can't be wanting more output after block 0xff, otherwise
4398          * the capacity check in psa_key_derivation_output_bytes() would have
4399          * prevented this call. It could happen only if the operation
4400          * object was corrupted or if this function is called directly
4401          * inside the library. */
4402         if( hkdf->block_number == 0xff )
4403             return( PSA_ERROR_BAD_STATE );
4404 
4405         /* We need a new block */
4406         ++hkdf->block_number;
4407         hkdf->offset_in_block = 0;
4408 
4409         status = psa_key_derivation_start_hmac( &hkdf->hmac,
4410                                                 hash_alg,
4411                                                 hkdf->prk,
4412                                                 hash_length );
4413         if( status != PSA_SUCCESS )
4414             return( status );
4415 
4416         if( hkdf->block_number != 1 )
4417         {
4418             status = psa_mac_update( &hkdf->hmac,
4419                                      hkdf->output_block,
4420                                      hash_length );
4421             if( status != PSA_SUCCESS )
4422                 return( status );
4423         }
4424         status = psa_mac_update( &hkdf->hmac,
4425                                  hkdf->info,
4426                                  hkdf->info_length );
4427         if( status != PSA_SUCCESS )
4428             return( status );
4429         status = psa_mac_update( &hkdf->hmac,
4430                                  &hkdf->block_number, 1 );
4431         if( status != PSA_SUCCESS )
4432             return( status );
4433         status = psa_mac_sign_finish( &hkdf->hmac,
4434                                       hkdf->output_block,
4435                                       sizeof( hkdf->output_block ),
4436                                       &hmac_output_length );
4437         if( status != PSA_SUCCESS )
4438             return( status );
4439     }
4440 
4441     return( PSA_SUCCESS );
4442 }
4443 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF */
4444 
4445 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
4446     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
psa_key_derivation_tls12_prf_generate_next_block(psa_tls12_prf_key_derivation_t * tls12_prf,psa_algorithm_t alg)4447 static psa_status_t psa_key_derivation_tls12_prf_generate_next_block(
4448     psa_tls12_prf_key_derivation_t *tls12_prf,
4449     psa_algorithm_t alg )
4450 {
4451     psa_algorithm_t hash_alg = PSA_ALG_HKDF_GET_HASH( alg );
4452     uint8_t hash_length = PSA_HASH_LENGTH( hash_alg );
4453     psa_mac_operation_t hmac = PSA_MAC_OPERATION_INIT;
4454     size_t hmac_output_length;
4455     psa_status_t status, cleanup_status;
4456 
4457     /* We can't be wanting more output after block 0xff, otherwise
4458      * the capacity check in psa_key_derivation_output_bytes() would have
4459      * prevented this call. It could happen only if the operation
4460      * object was corrupted or if this function is called directly
4461      * inside the library. */
4462     if( tls12_prf->block_number == 0xff )
4463         return( PSA_ERROR_CORRUPTION_DETECTED );
4464 
4465     /* We need a new block */
4466     ++tls12_prf->block_number;
4467     tls12_prf->left_in_block = hash_length;
4468 
4469     /* Recall the definition of the TLS-1.2-PRF from RFC 5246:
4470      *
4471      * PRF(secret, label, seed) = P_<hash>(secret, label + seed)
4472      *
4473      * P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
4474      *                        HMAC_hash(secret, A(2) + seed) +
4475      *                        HMAC_hash(secret, A(3) + seed) + ...
4476      *
4477      * A(0) = seed
4478      * A(i) = HMAC_hash(secret, A(i-1))
4479      *
4480      * The `psa_tls12_prf_key_derivation` structure saves the block
4481      * `HMAC_hash(secret, A(i) + seed)` from which the output
4482      * is currently extracted as `output_block` and where i is
4483      * `block_number`.
4484      */
4485 
4486     status = psa_key_derivation_start_hmac( &hmac,
4487                                             hash_alg,
4488                                             tls12_prf->secret,
4489                                             tls12_prf->secret_length );
4490     if( status != PSA_SUCCESS )
4491         goto cleanup;
4492 
4493     /* Calculate A(i) where i = tls12_prf->block_number. */
4494     if( tls12_prf->block_number == 1 )
4495     {
4496         /* A(1) = HMAC_hash(secret, A(0)), where A(0) = seed. (The RFC overloads
4497          * the variable seed and in this instance means it in the context of the
4498          * P_hash function, where seed = label + seed.) */
4499         status = psa_mac_update( &hmac,
4500                                  tls12_prf->label,
4501                                  tls12_prf->label_length );
4502         if( status != PSA_SUCCESS )
4503             goto cleanup;
4504         status = psa_mac_update( &hmac,
4505                                  tls12_prf->seed,
4506                                  tls12_prf->seed_length );
4507         if( status != PSA_SUCCESS )
4508             goto cleanup;
4509     }
4510     else
4511     {
4512         /* A(i) = HMAC_hash(secret, A(i-1)) */
4513         status = psa_mac_update( &hmac, tls12_prf->Ai, hash_length );
4514         if( status != PSA_SUCCESS )
4515             goto cleanup;
4516     }
4517 
4518     status = psa_mac_sign_finish( &hmac,
4519                                   tls12_prf->Ai, hash_length,
4520                                   &hmac_output_length );
4521     if( hmac_output_length != hash_length )
4522         status = PSA_ERROR_CORRUPTION_DETECTED;
4523     if( status != PSA_SUCCESS )
4524         goto cleanup;
4525 
4526     /* Calculate HMAC_hash(secret, A(i) + label + seed). */
4527     status = psa_key_derivation_start_hmac( &hmac,
4528                                             hash_alg,
4529                                             tls12_prf->secret,
4530                                             tls12_prf->secret_length );
4531     if( status != PSA_SUCCESS )
4532         goto cleanup;
4533     status = psa_mac_update( &hmac, tls12_prf->Ai, hash_length );
4534     if( status != PSA_SUCCESS )
4535         goto cleanup;
4536     status = psa_mac_update( &hmac, tls12_prf->label, tls12_prf->label_length );
4537     if( status != PSA_SUCCESS )
4538         goto cleanup;
4539     status = psa_mac_update( &hmac, tls12_prf->seed, tls12_prf->seed_length );
4540     if( status != PSA_SUCCESS )
4541         goto cleanup;
4542     status = psa_mac_sign_finish( &hmac,
4543                                   tls12_prf->output_block, hash_length,
4544                                   &hmac_output_length );
4545     if( status != PSA_SUCCESS )
4546         goto cleanup;
4547 
4548 
4549 cleanup:
4550     cleanup_status = psa_mac_abort( &hmac );
4551     if( status == PSA_SUCCESS && cleanup_status != PSA_SUCCESS )
4552         status = cleanup_status;
4553 
4554     return( status );
4555 }
4556 
psa_key_derivation_tls12_prf_read(psa_tls12_prf_key_derivation_t * tls12_prf,psa_algorithm_t alg,uint8_t * output,size_t output_length)4557 static psa_status_t psa_key_derivation_tls12_prf_read(
4558     psa_tls12_prf_key_derivation_t *tls12_prf,
4559     psa_algorithm_t alg,
4560     uint8_t *output,
4561     size_t output_length )
4562 {
4563     psa_algorithm_t hash_alg = PSA_ALG_TLS12_PRF_GET_HASH( alg );
4564     uint8_t hash_length = PSA_HASH_LENGTH( hash_alg );
4565     psa_status_t status;
4566     uint8_t offset, length;
4567 
4568     switch( tls12_prf->state )
4569     {
4570         case PSA_TLS12_PRF_STATE_LABEL_SET:
4571             tls12_prf->state = PSA_TLS12_PRF_STATE_OUTPUT;
4572             break;
4573         case PSA_TLS12_PRF_STATE_OUTPUT:
4574             break;
4575         default:
4576             return( PSA_ERROR_BAD_STATE );
4577     }
4578 
4579     while( output_length != 0 )
4580     {
4581         /* Check if we have fully processed the current block. */
4582         if( tls12_prf->left_in_block == 0 )
4583         {
4584             status = psa_key_derivation_tls12_prf_generate_next_block( tls12_prf,
4585                                                                        alg );
4586             if( status != PSA_SUCCESS )
4587                 return( status );
4588 
4589             continue;
4590         }
4591 
4592         if( tls12_prf->left_in_block > output_length )
4593             length = (uint8_t) output_length;
4594         else
4595             length = tls12_prf->left_in_block;
4596 
4597         offset = hash_length - tls12_prf->left_in_block;
4598         memcpy( output, tls12_prf->output_block + offset, length );
4599         output += length;
4600         output_length -= length;
4601         tls12_prf->left_in_block -= length;
4602     }
4603 
4604     return( PSA_SUCCESS );
4605 }
4606 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF ||
4607         * MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
4608 
psa_key_derivation_output_bytes(psa_key_derivation_operation_t * operation,uint8_t * output,size_t output_length)4609 psa_status_t psa_key_derivation_output_bytes(
4610     psa_key_derivation_operation_t *operation,
4611     uint8_t *output,
4612     size_t output_length )
4613 {
4614     psa_status_t status;
4615     psa_algorithm_t kdf_alg = psa_key_derivation_get_kdf_alg( operation );
4616 
4617     if( operation->alg == 0 )
4618     {
4619         /* This is a blank operation. */
4620         return( PSA_ERROR_BAD_STATE );
4621     }
4622 
4623     if( output_length > operation->capacity )
4624     {
4625         operation->capacity = 0;
4626         /* Go through the error path to wipe all confidential data now
4627          * that the operation object is useless. */
4628         status = PSA_ERROR_INSUFFICIENT_DATA;
4629         goto exit;
4630     }
4631     if( output_length == 0 && operation->capacity == 0 )
4632     {
4633         /* Edge case: this is a finished operation, and 0 bytes
4634          * were requested. The right error in this case could
4635          * be either INSUFFICIENT_CAPACITY or BAD_STATE. Return
4636          * INSUFFICIENT_CAPACITY, which is right for a finished
4637          * operation, for consistency with the case when
4638          * output_length > 0. */
4639         return( PSA_ERROR_INSUFFICIENT_DATA );
4640     }
4641     operation->capacity -= output_length;
4642 
4643 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF)
4644     if( PSA_ALG_IS_HKDF( kdf_alg ) )
4645     {
4646         psa_algorithm_t hash_alg = PSA_ALG_HKDF_GET_HASH( kdf_alg );
4647         status = psa_key_derivation_hkdf_read( &operation->ctx.hkdf, hash_alg,
4648                                           output, output_length );
4649     }
4650     else
4651 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF */
4652 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
4653     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
4654     if( PSA_ALG_IS_TLS12_PRF( kdf_alg ) ||
4655         PSA_ALG_IS_TLS12_PSK_TO_MS( kdf_alg ) )
4656     {
4657         status = psa_key_derivation_tls12_prf_read( &operation->ctx.tls12_prf,
4658                                                     kdf_alg, output,
4659                                                     output_length );
4660     }
4661     else
4662 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF ||
4663         * MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
4664     {
4665         (void) kdf_alg;
4666         return( PSA_ERROR_BAD_STATE );
4667     }
4668 
4669 exit:
4670     if( status != PSA_SUCCESS )
4671     {
4672         /* Preserve the algorithm upon errors, but clear all sensitive state.
4673          * This allows us to differentiate between exhausted operations and
4674          * blank operations, so we can return PSA_ERROR_BAD_STATE on blank
4675          * operations. */
4676         psa_algorithm_t alg = operation->alg;
4677         psa_key_derivation_abort( operation );
4678         operation->alg = alg;
4679         memset( output, '!', output_length );
4680     }
4681     return( status );
4682 }
4683 
4684 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES)
psa_des_set_key_parity(uint8_t * data,size_t data_size)4685 static void psa_des_set_key_parity( uint8_t *data, size_t data_size )
4686 {
4687     if( data_size >= 8 )
4688         mbedtls_des_key_set_parity( data );
4689     if( data_size >= 16 )
4690         mbedtls_des_key_set_parity( data + 8 );
4691     if( data_size >= 24 )
4692         mbedtls_des_key_set_parity( data + 16 );
4693 }
4694 #endif /* MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES */
4695 
psa_generate_derived_key_internal(psa_key_slot_t * slot,size_t bits,psa_key_derivation_operation_t * operation)4696 static psa_status_t psa_generate_derived_key_internal(
4697     psa_key_slot_t *slot,
4698     size_t bits,
4699     psa_key_derivation_operation_t *operation )
4700 {
4701     uint8_t *data = NULL;
4702     size_t bytes = PSA_BITS_TO_BYTES( bits );
4703     size_t storage_size = bytes;
4704     psa_status_t status;
4705 
4706     if( ! key_type_is_raw_bytes( slot->attr.type ) )
4707         return( PSA_ERROR_INVALID_ARGUMENT );
4708     if( bits % 8 != 0 )
4709         return( PSA_ERROR_INVALID_ARGUMENT );
4710     data = mbedtls_calloc( 1, bytes );
4711     if( data == NULL )
4712         return( PSA_ERROR_INSUFFICIENT_MEMORY );
4713 
4714     status = psa_key_derivation_output_bytes( operation, data, bytes );
4715     if( status != PSA_SUCCESS )
4716         goto exit;
4717 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES)
4718     if( slot->attr.type == PSA_KEY_TYPE_DES )
4719         psa_des_set_key_parity( data, bytes );
4720 #endif /* MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES */
4721 
4722     slot->attr.bits = (psa_key_bits_t) bits;
4723     psa_key_attributes_t attributes = {
4724       .core = slot->attr
4725     };
4726 
4727     if( psa_key_lifetime_is_external( attributes.core.lifetime ) )
4728     {
4729         status = psa_driver_wrapper_get_key_buffer_size( &attributes,
4730                                                          &storage_size );
4731         if( status != PSA_SUCCESS )
4732             goto exit;
4733     }
4734     status = psa_allocate_buffer_to_slot( slot, storage_size );
4735     if( status != PSA_SUCCESS )
4736         goto exit;
4737 
4738     status = psa_driver_wrapper_import_key( &attributes,
4739                                             data, bytes,
4740                                             slot->key.data,
4741                                             slot->key.bytes,
4742                                             &slot->key.bytes, &bits );
4743     if( bits != slot->attr.bits )
4744         status = PSA_ERROR_INVALID_ARGUMENT;
4745 
4746 exit:
4747     mbedtls_free( data );
4748     return( status );
4749 }
4750 
psa_key_derivation_output_key(const psa_key_attributes_t * attributes,psa_key_derivation_operation_t * operation,mbedtls_svc_key_id_t * key)4751 psa_status_t psa_key_derivation_output_key( const psa_key_attributes_t *attributes,
4752                                        psa_key_derivation_operation_t *operation,
4753                                        mbedtls_svc_key_id_t *key )
4754 {
4755     psa_status_t status;
4756     psa_key_slot_t *slot = NULL;
4757     psa_se_drv_table_entry_t *driver = NULL;
4758 
4759     *key = MBEDTLS_SVC_KEY_ID_INIT;
4760 
4761     /* Reject any attempt to create a zero-length key so that we don't
4762      * risk tripping up later, e.g. on a malloc(0) that returns NULL. */
4763     if( psa_get_key_bits( attributes ) == 0 )
4764         return( PSA_ERROR_INVALID_ARGUMENT );
4765 
4766     if( ! operation->can_output_key )
4767         return( PSA_ERROR_NOT_PERMITTED );
4768 
4769     status = psa_start_key_creation( PSA_KEY_CREATION_DERIVE, attributes,
4770                                      &slot, &driver );
4771 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
4772     if( driver != NULL )
4773     {
4774         /* Deriving a key in a secure element is not implemented yet. */
4775         status = PSA_ERROR_NOT_SUPPORTED;
4776     }
4777 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
4778     if( status == PSA_SUCCESS )
4779     {
4780         status = psa_generate_derived_key_internal( slot,
4781                                                     attributes->core.bits,
4782                                                     operation );
4783     }
4784     if( status == PSA_SUCCESS )
4785         status = psa_finish_key_creation( slot, driver, key );
4786     if( status != PSA_SUCCESS )
4787         psa_fail_key_creation( slot, driver );
4788 
4789     return( status );
4790 }
4791 
4792 
4793 
4794 /****************************************************************/
4795 /* Key derivation */
4796 /****************************************************************/
4797 
4798 #if defined(AT_LEAST_ONE_BUILTIN_KDF)
psa_key_derivation_setup_kdf(psa_key_derivation_operation_t * operation,psa_algorithm_t kdf_alg)4799 static psa_status_t psa_key_derivation_setup_kdf(
4800     psa_key_derivation_operation_t *operation,
4801     psa_algorithm_t kdf_alg )
4802 {
4803     int is_kdf_alg_supported;
4804 
4805     /* Make sure that operation->ctx is properly zero-initialised. (Macro
4806      * initialisers for this union leave some bytes unspecified.) */
4807     memset( &operation->ctx, 0, sizeof( operation->ctx ) );
4808 
4809     /* Make sure that kdf_alg is a supported key derivation algorithm. */
4810 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF)
4811     if( PSA_ALG_IS_HKDF( kdf_alg ) )
4812         is_kdf_alg_supported = 1;
4813     else
4814 #endif
4815 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF)
4816     if( PSA_ALG_IS_TLS12_PRF( kdf_alg ) )
4817         is_kdf_alg_supported = 1;
4818     else
4819 #endif
4820 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
4821     if( PSA_ALG_IS_TLS12_PSK_TO_MS( kdf_alg ) )
4822         is_kdf_alg_supported = 1;
4823     else
4824 #endif
4825     is_kdf_alg_supported = 0;
4826 
4827     if( is_kdf_alg_supported )
4828     {
4829         psa_algorithm_t hash_alg = PSA_ALG_HKDF_GET_HASH( kdf_alg );
4830         size_t hash_size = PSA_HASH_LENGTH( hash_alg );
4831         if( hash_size == 0 )
4832             return( PSA_ERROR_NOT_SUPPORTED );
4833         if( ( PSA_ALG_IS_TLS12_PRF( kdf_alg ) ||
4834               PSA_ALG_IS_TLS12_PSK_TO_MS( kdf_alg ) ) &&
4835             ! ( hash_alg == PSA_ALG_SHA_256 || hash_alg == PSA_ALG_SHA_384 ) )
4836         {
4837             return( PSA_ERROR_NOT_SUPPORTED );
4838         }
4839         operation->capacity = 255 * hash_size;
4840         return( PSA_SUCCESS );
4841     }
4842 
4843     return( PSA_ERROR_NOT_SUPPORTED );
4844 }
4845 #endif /* AT_LEAST_ONE_BUILTIN_KDF */
4846 
psa_key_derivation_setup(psa_key_derivation_operation_t * operation,psa_algorithm_t alg)4847 psa_status_t psa_key_derivation_setup( psa_key_derivation_operation_t *operation,
4848                                        psa_algorithm_t alg )
4849 {
4850     psa_status_t status;
4851 
4852     if( operation->alg != 0 )
4853         return( PSA_ERROR_BAD_STATE );
4854 
4855     if( PSA_ALG_IS_RAW_KEY_AGREEMENT( alg ) )
4856         return( PSA_ERROR_INVALID_ARGUMENT );
4857     else if( PSA_ALG_IS_KEY_AGREEMENT( alg ) )
4858     {
4859 #if defined(AT_LEAST_ONE_BUILTIN_KDF)
4860         psa_algorithm_t kdf_alg = PSA_ALG_KEY_AGREEMENT_GET_KDF( alg );
4861         status = psa_key_derivation_setup_kdf( operation, kdf_alg );
4862 #else
4863         return( PSA_ERROR_NOT_SUPPORTED );
4864 #endif /* AT_LEAST_ONE_BUILTIN_KDF */
4865     }
4866     else if( PSA_ALG_IS_KEY_DERIVATION( alg ) )
4867     {
4868 #if defined(AT_LEAST_ONE_BUILTIN_KDF)
4869         status = psa_key_derivation_setup_kdf( operation, alg );
4870 #else
4871         return( PSA_ERROR_NOT_SUPPORTED );
4872 #endif /* AT_LEAST_ONE_BUILTIN_KDF */
4873     }
4874     else
4875         return( PSA_ERROR_INVALID_ARGUMENT );
4876 
4877     if( status == PSA_SUCCESS )
4878         operation->alg = alg;
4879     return( status );
4880 }
4881 
4882 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF)
psa_hkdf_input(psa_hkdf_key_derivation_t * hkdf,psa_algorithm_t hash_alg,psa_key_derivation_step_t step,const uint8_t * data,size_t data_length)4883 static psa_status_t psa_hkdf_input( psa_hkdf_key_derivation_t *hkdf,
4884                                     psa_algorithm_t hash_alg,
4885                                     psa_key_derivation_step_t step,
4886                                     const uint8_t *data,
4887                                     size_t data_length )
4888 {
4889     psa_status_t status;
4890     switch( step )
4891     {
4892         case PSA_KEY_DERIVATION_INPUT_SALT:
4893             if( hkdf->state != HKDF_STATE_INIT )
4894                 return( PSA_ERROR_BAD_STATE );
4895             else
4896             {
4897                 status = psa_key_derivation_start_hmac( &hkdf->hmac,
4898                                                         hash_alg,
4899                                                         data, data_length );
4900                 if( status != PSA_SUCCESS )
4901                     return( status );
4902                 hkdf->state = HKDF_STATE_STARTED;
4903                 return( PSA_SUCCESS );
4904             }
4905         case PSA_KEY_DERIVATION_INPUT_SECRET:
4906             /* If no salt was provided, use an empty salt. */
4907             if( hkdf->state == HKDF_STATE_INIT )
4908             {
4909                 status = psa_key_derivation_start_hmac( &hkdf->hmac,
4910                                                         hash_alg,
4911                                                         NULL, 0 );
4912                 if( status != PSA_SUCCESS )
4913                     return( status );
4914                 hkdf->state = HKDF_STATE_STARTED;
4915             }
4916             if( hkdf->state != HKDF_STATE_STARTED )
4917                 return( PSA_ERROR_BAD_STATE );
4918             status = psa_mac_update( &hkdf->hmac,
4919                                      data, data_length );
4920             if( status != PSA_SUCCESS )
4921                 return( status );
4922             status = psa_mac_sign_finish( &hkdf->hmac,
4923                                           hkdf->prk,
4924                                           sizeof( hkdf->prk ),
4925                                           &data_length );
4926             if( status != PSA_SUCCESS )
4927                 return( status );
4928             hkdf->offset_in_block = PSA_HASH_LENGTH( hash_alg );
4929             hkdf->block_number = 0;
4930             hkdf->state = HKDF_STATE_KEYED;
4931             return( PSA_SUCCESS );
4932         case PSA_KEY_DERIVATION_INPUT_INFO:
4933             if( hkdf->state == HKDF_STATE_OUTPUT )
4934                 return( PSA_ERROR_BAD_STATE );
4935             if( hkdf->info_set )
4936                 return( PSA_ERROR_BAD_STATE );
4937             hkdf->info_length = data_length;
4938             if( data_length != 0 )
4939             {
4940                 hkdf->info = mbedtls_calloc( 1, data_length );
4941                 if( hkdf->info == NULL )
4942                     return( PSA_ERROR_INSUFFICIENT_MEMORY );
4943                 memcpy( hkdf->info, data, data_length );
4944             }
4945             hkdf->info_set = 1;
4946             return( PSA_SUCCESS );
4947         default:
4948             return( PSA_ERROR_INVALID_ARGUMENT );
4949     }
4950 }
4951 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF */
4952 
4953 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
4954     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
psa_tls12_prf_set_seed(psa_tls12_prf_key_derivation_t * prf,const uint8_t * data,size_t data_length)4955 static psa_status_t psa_tls12_prf_set_seed( psa_tls12_prf_key_derivation_t *prf,
4956                                             const uint8_t *data,
4957                                             size_t data_length )
4958 {
4959     if( prf->state != PSA_TLS12_PRF_STATE_INIT )
4960         return( PSA_ERROR_BAD_STATE );
4961 
4962     if( data_length != 0 )
4963     {
4964         prf->seed = mbedtls_calloc( 1, data_length );
4965         if( prf->seed == NULL )
4966             return( PSA_ERROR_INSUFFICIENT_MEMORY );
4967 
4968         memcpy( prf->seed, data, data_length );
4969         prf->seed_length = data_length;
4970     }
4971 
4972     prf->state = PSA_TLS12_PRF_STATE_SEED_SET;
4973 
4974     return( PSA_SUCCESS );
4975 }
4976 
psa_tls12_prf_set_key(psa_tls12_prf_key_derivation_t * prf,const uint8_t * data,size_t data_length)4977 static psa_status_t psa_tls12_prf_set_key( psa_tls12_prf_key_derivation_t *prf,
4978                                            const uint8_t *data,
4979                                            size_t data_length )
4980 {
4981     if( prf->state != PSA_TLS12_PRF_STATE_SEED_SET )
4982         return( PSA_ERROR_BAD_STATE );
4983 
4984     if( data_length != 0 )
4985     {
4986         prf->secret = mbedtls_calloc( 1, data_length );
4987         if( prf->secret == NULL )
4988             return( PSA_ERROR_INSUFFICIENT_MEMORY );
4989 
4990         memcpy( prf->secret, data, data_length );
4991         prf->secret_length = data_length;
4992     }
4993 
4994     prf->state = PSA_TLS12_PRF_STATE_KEY_SET;
4995 
4996     return( PSA_SUCCESS );
4997 }
4998 
psa_tls12_prf_set_label(psa_tls12_prf_key_derivation_t * prf,const uint8_t * data,size_t data_length)4999 static psa_status_t psa_tls12_prf_set_label( psa_tls12_prf_key_derivation_t *prf,
5000                                              const uint8_t *data,
5001                                              size_t data_length )
5002 {
5003     if( prf->state != PSA_TLS12_PRF_STATE_KEY_SET )
5004         return( PSA_ERROR_BAD_STATE );
5005 
5006     if( data_length != 0 )
5007     {
5008         prf->label = mbedtls_calloc( 1, data_length );
5009         if( prf->label == NULL )
5010             return( PSA_ERROR_INSUFFICIENT_MEMORY );
5011 
5012         memcpy( prf->label, data, data_length );
5013         prf->label_length = data_length;
5014     }
5015 
5016     prf->state = PSA_TLS12_PRF_STATE_LABEL_SET;
5017 
5018     return( PSA_SUCCESS );
5019 }
5020 
psa_tls12_prf_input(psa_tls12_prf_key_derivation_t * prf,psa_key_derivation_step_t step,const uint8_t * data,size_t data_length)5021 static psa_status_t psa_tls12_prf_input( psa_tls12_prf_key_derivation_t *prf,
5022                                          psa_key_derivation_step_t step,
5023                                          const uint8_t *data,
5024                                          size_t data_length )
5025 {
5026     switch( step )
5027     {
5028         case PSA_KEY_DERIVATION_INPUT_SEED:
5029             return( psa_tls12_prf_set_seed( prf, data, data_length ) );
5030         case PSA_KEY_DERIVATION_INPUT_SECRET:
5031             return( psa_tls12_prf_set_key( prf, data, data_length ) );
5032         case PSA_KEY_DERIVATION_INPUT_LABEL:
5033             return( psa_tls12_prf_set_label( prf, data, data_length ) );
5034         default:
5035             return( PSA_ERROR_INVALID_ARGUMENT );
5036     }
5037 }
5038 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) ||
5039         * MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
5040 
5041 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
psa_tls12_prf_psk_to_ms_set_key(psa_tls12_prf_key_derivation_t * prf,const uint8_t * data,size_t data_length)5042 static psa_status_t psa_tls12_prf_psk_to_ms_set_key(
5043     psa_tls12_prf_key_derivation_t *prf,
5044     const uint8_t *data,
5045     size_t data_length )
5046 {
5047     psa_status_t status;
5048     uint8_t pms[ 4 + 2 * PSA_TLS12_PSK_TO_MS_PSK_MAX_SIZE ];
5049     uint8_t *cur = pms;
5050 
5051     if( data_length > PSA_TLS12_PSK_TO_MS_PSK_MAX_SIZE )
5052         return( PSA_ERROR_INVALID_ARGUMENT );
5053 
5054     /* Quoting RFC 4279, Section 2:
5055      *
5056      * The premaster secret is formed as follows: if the PSK is N octets
5057      * long, concatenate a uint16 with the value N, N zero octets, a second
5058      * uint16 with the value N, and the PSK itself.
5059      */
5060 
5061     *cur++ = MBEDTLS_BYTE_1( data_length );
5062     *cur++ = MBEDTLS_BYTE_0( data_length );
5063     memset( cur, 0, data_length );
5064     cur += data_length;
5065     *cur++ = pms[0];
5066     *cur++ = pms[1];
5067     memcpy( cur, data, data_length );
5068     cur += data_length;
5069 
5070     status = psa_tls12_prf_set_key( prf, pms, cur - pms );
5071 
5072     mbedtls_platform_zeroize( pms, sizeof( pms ) );
5073     return( status );
5074 }
5075 
psa_tls12_prf_psk_to_ms_input(psa_tls12_prf_key_derivation_t * prf,psa_key_derivation_step_t step,const uint8_t * data,size_t data_length)5076 static psa_status_t psa_tls12_prf_psk_to_ms_input(
5077     psa_tls12_prf_key_derivation_t *prf,
5078     psa_key_derivation_step_t step,
5079     const uint8_t *data,
5080     size_t data_length )
5081 {
5082     if( step == PSA_KEY_DERIVATION_INPUT_SECRET )
5083     {
5084         return( psa_tls12_prf_psk_to_ms_set_key( prf,
5085                                                  data, data_length ) );
5086     }
5087 
5088     return( psa_tls12_prf_input( prf, step, data, data_length ) );
5089 }
5090 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
5091 
5092 /** Check whether the given key type is acceptable for the given
5093  * input step of a key derivation.
5094  *
5095  * Secret inputs must have the type #PSA_KEY_TYPE_DERIVE.
5096  * Non-secret inputs must have the type #PSA_KEY_TYPE_RAW_DATA.
5097  * Both secret and non-secret inputs can alternatively have the type
5098  * #PSA_KEY_TYPE_NONE, which is never the type of a key object, meaning
5099  * that the input was passed as a buffer rather than via a key object.
5100  */
psa_key_derivation_check_input_type(psa_key_derivation_step_t step,psa_key_type_t key_type)5101 static int psa_key_derivation_check_input_type(
5102     psa_key_derivation_step_t step,
5103     psa_key_type_t key_type )
5104 {
5105     switch( step )
5106     {
5107         case PSA_KEY_DERIVATION_INPUT_SECRET:
5108             if( key_type == PSA_KEY_TYPE_DERIVE )
5109                 return( PSA_SUCCESS );
5110             if( key_type == PSA_KEY_TYPE_NONE )
5111                 return( PSA_SUCCESS );
5112             break;
5113         case PSA_KEY_DERIVATION_INPUT_LABEL:
5114         case PSA_KEY_DERIVATION_INPUT_SALT:
5115         case PSA_KEY_DERIVATION_INPUT_INFO:
5116         case PSA_KEY_DERIVATION_INPUT_SEED:
5117             if( key_type == PSA_KEY_TYPE_RAW_DATA )
5118                 return( PSA_SUCCESS );
5119             if( key_type == PSA_KEY_TYPE_NONE )
5120                 return( PSA_SUCCESS );
5121             break;
5122     }
5123     return( PSA_ERROR_INVALID_ARGUMENT );
5124 }
5125 
psa_key_derivation_input_internal(psa_key_derivation_operation_t * operation,psa_key_derivation_step_t step,psa_key_type_t key_type,const uint8_t * data,size_t data_length)5126 static psa_status_t psa_key_derivation_input_internal(
5127     psa_key_derivation_operation_t *operation,
5128     psa_key_derivation_step_t step,
5129     psa_key_type_t key_type,
5130     const uint8_t *data,
5131     size_t data_length )
5132 {
5133     psa_status_t status;
5134     psa_algorithm_t kdf_alg = psa_key_derivation_get_kdf_alg( operation );
5135 
5136     status = psa_key_derivation_check_input_type( step, key_type );
5137     if( status != PSA_SUCCESS )
5138         goto exit;
5139 
5140 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF)
5141     if( PSA_ALG_IS_HKDF( kdf_alg ) )
5142     {
5143         status = psa_hkdf_input( &operation->ctx.hkdf,
5144                                  PSA_ALG_HKDF_GET_HASH( kdf_alg ),
5145                                  step, data, data_length );
5146     }
5147     else
5148 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF */
5149 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF)
5150     if( PSA_ALG_IS_TLS12_PRF( kdf_alg ) )
5151     {
5152         status = psa_tls12_prf_input( &operation->ctx.tls12_prf,
5153                                       step, data, data_length );
5154     }
5155     else
5156 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF */
5157 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
5158     if( PSA_ALG_IS_TLS12_PSK_TO_MS( kdf_alg ) )
5159     {
5160         status = psa_tls12_prf_psk_to_ms_input( &operation->ctx.tls12_prf,
5161                                                 step, data, data_length );
5162     }
5163     else
5164 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
5165     {
5166         /* This can't happen unless the operation object was not initialized */
5167         (void) data;
5168         (void) data_length;
5169         (void) kdf_alg;
5170         return( PSA_ERROR_BAD_STATE );
5171     }
5172 
5173 exit:
5174     if( status != PSA_SUCCESS )
5175         psa_key_derivation_abort( operation );
5176     return( status );
5177 }
5178 
psa_key_derivation_input_bytes(psa_key_derivation_operation_t * operation,psa_key_derivation_step_t step,const uint8_t * data,size_t data_length)5179 psa_status_t psa_key_derivation_input_bytes(
5180     psa_key_derivation_operation_t *operation,
5181     psa_key_derivation_step_t step,
5182     const uint8_t *data,
5183     size_t data_length )
5184 {
5185     return( psa_key_derivation_input_internal( operation, step,
5186                                                PSA_KEY_TYPE_NONE,
5187                                                data, data_length ) );
5188 }
5189 
psa_key_derivation_input_key(psa_key_derivation_operation_t * operation,psa_key_derivation_step_t step,mbedtls_svc_key_id_t key)5190 psa_status_t psa_key_derivation_input_key(
5191     psa_key_derivation_operation_t *operation,
5192     psa_key_derivation_step_t step,
5193     mbedtls_svc_key_id_t key )
5194 {
5195     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
5196     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
5197     psa_key_slot_t *slot;
5198 
5199     status = psa_get_and_lock_transparent_key_slot_with_policy(
5200                  key, &slot, PSA_KEY_USAGE_DERIVE, operation->alg );
5201     if( status != PSA_SUCCESS )
5202     {
5203         psa_key_derivation_abort( operation );
5204         return( status );
5205     }
5206 
5207     /* Passing a key object as a SECRET input unlocks the permission
5208      * to output to a key object. */
5209     if( step == PSA_KEY_DERIVATION_INPUT_SECRET )
5210         operation->can_output_key = 1;
5211 
5212     status = psa_key_derivation_input_internal( operation,
5213                                                 step, slot->attr.type,
5214                                                 slot->key.data,
5215                                                 slot->key.bytes );
5216 
5217     unlock_status = psa_unlock_key_slot( slot );
5218 
5219     return( ( status == PSA_SUCCESS ) ? unlock_status : status );
5220 }
5221 
5222 
5223 
5224 /****************************************************************/
5225 /* Key agreement */
5226 /****************************************************************/
5227 
5228 #if defined(MBEDTLS_PSA_BUILTIN_ALG_ECDH)
psa_key_agreement_ecdh(const uint8_t * peer_key,size_t peer_key_length,const mbedtls_ecp_keypair * our_key,uint8_t * shared_secret,size_t shared_secret_size,size_t * shared_secret_length)5229 static psa_status_t psa_key_agreement_ecdh( const uint8_t *peer_key,
5230                                             size_t peer_key_length,
5231                                             const mbedtls_ecp_keypair *our_key,
5232                                             uint8_t *shared_secret,
5233                                             size_t shared_secret_size,
5234                                             size_t *shared_secret_length )
5235 {
5236     mbedtls_ecp_keypair *their_key = NULL;
5237     mbedtls_ecdh_context ecdh;
5238     psa_status_t status;
5239     size_t bits = 0;
5240     psa_ecc_family_t curve = mbedtls_ecc_group_to_psa( our_key->grp.id, &bits );
5241     mbedtls_ecdh_init( &ecdh );
5242 
5243     status = mbedtls_psa_ecp_load_representation(
5244                  PSA_KEY_TYPE_ECC_PUBLIC_KEY(curve),
5245                  bits,
5246                  peer_key,
5247                  peer_key_length,
5248                  &their_key );
5249     if( status != PSA_SUCCESS )
5250         goto exit;
5251 
5252     status = mbedtls_to_psa_error(
5253         mbedtls_ecdh_get_params( &ecdh, their_key, MBEDTLS_ECDH_THEIRS ) );
5254     if( status != PSA_SUCCESS )
5255         goto exit;
5256     status = mbedtls_to_psa_error(
5257         mbedtls_ecdh_get_params( &ecdh, our_key, MBEDTLS_ECDH_OURS ) );
5258     if( status != PSA_SUCCESS )
5259         goto exit;
5260 
5261     status = mbedtls_to_psa_error(
5262         mbedtls_ecdh_calc_secret( &ecdh,
5263                                   shared_secret_length,
5264                                   shared_secret, shared_secret_size,
5265                                   mbedtls_psa_get_random,
5266                                   MBEDTLS_PSA_RANDOM_STATE ) );
5267     if( status != PSA_SUCCESS )
5268         goto exit;
5269     if( PSA_BITS_TO_BYTES( bits ) != *shared_secret_length )
5270         status = PSA_ERROR_CORRUPTION_DETECTED;
5271 
5272 exit:
5273     if( status != PSA_SUCCESS )
5274         mbedtls_platform_zeroize( shared_secret, shared_secret_size );
5275     mbedtls_ecdh_free( &ecdh );
5276     mbedtls_ecp_keypair_free( their_key );
5277     mbedtls_free( their_key );
5278 
5279     return( status );
5280 }
5281 #endif /* MBEDTLS_PSA_BUILTIN_ALG_ECDH */
5282 
5283 #define PSA_KEY_AGREEMENT_MAX_SHARED_SECRET_SIZE MBEDTLS_ECP_MAX_BYTES
5284 
psa_key_agreement_raw_internal(psa_algorithm_t alg,psa_key_slot_t * private_key,const uint8_t * peer_key,size_t peer_key_length,uint8_t * shared_secret,size_t shared_secret_size,size_t * shared_secret_length)5285 static psa_status_t psa_key_agreement_raw_internal( psa_algorithm_t alg,
5286                                                     psa_key_slot_t *private_key,
5287                                                     const uint8_t *peer_key,
5288                                                     size_t peer_key_length,
5289                                                     uint8_t *shared_secret,
5290                                                     size_t shared_secret_size,
5291                                                     size_t *shared_secret_length )
5292 {
5293     switch( alg )
5294     {
5295 #if defined(MBEDTLS_PSA_BUILTIN_ALG_ECDH)
5296         case PSA_ALG_ECDH:
5297             if( ! PSA_KEY_TYPE_IS_ECC_KEY_PAIR( private_key->attr.type ) )
5298                 return( PSA_ERROR_INVALID_ARGUMENT );
5299             mbedtls_ecp_keypair *ecp = NULL;
5300             psa_status_t status = mbedtls_psa_ecp_load_representation(
5301                                       private_key->attr.type,
5302                                       private_key->attr.bits,
5303                                       private_key->key.data,
5304                                       private_key->key.bytes,
5305                                       &ecp );
5306             if( status != PSA_SUCCESS )
5307                 return( status );
5308             status = psa_key_agreement_ecdh( peer_key, peer_key_length,
5309                                              ecp,
5310                                              shared_secret, shared_secret_size,
5311                                              shared_secret_length );
5312             mbedtls_ecp_keypair_free( ecp );
5313             mbedtls_free( ecp );
5314             return( status );
5315 #endif /* MBEDTLS_PSA_BUILTIN_ALG_ECDH */
5316         default:
5317             (void) private_key;
5318             (void) peer_key;
5319             (void) peer_key_length;
5320             (void) shared_secret;
5321             (void) shared_secret_size;
5322             (void) shared_secret_length;
5323             return( PSA_ERROR_NOT_SUPPORTED );
5324     }
5325 }
5326 
5327 /* Note that if this function fails, you must call psa_key_derivation_abort()
5328  * to potentially free embedded data structures and wipe confidential data.
5329  */
psa_key_agreement_internal(psa_key_derivation_operation_t * operation,psa_key_derivation_step_t step,psa_key_slot_t * private_key,const uint8_t * peer_key,size_t peer_key_length)5330 static psa_status_t psa_key_agreement_internal( psa_key_derivation_operation_t *operation,
5331                                                 psa_key_derivation_step_t step,
5332                                                 psa_key_slot_t *private_key,
5333                                                 const uint8_t *peer_key,
5334                                                 size_t peer_key_length )
5335 {
5336     psa_status_t status;
5337     uint8_t shared_secret[PSA_KEY_AGREEMENT_MAX_SHARED_SECRET_SIZE];
5338     size_t shared_secret_length = 0;
5339     psa_algorithm_t ka_alg = PSA_ALG_KEY_AGREEMENT_GET_BASE( operation->alg );
5340 
5341     /* Step 1: run the secret agreement algorithm to generate the shared
5342      * secret. */
5343     status = psa_key_agreement_raw_internal( ka_alg,
5344                                              private_key,
5345                                              peer_key, peer_key_length,
5346                                              shared_secret,
5347                                              sizeof( shared_secret ),
5348                                              &shared_secret_length );
5349     if( status != PSA_SUCCESS )
5350         goto exit;
5351 
5352     /* Step 2: set up the key derivation to generate key material from
5353      * the shared secret. A shared secret is permitted wherever a key
5354      * of type DERIVE is permitted. */
5355     status = psa_key_derivation_input_internal( operation, step,
5356                                                 PSA_KEY_TYPE_DERIVE,
5357                                                 shared_secret,
5358                                                 shared_secret_length );
5359 exit:
5360     mbedtls_platform_zeroize( shared_secret, shared_secret_length );
5361     return( status );
5362 }
5363 
psa_key_derivation_key_agreement(psa_key_derivation_operation_t * operation,psa_key_derivation_step_t step,mbedtls_svc_key_id_t private_key,const uint8_t * peer_key,size_t peer_key_length)5364 psa_status_t psa_key_derivation_key_agreement( psa_key_derivation_operation_t *operation,
5365                                                psa_key_derivation_step_t step,
5366                                                mbedtls_svc_key_id_t private_key,
5367                                                const uint8_t *peer_key,
5368                                                size_t peer_key_length )
5369 {
5370     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
5371     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
5372     psa_key_slot_t *slot;
5373 
5374     if( ! PSA_ALG_IS_KEY_AGREEMENT( operation->alg ) )
5375         return( PSA_ERROR_INVALID_ARGUMENT );
5376     status = psa_get_and_lock_transparent_key_slot_with_policy(
5377                  private_key, &slot, PSA_KEY_USAGE_DERIVE, operation->alg );
5378     if( status != PSA_SUCCESS )
5379         return( status );
5380     status = psa_key_agreement_internal( operation, step,
5381                                          slot,
5382                                          peer_key, peer_key_length );
5383     if( status != PSA_SUCCESS )
5384         psa_key_derivation_abort( operation );
5385     else
5386     {
5387         /* If a private key has been added as SECRET, we allow the derived
5388          * key material to be used as a key in PSA Crypto. */
5389         if( step == PSA_KEY_DERIVATION_INPUT_SECRET )
5390             operation->can_output_key = 1;
5391     }
5392 
5393     unlock_status = psa_unlock_key_slot( slot );
5394 
5395     return( ( status == PSA_SUCCESS ) ? unlock_status : status );
5396 }
5397 
psa_raw_key_agreement(psa_algorithm_t alg,mbedtls_svc_key_id_t private_key,const uint8_t * peer_key,size_t peer_key_length,uint8_t * output,size_t output_size,size_t * output_length)5398 psa_status_t psa_raw_key_agreement( psa_algorithm_t alg,
5399                                     mbedtls_svc_key_id_t private_key,
5400                                     const uint8_t *peer_key,
5401                                     size_t peer_key_length,
5402                                     uint8_t *output,
5403                                     size_t output_size,
5404                                     size_t *output_length )
5405 {
5406     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
5407     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
5408     psa_key_slot_t *slot = NULL;
5409 
5410     if( ! PSA_ALG_IS_KEY_AGREEMENT( alg ) )
5411     {
5412         status = PSA_ERROR_INVALID_ARGUMENT;
5413         goto exit;
5414     }
5415     status = psa_get_and_lock_transparent_key_slot_with_policy(
5416                  private_key, &slot, PSA_KEY_USAGE_DERIVE, alg );
5417     if( status != PSA_SUCCESS )
5418         goto exit;
5419 
5420     status = psa_key_agreement_raw_internal( alg, slot,
5421                                              peer_key, peer_key_length,
5422                                              output, output_size,
5423                                              output_length );
5424 
5425 exit:
5426     if( status != PSA_SUCCESS )
5427     {
5428         /* If an error happens and is not handled properly, the output
5429          * may be used as a key to protect sensitive data. Arrange for such
5430          * a key to be random, which is likely to result in decryption or
5431          * verification errors. This is better than filling the buffer with
5432          * some constant data such as zeros, which would result in the data
5433          * being protected with a reproducible, easily knowable key.
5434          */
5435         psa_generate_random( output, output_size );
5436         *output_length = output_size;
5437     }
5438 
5439     unlock_status = psa_unlock_key_slot( slot );
5440 
5441     return( ( status == PSA_SUCCESS ) ? unlock_status : status );
5442 }
5443 
5444 
5445 
5446 /****************************************************************/
5447 /* Random generation */
5448 /****************************************************************/
5449 
5450 /** Initialize the PSA random generator.
5451  */
mbedtls_psa_random_init(mbedtls_psa_random_context_t * rng)5452 static void mbedtls_psa_random_init( mbedtls_psa_random_context_t *rng )
5453 {
5454 #if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
5455     memset( rng, 0, sizeof( *rng ) );
5456 #else /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
5457 
5458     /* Set default configuration if
5459      * mbedtls_psa_crypto_configure_entropy_sources() hasn't been called. */
5460     if( rng->entropy_init == NULL )
5461         rng->entropy_init = mbedtls_entropy_init;
5462     if( rng->entropy_free == NULL )
5463         rng->entropy_free = mbedtls_entropy_free;
5464 
5465     rng->entropy_init( &rng->entropy );
5466 #if defined(MBEDTLS_PSA_INJECT_ENTROPY) && \
5467     defined(MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES)
5468     /* The PSA entropy injection feature depends on using NV seed as an entropy
5469      * source. Add NV seed as an entropy source for PSA entropy injection. */
5470     mbedtls_entropy_add_source( &rng->entropy,
5471                                 mbedtls_nv_seed_poll, NULL,
5472                                 MBEDTLS_ENTROPY_BLOCK_SIZE,
5473                                 MBEDTLS_ENTROPY_SOURCE_STRONG );
5474 #endif
5475 
5476     mbedtls_psa_drbg_init( MBEDTLS_PSA_RANDOM_STATE );
5477 #endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
5478 }
5479 
5480 /** Deinitialize the PSA random generator.
5481  */
mbedtls_psa_random_free(mbedtls_psa_random_context_t * rng)5482 static void mbedtls_psa_random_free( mbedtls_psa_random_context_t *rng )
5483 {
5484 #if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
5485     memset( rng, 0, sizeof( *rng ) );
5486 #else /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
5487     mbedtls_psa_drbg_free( MBEDTLS_PSA_RANDOM_STATE );
5488     rng->entropy_free( &rng->entropy );
5489 #endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
5490 }
5491 
5492 /** Seed the PSA random generator.
5493  */
mbedtls_psa_random_seed(mbedtls_psa_random_context_t * rng)5494 static psa_status_t mbedtls_psa_random_seed( mbedtls_psa_random_context_t *rng )
5495 {
5496 #if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
5497     /* Do nothing: the external RNG seeds itself. */
5498     (void) rng;
5499     return( PSA_SUCCESS );
5500 #else /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
5501     const unsigned char drbg_seed[] = "PSA";
5502     int ret = mbedtls_psa_drbg_seed( &rng->entropy,
5503                                      drbg_seed, sizeof( drbg_seed ) - 1 );
5504     return mbedtls_to_psa_error( ret );
5505 #endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
5506 }
5507 
psa_generate_random(uint8_t * output,size_t output_size)5508 psa_status_t psa_generate_random( uint8_t *output,
5509                                   size_t output_size )
5510 {
5511     GUARD_MODULE_INITIALIZED;
5512 
5513 #if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
5514 
5515     size_t output_length = 0;
5516     psa_status_t status = mbedtls_psa_external_get_random( &global_data.rng,
5517                                                            output, output_size,
5518                                                            &output_length );
5519     if( status != PSA_SUCCESS )
5520         return( status );
5521     /* Breaking up a request into smaller chunks is currently not supported
5522      * for the extrernal RNG interface. */
5523     if( output_length != output_size )
5524         return( PSA_ERROR_INSUFFICIENT_ENTROPY );
5525     return( PSA_SUCCESS );
5526 
5527 #else /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
5528 
5529     while( output_size > 0 )
5530     {
5531         size_t request_size =
5532             ( output_size > MBEDTLS_PSA_RANDOM_MAX_REQUEST ?
5533               MBEDTLS_PSA_RANDOM_MAX_REQUEST :
5534               output_size );
5535         int ret = mbedtls_psa_get_random( MBEDTLS_PSA_RANDOM_STATE,
5536                                           output, request_size );
5537         if( ret != 0 )
5538             return( mbedtls_to_psa_error( ret ) );
5539         output_size -= request_size;
5540         output += request_size;
5541     }
5542     return( PSA_SUCCESS );
5543 #endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
5544 }
5545 
5546 /* Wrapper function allowing the classic API to use the PSA RNG.
5547  *
5548  * `mbedtls_psa_get_random(MBEDTLS_PSA_RANDOM_STATE, ...)` calls
5549  * `psa_generate_random(...)`. The state parameter is ignored since the
5550  * PSA API doesn't support passing an explicit state.
5551  *
5552  * In the non-external case, psa_generate_random() calls an
5553  * `mbedtls_xxx_drbg_random` function which has exactly the same signature
5554  * and semantics as mbedtls_psa_get_random(). As an optimization,
5555  * instead of doing this back-and-forth between the PSA API and the
5556  * classic API, psa_crypto_random_impl.h defines `mbedtls_psa_get_random`
5557  * as a constant function pointer to `mbedtls_xxx_drbg_random`.
5558  */
5559 #if defined (MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
mbedtls_psa_get_random(void * p_rng,unsigned char * output,size_t output_size)5560 int mbedtls_psa_get_random( void *p_rng,
5561                             unsigned char *output,
5562                             size_t output_size )
5563 {
5564     /* This function takes a pointer to the RNG state because that's what
5565      * classic mbedtls functions using an RNG expect. The PSA RNG manages
5566      * its own state internally and doesn't let the caller access that state.
5567      * So we just ignore the state parameter, and in practice we'll pass
5568      * NULL. */
5569     (void) p_rng;
5570     psa_status_t status = psa_generate_random( output, output_size );
5571     if( status == PSA_SUCCESS )
5572         return( 0 );
5573     else
5574         return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );
5575 }
5576 #endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
5577 
5578 #if defined(MBEDTLS_PSA_INJECT_ENTROPY)
5579 #include "entropy_poll.h"
5580 
mbedtls_psa_inject_entropy(const uint8_t * seed,size_t seed_size)5581 psa_status_t mbedtls_psa_inject_entropy( const uint8_t *seed,
5582                                          size_t seed_size )
5583 {
5584     if( global_data.initialized )
5585         return( PSA_ERROR_NOT_PERMITTED );
5586 
5587     if( ( ( seed_size < MBEDTLS_ENTROPY_MIN_PLATFORM ) ||
5588           ( seed_size < MBEDTLS_ENTROPY_BLOCK_SIZE ) ) ||
5589           ( seed_size > MBEDTLS_ENTROPY_MAX_SEED_SIZE ) )
5590             return( PSA_ERROR_INVALID_ARGUMENT );
5591 
5592     return( mbedtls_psa_storage_inject_entropy( seed, seed_size ) );
5593 }
5594 #endif /* MBEDTLS_PSA_INJECT_ENTROPY */
5595 
5596 /** Validate the key type and size for key generation
5597  *
5598  * \param  type  The key type
5599  * \param  bits  The number of bits of the key
5600  *
5601  * \retval #PSA_SUCCESS
5602  *         The key type and size are valid.
5603  * \retval #PSA_ERROR_INVALID_ARGUMENT
5604  *         The size in bits of the key is not valid.
5605  * \retval #PSA_ERROR_NOT_SUPPORTED
5606  *         The type and/or the size in bits of the key or the combination of
5607  *         the two is not supported.
5608  */
psa_validate_key_type_and_size_for_key_generation(psa_key_type_t type,size_t bits)5609 static psa_status_t psa_validate_key_type_and_size_for_key_generation(
5610     psa_key_type_t type, size_t bits )
5611 {
5612     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
5613 
5614     if( key_type_is_raw_bytes( type ) )
5615     {
5616         status = psa_validate_unstructured_key_bit_size( type, bits );
5617         if( status != PSA_SUCCESS )
5618             return( status );
5619     }
5620     else
5621 #if defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR)
5622     if( PSA_KEY_TYPE_IS_RSA( type ) && PSA_KEY_TYPE_IS_KEY_PAIR( type ) )
5623     {
5624         if( bits > PSA_VENDOR_RSA_MAX_KEY_BITS )
5625             return( PSA_ERROR_NOT_SUPPORTED );
5626 
5627         /* Accept only byte-aligned keys, for the same reasons as
5628          * in psa_import_rsa_key(). */
5629         if( bits % 8 != 0 )
5630             return( PSA_ERROR_NOT_SUPPORTED );
5631     }
5632     else
5633 #endif /* defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR) */
5634 
5635 #if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR)
5636     if( PSA_KEY_TYPE_IS_ECC( type ) && PSA_KEY_TYPE_IS_KEY_PAIR( type ) )
5637     {
5638         /* To avoid empty block, return successfully here. */
5639         return( PSA_SUCCESS );
5640     }
5641     else
5642 #endif /* defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR) */
5643     {
5644         return( PSA_ERROR_NOT_SUPPORTED );
5645     }
5646 
5647     return( PSA_SUCCESS );
5648 }
5649 
psa_generate_key_internal(const psa_key_attributes_t * attributes,uint8_t * key_buffer,size_t key_buffer_size,size_t * key_buffer_length)5650 psa_status_t psa_generate_key_internal(
5651     const psa_key_attributes_t *attributes,
5652     uint8_t *key_buffer, size_t key_buffer_size, size_t *key_buffer_length )
5653 {
5654     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
5655     psa_key_type_t type = attributes->core.type;
5656 
5657     if( ( attributes->domain_parameters == NULL ) &&
5658         ( attributes->domain_parameters_size != 0 ) )
5659         return( PSA_ERROR_INVALID_ARGUMENT );
5660 
5661     if( key_type_is_raw_bytes( type ) )
5662     {
5663         status = psa_generate_random( key_buffer, key_buffer_size );
5664         if( status != PSA_SUCCESS )
5665             return( status );
5666 
5667 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES)
5668         if( type == PSA_KEY_TYPE_DES )
5669             psa_des_set_key_parity( key_buffer, key_buffer_size );
5670 #endif /* MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES */
5671     }
5672     else
5673 
5674 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) && \
5675     defined(MBEDTLS_GENPRIME)
5676     if ( type == PSA_KEY_TYPE_RSA_KEY_PAIR )
5677     {
5678         return( mbedtls_psa_rsa_generate_key( attributes,
5679                                               key_buffer,
5680                                               key_buffer_size,
5681                                               key_buffer_length ) );
5682     }
5683     else
5684 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR)
5685         * defined(MBEDTLS_GENPRIME) */
5686 
5687 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR)
5688     if ( PSA_KEY_TYPE_IS_ECC( type ) && PSA_KEY_TYPE_IS_KEY_PAIR( type ) )
5689     {
5690         return( mbedtls_psa_ecp_generate_key( attributes,
5691                                               key_buffer,
5692                                               key_buffer_size,
5693                                               key_buffer_length ) );
5694     }
5695     else
5696 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) */
5697     {
5698         (void)key_buffer_length;
5699         return( PSA_ERROR_NOT_SUPPORTED );
5700     }
5701 
5702     return( PSA_SUCCESS );
5703 }
5704 
psa_generate_key(const psa_key_attributes_t * attributes,mbedtls_svc_key_id_t * key)5705 psa_status_t psa_generate_key( const psa_key_attributes_t *attributes,
5706                                mbedtls_svc_key_id_t *key )
5707 {
5708     psa_status_t status;
5709     psa_key_slot_t *slot = NULL;
5710     psa_se_drv_table_entry_t *driver = NULL;
5711     size_t key_buffer_size;
5712 
5713     *key = MBEDTLS_SVC_KEY_ID_INIT;
5714 
5715     /* Reject any attempt to create a zero-length key so that we don't
5716      * risk tripping up later, e.g. on a malloc(0) that returns NULL. */
5717     if( psa_get_key_bits( attributes ) == 0 )
5718         return( PSA_ERROR_INVALID_ARGUMENT );
5719 
5720     /* Reject any attempt to create a public key. */
5721     if( PSA_KEY_TYPE_IS_PUBLIC_KEY(attributes->core.type) )
5722         return( PSA_ERROR_INVALID_ARGUMENT );
5723 
5724     status = psa_start_key_creation( PSA_KEY_CREATION_GENERATE, attributes,
5725                                      &slot, &driver );
5726     if( status != PSA_SUCCESS )
5727         goto exit;
5728 
5729     /* In the case of a transparent key or an opaque key stored in local
5730      * storage ( thus not in the case of generating a key in a secure element
5731      * with storage ( MBEDTLS_PSA_CRYPTO_SE_C ) ),we have to allocate a
5732      * buffer to hold the generated key material. */
5733     if( slot->key.data == NULL )
5734     {
5735         if ( PSA_KEY_LIFETIME_GET_LOCATION( attributes->core.lifetime ) ==
5736              PSA_KEY_LOCATION_LOCAL_STORAGE )
5737         {
5738             status = psa_validate_key_type_and_size_for_key_generation(
5739                 attributes->core.type, attributes->core.bits );
5740             if( status != PSA_SUCCESS )
5741                 goto exit;
5742 
5743             key_buffer_size = PSA_EXPORT_KEY_OUTPUT_SIZE(
5744                                   attributes->core.type,
5745                                   attributes->core.bits );
5746         }
5747         else
5748         {
5749             status = psa_driver_wrapper_get_key_buffer_size(
5750                          attributes, &key_buffer_size );
5751             if( status != PSA_SUCCESS )
5752                 goto exit;
5753         }
5754 
5755         status = psa_allocate_buffer_to_slot( slot, key_buffer_size );
5756         if( status != PSA_SUCCESS )
5757             goto exit;
5758     }
5759 
5760     status = psa_driver_wrapper_generate_key( attributes,
5761         slot->key.data, slot->key.bytes, &slot->key.bytes );
5762 
5763     if( status != PSA_SUCCESS )
5764         psa_remove_key_data_from_memory( slot );
5765 
5766 exit:
5767     if( status == PSA_SUCCESS )
5768         status = psa_finish_key_creation( slot, driver, key );
5769     if( status != PSA_SUCCESS )
5770         psa_fail_key_creation( slot, driver );
5771 
5772     return( status );
5773 }
5774 
5775 /****************************************************************/
5776 /* Module setup */
5777 /****************************************************************/
5778 
5779 #if !defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
mbedtls_psa_crypto_configure_entropy_sources(void (* entropy_init)(mbedtls_entropy_context * ctx),void (* entropy_free)(mbedtls_entropy_context * ctx))5780 psa_status_t mbedtls_psa_crypto_configure_entropy_sources(
5781     void (* entropy_init )( mbedtls_entropy_context *ctx ),
5782     void (* entropy_free )( mbedtls_entropy_context *ctx ) )
5783 {
5784     if( global_data.rng_state != RNG_NOT_INITIALIZED )
5785         return( PSA_ERROR_BAD_STATE );
5786     global_data.rng.entropy_init = entropy_init;
5787     global_data.rng.entropy_free = entropy_free;
5788     return( PSA_SUCCESS );
5789 }
5790 #endif /* !defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG) */
5791 
mbedtls_psa_crypto_free(void)5792 void mbedtls_psa_crypto_free( void )
5793 {
5794     psa_wipe_all_key_slots( );
5795     if( global_data.rng_state != RNG_NOT_INITIALIZED )
5796     {
5797         mbedtls_psa_random_free( &global_data.rng );
5798     }
5799     /* Wipe all remaining data, including configuration.
5800      * In particular, this sets all state indicator to the value
5801      * indicating "uninitialized". */
5802     mbedtls_platform_zeroize( &global_data, sizeof( global_data ) );
5803 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
5804     /* Unregister all secure element drivers, so that we restart from
5805      * a pristine state. */
5806     psa_unregister_all_se_drivers( );
5807 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
5808 }
5809 
5810 #if defined(PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS)
5811 /** Recover a transaction that was interrupted by a power failure.
5812  *
5813  * This function is called during initialization, before psa_crypto_init()
5814  * returns. If this function returns a failure status, the initialization
5815  * fails.
5816  */
psa_crypto_recover_transaction(const psa_crypto_transaction_t * transaction)5817 static psa_status_t psa_crypto_recover_transaction(
5818     const psa_crypto_transaction_t *transaction )
5819 {
5820     switch( transaction->unknown.type )
5821     {
5822         case PSA_CRYPTO_TRANSACTION_CREATE_KEY:
5823         case PSA_CRYPTO_TRANSACTION_DESTROY_KEY:
5824             /* TODO - fall through to the failure case until this
5825              * is implemented.
5826              * https://github.com/ARMmbed/mbed-crypto/issues/218
5827              */
5828         default:
5829             /* We found an unsupported transaction in the storage.
5830              * We don't know what state the storage is in. Give up. */
5831             return( PSA_ERROR_DATA_INVALID );
5832     }
5833 }
5834 #endif /* PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS */
5835 
psa_crypto_init(void)5836 psa_status_t psa_crypto_init( void )
5837 {
5838     psa_status_t status;
5839 
5840     /* Double initialization is explicitly allowed. */
5841     if( global_data.initialized != 0 )
5842         return( PSA_SUCCESS );
5843 
5844     /* Initialize and seed the random generator. */
5845     mbedtls_psa_random_init( &global_data.rng );
5846     global_data.rng_state = RNG_INITIALIZED;
5847     status = mbedtls_psa_random_seed( &global_data.rng );
5848     if( status != PSA_SUCCESS )
5849         goto exit;
5850     global_data.rng_state = RNG_SEEDED;
5851 
5852     status = psa_initialize_key_slots( );
5853     if( status != PSA_SUCCESS )
5854         goto exit;
5855 
5856 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
5857     status = psa_init_all_se_drivers( );
5858     if( status != PSA_SUCCESS )
5859         goto exit;
5860 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
5861 
5862 #if defined(PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS)
5863     status = psa_crypto_load_transaction( );
5864     if( status == PSA_SUCCESS )
5865     {
5866         status = psa_crypto_recover_transaction( &psa_crypto_transaction );
5867         if( status != PSA_SUCCESS )
5868             goto exit;
5869         status = psa_crypto_stop_transaction( );
5870     }
5871     else if( status == PSA_ERROR_DOES_NOT_EXIST )
5872     {
5873         /* There's no transaction to complete. It's all good. */
5874         status = PSA_SUCCESS;
5875     }
5876 #endif /* PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS */
5877 
5878     /* All done. */
5879     global_data.initialized = 1;
5880 
5881 exit:
5882     if( status != PSA_SUCCESS )
5883         mbedtls_psa_crypto_free( );
5884     return( status );
5885 }
5886 
5887 #endif /* MBEDTLS_PSA_CRYPTO_C */
5888