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_service_integration.h"
30 #include "psa/crypto.h"
31 
32 #include "psa_crypto_core.h"
33 #include "psa_crypto_invasive.h"
34 #include "psa_crypto_driver_wrappers.h"
35 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
36 #include "psa_crypto_se.h"
37 #endif
38 #include "psa_crypto_slot_management.h"
39 /* Include internal declarations that are useful for implementing persistently
40  * stored keys. */
41 #include "psa_crypto_storage.h"
42 
43 #include <assert.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include "mbedtls/platform.h"
47 #if !defined(MBEDTLS_PLATFORM_C)
48 #define vdb_mbedtls_calloc calloc
49 #define vdb_mbedtls_free   free
50 #endif
51 
52 #include "mbedtls/arc4.h"
53 #include "mbedtls/asn1.h"
54 #include "mbedtls/asn1write.h"
55 #include "mbedtls/bignum.h"
56 #include "mbedtls/blowfish.h"
57 #include "mbedtls/camellia.h"
58 #include "mbedtls/chacha20.h"
59 #include "mbedtls/chachapoly.h"
60 #include "mbedtls/cipher.h"
61 #include "mbedtls/ccm.h"
62 #include "mbedtls/cmac.h"
63 #include "mbedtls/ctr_drbg.h"
64 #include "mbedtls/des.h"
65 #include "mbedtls/ecdh.h"
66 #include "mbedtls/ecp.h"
67 #include "mbedtls/entropy.h"
68 #include "mbedtls/error.h"
69 #include "mbedtls/gcm.h"
70 #include "mbedtls/md2.h"
71 #include "mbedtls/md4.h"
72 #include "mbedtls/md5.h"
73 #include "mbedtls/md.h"
74 #include "mbedtls/md_internal.h"
75 #include "mbedtls/pk.h"
76 #include "mbedtls/pk_internal.h"
77 #include "mbedtls/platform_util.h"
78 #include "mbedtls/error.h"
79 #include "mbedtls/ripemd160.h"
80 #include "mbedtls/rsa.h"
81 #include "mbedtls/sha1.h"
82 #include "mbedtls/sha256.h"
83 #include "mbedtls/sha512.h"
84 #include "mbedtls/xtea.h"
85 
86 #define ARRAY_LENGTH( array ) ( sizeof( array ) / sizeof( *( array ) ) )
87 
88 /* constant-time buffer comparison */
safer_memcmp(const uint8_t * a,const uint8_t * b,size_t n)89 static inline int safer_memcmp( const uint8_t *a, const uint8_t *b, size_t n )
90 {
91     size_t i;
92     unsigned char diff = 0;
93 
94     for( i = 0; i < n; i++ )
95         diff |= a[i] ^ b[i];
96 
97     return( diff );
98 }
99 
100 
101 
102 /****************************************************************/
103 /* Global data, support functions and library management */
104 /****************************************************************/
105 
key_type_is_raw_bytes(psa_key_type_t type)106 static int key_type_is_raw_bytes( psa_key_type_t type )
107 {
108     return( PSA_KEY_TYPE_IS_UNSTRUCTURED( type ) );
109 }
110 
111 /* Values for psa_global_data_t::rng_state */
112 #define RNG_NOT_INITIALIZED 0
113 #define RNG_INITIALIZED 1
114 #define RNG_SEEDED 2
115 
116 typedef struct
117 {
118     void (* entropy_init )( mbedtls_entropy_context *ctx );
119     void (* entropy_free )( mbedtls_entropy_context *ctx );
120     mbedtls_entropy_context entropy;
121     mbedtls_ctr_drbg_context ctr_drbg;
122     unsigned initialized : 1;
123     unsigned rng_state : 2;
124 } psa_global_data_t;
125 
126 static psa_global_data_t global_data;
127 
128 #define GUARD_MODULE_INITIALIZED        \
129     if( global_data.initialized == 0 )  \
130         return( PSA_ERROR_BAD_STATE );
131 
mbedtls_to_psa_error(int ret)132 psa_status_t mbedtls_to_psa_error( int ret )
133 {
134     /* If there's both a high-level code and low-level code, dispatch on
135      * the high-level code. */
136     switch( ret < -0x7f ? - ( -ret & 0x7f80 ) : ret )
137     {
138         case 0:
139             return( PSA_SUCCESS );
140 
141         case MBEDTLS_ERR_AES_INVALID_KEY_LENGTH:
142         case MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH:
143         case MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE:
144             return( PSA_ERROR_NOT_SUPPORTED );
145         case MBEDTLS_ERR_AES_HW_ACCEL_FAILED:
146             return( PSA_ERROR_HARDWARE_FAILURE );
147 
148         case MBEDTLS_ERR_ARC4_HW_ACCEL_FAILED:
149             return( PSA_ERROR_HARDWARE_FAILURE );
150 
151         case MBEDTLS_ERR_ASN1_OUT_OF_DATA:
152         case MBEDTLS_ERR_ASN1_UNEXPECTED_TAG:
153         case MBEDTLS_ERR_ASN1_INVALID_LENGTH:
154         case MBEDTLS_ERR_ASN1_LENGTH_MISMATCH:
155         case MBEDTLS_ERR_ASN1_INVALID_DATA:
156             return( PSA_ERROR_INVALID_ARGUMENT );
157         case MBEDTLS_ERR_ASN1_ALLOC_FAILED:
158             return( PSA_ERROR_INSUFFICIENT_MEMORY );
159         case MBEDTLS_ERR_ASN1_BUF_TOO_SMALL:
160             return( PSA_ERROR_BUFFER_TOO_SMALL );
161 
162 #if defined(MBEDTLS_ERR_BLOWFISH_BAD_INPUT_DATA)
163         case MBEDTLS_ERR_BLOWFISH_BAD_INPUT_DATA:
164 #elif defined(MBEDTLS_ERR_BLOWFISH_INVALID_KEY_LENGTH)
165         case MBEDTLS_ERR_BLOWFISH_INVALID_KEY_LENGTH:
166 #endif
167         case MBEDTLS_ERR_BLOWFISH_INVALID_INPUT_LENGTH:
168             return( PSA_ERROR_NOT_SUPPORTED );
169         case MBEDTLS_ERR_BLOWFISH_HW_ACCEL_FAILED:
170             return( PSA_ERROR_HARDWARE_FAILURE );
171 
172 #if defined(MBEDTLS_ERR_CAMELLIA_BAD_INPUT_DATA)
173         case MBEDTLS_ERR_CAMELLIA_BAD_INPUT_DATA:
174 #elif defined(MBEDTLS_ERR_CAMELLIA_INVALID_KEY_LENGTH)
175         case MBEDTLS_ERR_CAMELLIA_INVALID_KEY_LENGTH:
176 #endif
177         case MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH:
178             return( PSA_ERROR_NOT_SUPPORTED );
179         case MBEDTLS_ERR_CAMELLIA_HW_ACCEL_FAILED:
180             return( PSA_ERROR_HARDWARE_FAILURE );
181 
182         case MBEDTLS_ERR_CCM_BAD_INPUT:
183             return( PSA_ERROR_INVALID_ARGUMENT );
184         case MBEDTLS_ERR_CCM_AUTH_FAILED:
185             return( PSA_ERROR_INVALID_SIGNATURE );
186         case MBEDTLS_ERR_CCM_HW_ACCEL_FAILED:
187             return( PSA_ERROR_HARDWARE_FAILURE );
188 
189         case MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA:
190             return( PSA_ERROR_INVALID_ARGUMENT );
191 
192         case MBEDTLS_ERR_CHACHAPOLY_BAD_STATE:
193             return( PSA_ERROR_BAD_STATE );
194         case MBEDTLS_ERR_CHACHAPOLY_AUTH_FAILED:
195             return( PSA_ERROR_INVALID_SIGNATURE );
196 
197         case MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE:
198             return( PSA_ERROR_NOT_SUPPORTED );
199         case MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA:
200             return( PSA_ERROR_INVALID_ARGUMENT );
201         case MBEDTLS_ERR_CIPHER_ALLOC_FAILED:
202             return( PSA_ERROR_INSUFFICIENT_MEMORY );
203         case MBEDTLS_ERR_CIPHER_INVALID_PADDING:
204             return( PSA_ERROR_INVALID_PADDING );
205         case MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED:
206             return( PSA_ERROR_INVALID_ARGUMENT );
207         case MBEDTLS_ERR_CIPHER_AUTH_FAILED:
208             return( PSA_ERROR_INVALID_SIGNATURE );
209         case MBEDTLS_ERR_CIPHER_INVALID_CONTEXT:
210             return( PSA_ERROR_CORRUPTION_DETECTED );
211         case MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED:
212             return( PSA_ERROR_HARDWARE_FAILURE );
213 
214         case MBEDTLS_ERR_CMAC_HW_ACCEL_FAILED:
215             return( PSA_ERROR_HARDWARE_FAILURE );
216 
217         case MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED:
218             return( PSA_ERROR_INSUFFICIENT_ENTROPY );
219         case MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG:
220         case MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG:
221             return( PSA_ERROR_NOT_SUPPORTED );
222         case MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR:
223             return( PSA_ERROR_INSUFFICIENT_ENTROPY );
224 
225         case MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH:
226             return( PSA_ERROR_NOT_SUPPORTED );
227         case MBEDTLS_ERR_DES_HW_ACCEL_FAILED:
228             return( PSA_ERROR_HARDWARE_FAILURE );
229 
230         case MBEDTLS_ERR_ENTROPY_NO_SOURCES_DEFINED:
231         case MBEDTLS_ERR_ENTROPY_NO_STRONG_SOURCE:
232         case MBEDTLS_ERR_ENTROPY_SOURCE_FAILED:
233             return( PSA_ERROR_INSUFFICIENT_ENTROPY );
234 
235         case MBEDTLS_ERR_GCM_AUTH_FAILED:
236             return( PSA_ERROR_INVALID_SIGNATURE );
237         case MBEDTLS_ERR_GCM_BAD_INPUT:
238             return( PSA_ERROR_INVALID_ARGUMENT );
239         case MBEDTLS_ERR_GCM_HW_ACCEL_FAILED:
240             return( PSA_ERROR_HARDWARE_FAILURE );
241 
242         case MBEDTLS_ERR_MD2_HW_ACCEL_FAILED:
243         case MBEDTLS_ERR_MD4_HW_ACCEL_FAILED:
244         case MBEDTLS_ERR_MD5_HW_ACCEL_FAILED:
245             return( PSA_ERROR_HARDWARE_FAILURE );
246 
247         case MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE:
248             return( PSA_ERROR_NOT_SUPPORTED );
249         case MBEDTLS_ERR_MD_BAD_INPUT_DATA:
250             return( PSA_ERROR_INVALID_ARGUMENT );
251         case MBEDTLS_ERR_MD_ALLOC_FAILED:
252             return( PSA_ERROR_INSUFFICIENT_MEMORY );
253         case MBEDTLS_ERR_MD_FILE_IO_ERROR:
254             return( PSA_ERROR_STORAGE_FAILURE );
255         case MBEDTLS_ERR_MD_HW_ACCEL_FAILED:
256             return( PSA_ERROR_HARDWARE_FAILURE );
257 
258         case MBEDTLS_ERR_MPI_FILE_IO_ERROR:
259             return( PSA_ERROR_STORAGE_FAILURE );
260         case MBEDTLS_ERR_MPI_BAD_INPUT_DATA:
261             return( PSA_ERROR_INVALID_ARGUMENT );
262         case MBEDTLS_ERR_MPI_INVALID_CHARACTER:
263             return( PSA_ERROR_INVALID_ARGUMENT );
264         case MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL:
265             return( PSA_ERROR_BUFFER_TOO_SMALL );
266         case MBEDTLS_ERR_MPI_NEGATIVE_VALUE:
267             return( PSA_ERROR_INVALID_ARGUMENT );
268         case MBEDTLS_ERR_MPI_DIVISION_BY_ZERO:
269             return( PSA_ERROR_INVALID_ARGUMENT );
270         case MBEDTLS_ERR_MPI_NOT_ACCEPTABLE:
271             return( PSA_ERROR_INVALID_ARGUMENT );
272         case MBEDTLS_ERR_MPI_ALLOC_FAILED:
273             return( PSA_ERROR_INSUFFICIENT_MEMORY );
274 
275         case MBEDTLS_ERR_PK_ALLOC_FAILED:
276             return( PSA_ERROR_INSUFFICIENT_MEMORY );
277         case MBEDTLS_ERR_PK_TYPE_MISMATCH:
278         case MBEDTLS_ERR_PK_BAD_INPUT_DATA:
279             return( PSA_ERROR_INVALID_ARGUMENT );
280         case MBEDTLS_ERR_PK_FILE_IO_ERROR:
281             return( PSA_ERROR_STORAGE_FAILURE );
282         case MBEDTLS_ERR_PK_KEY_INVALID_VERSION:
283         case MBEDTLS_ERR_PK_KEY_INVALID_FORMAT:
284             return( PSA_ERROR_INVALID_ARGUMENT );
285         case MBEDTLS_ERR_PK_UNKNOWN_PK_ALG:
286             return( PSA_ERROR_NOT_SUPPORTED );
287         case MBEDTLS_ERR_PK_PASSWORD_REQUIRED:
288         case MBEDTLS_ERR_PK_PASSWORD_MISMATCH:
289             return( PSA_ERROR_NOT_PERMITTED );
290         case MBEDTLS_ERR_PK_INVALID_PUBKEY:
291             return( PSA_ERROR_INVALID_ARGUMENT );
292         case MBEDTLS_ERR_PK_INVALID_ALG:
293         case MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE:
294         case MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE:
295             return( PSA_ERROR_NOT_SUPPORTED );
296         case MBEDTLS_ERR_PK_SIG_LEN_MISMATCH:
297             return( PSA_ERROR_INVALID_SIGNATURE );
298         case MBEDTLS_ERR_PK_HW_ACCEL_FAILED:
299             return( PSA_ERROR_HARDWARE_FAILURE );
300 
301         case MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED:
302             return( PSA_ERROR_HARDWARE_FAILURE );
303         case MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED:
304             return( PSA_ERROR_NOT_SUPPORTED );
305 
306         case MBEDTLS_ERR_RIPEMD160_HW_ACCEL_FAILED:
307             return( PSA_ERROR_HARDWARE_FAILURE );
308 
309         case MBEDTLS_ERR_RSA_BAD_INPUT_DATA:
310             return( PSA_ERROR_INVALID_ARGUMENT );
311         case MBEDTLS_ERR_RSA_INVALID_PADDING:
312             return( PSA_ERROR_INVALID_PADDING );
313         case MBEDTLS_ERR_RSA_KEY_GEN_FAILED:
314             return( PSA_ERROR_HARDWARE_FAILURE );
315         case MBEDTLS_ERR_RSA_KEY_CHECK_FAILED:
316             return( PSA_ERROR_INVALID_ARGUMENT );
317         case MBEDTLS_ERR_RSA_PUBLIC_FAILED:
318         case MBEDTLS_ERR_RSA_PRIVATE_FAILED:
319             return( PSA_ERROR_CORRUPTION_DETECTED );
320         case MBEDTLS_ERR_RSA_VERIFY_FAILED:
321             return( PSA_ERROR_INVALID_SIGNATURE );
322         case MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE:
323             return( PSA_ERROR_BUFFER_TOO_SMALL );
324         case MBEDTLS_ERR_RSA_RNG_FAILED:
325             return( PSA_ERROR_INSUFFICIENT_MEMORY );
326         case MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION:
327             return( PSA_ERROR_NOT_SUPPORTED );
328         case MBEDTLS_ERR_RSA_HW_ACCEL_FAILED:
329             return( PSA_ERROR_HARDWARE_FAILURE );
330 
331         case MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED:
332         case MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED:
333         case MBEDTLS_ERR_SHA512_HW_ACCEL_FAILED:
334             return( PSA_ERROR_HARDWARE_FAILURE );
335 
336         case MBEDTLS_ERR_XTEA_INVALID_INPUT_LENGTH:
337             return( PSA_ERROR_INVALID_ARGUMENT );
338         case MBEDTLS_ERR_XTEA_HW_ACCEL_FAILED:
339             return( PSA_ERROR_HARDWARE_FAILURE );
340 
341         case MBEDTLS_ERR_ECP_BAD_INPUT_DATA:
342         case MBEDTLS_ERR_ECP_INVALID_KEY:
343             return( PSA_ERROR_INVALID_ARGUMENT );
344         case MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL:
345             return( PSA_ERROR_BUFFER_TOO_SMALL );
346         case MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE:
347             return( PSA_ERROR_NOT_SUPPORTED );
348         case MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH:
349         case MBEDTLS_ERR_ECP_VERIFY_FAILED:
350             return( PSA_ERROR_INVALID_SIGNATURE );
351         case MBEDTLS_ERR_ECP_ALLOC_FAILED:
352             return( PSA_ERROR_INSUFFICIENT_MEMORY );
353         case MBEDTLS_ERR_ECP_HW_ACCEL_FAILED:
354             return( PSA_ERROR_HARDWARE_FAILURE );
355         case MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED:
356             return( PSA_ERROR_CORRUPTION_DETECTED );
357 
358         default:
359             return( PSA_ERROR_GENERIC_ERROR );
360     }
361 }
362 
363 
364 
365 
366 /****************************************************************/
367 /* Key management */
368 /****************************************************************/
369 
370 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
psa_key_slot_is_external(const psa_key_slot_t * slot)371 static inline int psa_key_slot_is_external( const psa_key_slot_t *slot )
372 {
373     return( psa_key_lifetime_is_external( slot->attr.lifetime ) );
374 }
375 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
376 
377 /* For now the MBEDTLS_PSA_ACCEL_ guards are also used here since the
378  * current test driver in key_management.c is using this function
379  * when accelerators are used for ECC key pair and public key.
380  * Once that dependency is resolved these guards can be removed.
381  */
382 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) || \
383     defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY) || \
384     defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR) || \
385     defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_PUBLIC_KEY)
vdb_mbedtls_ecc_group_of_psa(psa_ecc_family_t curve,size_t byte_length)386 mbedtls_ecp_group_id vdb_mbedtls_ecc_group_of_psa( psa_ecc_family_t curve,
387                                                size_t byte_length )
388 {
389     switch( curve )
390     {
391         case PSA_ECC_FAMILY_SECP_R1:
392             switch( byte_length )
393             {
394                 case PSA_BITS_TO_BYTES( 192 ):
395                     return( MBEDTLS_ECP_DP_SECP192R1 );
396                 case PSA_BITS_TO_BYTES( 224 ):
397                     return( MBEDTLS_ECP_DP_SECP224R1 );
398                 case PSA_BITS_TO_BYTES( 256 ):
399                     return( MBEDTLS_ECP_DP_SECP256R1 );
400                 case PSA_BITS_TO_BYTES( 384 ):
401                     return( MBEDTLS_ECP_DP_SECP384R1 );
402                 case PSA_BITS_TO_BYTES( 521 ):
403                     return( MBEDTLS_ECP_DP_SECP521R1 );
404                 default:
405                     return( MBEDTLS_ECP_DP_NONE );
406             }
407             break;
408 
409         case PSA_ECC_FAMILY_BRAINPOOL_P_R1:
410             switch( byte_length )
411             {
412                 case PSA_BITS_TO_BYTES( 256 ):
413                     return( MBEDTLS_ECP_DP_BP256R1 );
414                 case PSA_BITS_TO_BYTES( 384 ):
415                     return( MBEDTLS_ECP_DP_BP384R1 );
416                 case PSA_BITS_TO_BYTES( 512 ):
417                     return( MBEDTLS_ECP_DP_BP512R1 );
418                 default:
419                     return( MBEDTLS_ECP_DP_NONE );
420             }
421             break;
422 
423         case PSA_ECC_FAMILY_MONTGOMERY:
424             switch( byte_length )
425             {
426                 case PSA_BITS_TO_BYTES( 255 ):
427                     return( MBEDTLS_ECP_DP_CURVE25519 );
428                 case PSA_BITS_TO_BYTES( 448 ):
429                     return( MBEDTLS_ECP_DP_CURVE448 );
430                 default:
431                     return( MBEDTLS_ECP_DP_NONE );
432             }
433             break;
434 
435         case PSA_ECC_FAMILY_SECP_K1:
436             switch( byte_length )
437             {
438                 case PSA_BITS_TO_BYTES( 192 ):
439                     return( MBEDTLS_ECP_DP_SECP192K1 );
440                 case PSA_BITS_TO_BYTES( 224 ):
441                     return( MBEDTLS_ECP_DP_SECP224K1 );
442                 case PSA_BITS_TO_BYTES( 256 ):
443                     return( MBEDTLS_ECP_DP_SECP256K1 );
444                 default:
445                     return( MBEDTLS_ECP_DP_NONE );
446             }
447             break;
448 
449         default:
450             return( MBEDTLS_ECP_DP_NONE );
451     }
452 }
453 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) ||
454         * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY) ||
455         * defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR) ||
456         * defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_PUBLIC_KEY) */
457 
validate_unstructured_key_bit_size(psa_key_type_t type,size_t bits)458 static psa_status_t validate_unstructured_key_bit_size( psa_key_type_t type,
459                                                         size_t bits )
460 {
461     /* Check that the bit size is acceptable for the key type */
462     switch( type )
463     {
464         case PSA_KEY_TYPE_RAW_DATA:
465         case PSA_KEY_TYPE_HMAC:
466         case PSA_KEY_TYPE_DERIVE:
467             break;
468 #if defined(MBEDTLS_AES_C)
469         case PSA_KEY_TYPE_AES:
470             if( bits != 128 && bits != 192 && bits != 256 )
471                 return( PSA_ERROR_INVALID_ARGUMENT );
472             break;
473 #endif
474 #if defined(MBEDTLS_CAMELLIA_C)
475         case PSA_KEY_TYPE_CAMELLIA:
476             if( bits != 128 && bits != 192 && bits != 256 )
477                 return( PSA_ERROR_INVALID_ARGUMENT );
478             break;
479 #endif
480 #if defined(MBEDTLS_DES_C)
481         case PSA_KEY_TYPE_DES:
482             if( bits != 64 && bits != 128 && bits != 192 )
483                 return( PSA_ERROR_INVALID_ARGUMENT );
484             break;
485 #endif
486 #if defined(MBEDTLS_ARC4_C)
487         case PSA_KEY_TYPE_ARC4:
488             if( bits < 8 || bits > 2048 )
489                 return( PSA_ERROR_INVALID_ARGUMENT );
490             break;
491 #endif
492 #if defined(MBEDTLS_CHACHA20_C)
493         case PSA_KEY_TYPE_CHACHA20:
494             if( bits != 256 )
495                 return( PSA_ERROR_INVALID_ARGUMENT );
496             break;
497 #endif
498         default:
499             return( PSA_ERROR_NOT_SUPPORTED );
500     }
501     if( bits % 8 != 0 )
502         return( PSA_ERROR_INVALID_ARGUMENT );
503 
504     return( PSA_SUCCESS );
505 }
506 
507 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT) || \
508     defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) || \
509     defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP) || \
510     defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS) || \
511     defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) || \
512     defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY)
513 
514 /* Mbed TLS doesn't support non-byte-aligned key sizes (i.e. key sizes
515  * that are not a multiple of 8) well. For example, there is only
516  * vdb_mbedtls_rsa_get_len(), which returns a number of bytes, and no
517  * way to return the exact bit size of a key.
518  * To keep things simple, reject non-byte-aligned key sizes. */
psa_check_rsa_key_byte_aligned(const mbedtls_rsa_context * rsa)519 static psa_status_t psa_check_rsa_key_byte_aligned(
520     const mbedtls_rsa_context *rsa )
521 {
522     mbedtls_mpi n;
523     psa_status_t status;
524     vdb_mbedtls_mpi_init( &n );
525     status = mbedtls_to_psa_error(
526         vdb_mbedtls_rsa_export( rsa, &n, NULL, NULL, NULL, NULL ) );
527     if( status == PSA_SUCCESS )
528     {
529         if( vdb_mbedtls_mpi_bitlen( &n ) % 8 != 0 )
530             status = PSA_ERROR_NOT_SUPPORTED;
531     }
532     vdb_mbedtls_mpi_free( &n );
533     return( status );
534 }
535 
536 /** Load the contents of a key buffer into an internal RSA representation
537  *
538  * \param[in] type          The type of key contained in \p data.
539  * \param[in] data          The buffer from which to load the representation.
540  * \param[in] data_length   The size in bytes of \p data.
541  * \param[out] p_rsa        Returns a pointer to an RSA context on success.
542  *                          The caller is responsible for freeing both the
543  *                          contents of the context and the context itself
544  *                          when done.
545  */
psa_load_rsa_representation(psa_key_type_t type,const uint8_t * data,size_t data_length,mbedtls_rsa_context ** p_rsa)546 static psa_status_t psa_load_rsa_representation( psa_key_type_t type,
547                                                  const uint8_t *data,
548                                                  size_t data_length,
549                                                  mbedtls_rsa_context **p_rsa )
550 {
551     psa_status_t status;
552     mbedtls_pk_context ctx;
553     size_t bits;
554     vdb_mbedtls_pk_init( &ctx );
555 
556     /* Parse the data. */
557     if( PSA_KEY_TYPE_IS_KEY_PAIR( type ) )
558         status = mbedtls_to_psa_error(
559             vdb_mbedtls_pk_parse_key( &ctx, data, data_length, NULL, 0 ) );
560     else
561         status = mbedtls_to_psa_error(
562             vdb_mbedtls_pk_parse_public_key( &ctx, data, data_length ) );
563     if( status != PSA_SUCCESS )
564         goto exit;
565 
566     /* We have something that the pkparse module recognizes. If it is a
567      * valid RSA key, store it. */
568     if( vdb_mbedtls_pk_get_type( &ctx ) != MBEDTLS_PK_RSA )
569     {
570         status = PSA_ERROR_INVALID_ARGUMENT;
571         goto exit;
572     }
573 
574     /* The size of an RSA key doesn't have to be a multiple of 8. Mbed TLS
575      * supports non-byte-aligned key sizes, but not well. For example,
576      * vdb_mbedtls_rsa_get_len() returns the key size in bytes, not in bits. */
577     bits = PSA_BYTES_TO_BITS( vdb_mbedtls_rsa_get_len( vdb_mbedtls_pk_rsa( ctx ) ) );
578     if( bits > PSA_VENDOR_RSA_MAX_KEY_BITS )
579     {
580         status = PSA_ERROR_NOT_SUPPORTED;
581         goto exit;
582     }
583     status = psa_check_rsa_key_byte_aligned( vdb_mbedtls_pk_rsa( ctx ) );
584     if( status != PSA_SUCCESS )
585         goto exit;
586 
587     /* Copy out the pointer to the RSA context, and reset the PK context
588      * such that pk_free doesn't free the RSA context we just grabbed. */
589     *p_rsa = vdb_mbedtls_pk_rsa( ctx );
590     ctx.pk_info = NULL;
591 
592 exit:
593     vdb_mbedtls_pk_free( &ctx );
594     return( status );
595 }
596 
597 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT) ||
598         * defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) ||
599         * defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP) ||
600         * defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS) ||
601         * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) ||
602         * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY) */
603 
604 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) || \
605     defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY)
606 
607 /** Export an RSA key to export representation
608  *
609  * \param[in] type          The type of key (public/private) to export
610  * \param[in] rsa           The internal RSA representation from which to export
611  * \param[out] data         The buffer to export to
612  * \param[in] data_size     The length of the buffer to export to
613  * \param[out] data_length  The amount of bytes written to \p data
614  */
psa_export_rsa_key(psa_key_type_t type,mbedtls_rsa_context * rsa,uint8_t * data,size_t data_size,size_t * data_length)615 static psa_status_t psa_export_rsa_key( psa_key_type_t type,
616                                         mbedtls_rsa_context *rsa,
617                                         uint8_t *data,
618                                         size_t data_size,
619                                         size_t *data_length )
620 {
621 #if defined(MBEDTLS_PK_WRITE_C)
622     int ret;
623     mbedtls_pk_context pk;
624     uint8_t *pos = data + data_size;
625 
626     vdb_mbedtls_pk_init( &pk );
627     pk.pk_info = &vdb_mbedtls_rsa_info;
628     pk.pk_ctx = rsa;
629 
630     /* PSA Crypto API defines the format of an RSA key as a DER-encoded
631      * representation of the non-encrypted PKCS#1 RSAPrivateKey for a
632      * private key and of the RFC3279 RSAPublicKey for a public key. */
633     if( PSA_KEY_TYPE_IS_KEY_PAIR( type ) )
634         ret = vdb_mbedtls_pk_write_key_der( &pk, data, data_size );
635     else
636         ret = vdb_mbedtls_pk_write_pubkey( &pos, data, &pk );
637 
638     if( ret < 0 )
639     {
640         /* Clean up in case pk_write failed halfway through. */
641         memset( data, 0, data_size );
642         return( mbedtls_to_psa_error( ret ) );
643     }
644 
645     /* The mbedtls_pk_xxx functions write to the end of the buffer.
646      * Move the data to the beginning and erase remaining data
647      * at the original location. */
648     if( 2 * (size_t) ret <= data_size )
649     {
650         memcpy( data, data + data_size - ret, ret );
651         memset( data + data_size - ret, 0, ret );
652     }
653     else if( (size_t) ret < data_size )
654     {
655         memmove( data, data + data_size - ret, ret );
656         memset( data + ret, 0, data_size - ret );
657     }
658 
659     *data_length = ret;
660     return( PSA_SUCCESS );
661 #else
662     (void) type;
663     (void) rsa;
664     (void) data;
665     (void) data_size;
666     (void) data_length;
667     return( PSA_ERROR_NOT_SUPPORTED );
668 #endif /* MBEDTLS_PK_WRITE_C */
669 }
670 
671 /** Import an RSA key from import representation to a slot
672  *
673  * \param[in,out] slot      The slot where to store the export representation to
674  * \param[in] data          The buffer containing the import representation
675  * \param[in] data_length   The amount of bytes in \p data
676  */
psa_import_rsa_key(psa_key_slot_t * slot,const uint8_t * data,size_t data_length)677 static psa_status_t psa_import_rsa_key( psa_key_slot_t *slot,
678                                         const uint8_t *data,
679                                         size_t data_length )
680 {
681     psa_status_t status;
682     uint8_t* output = NULL;
683     mbedtls_rsa_context *rsa = NULL;
684 
685     /* Parse input */
686     status = psa_load_rsa_representation( slot->attr.type,
687                                           data,
688                                           data_length,
689                                           &rsa );
690     if( status != PSA_SUCCESS )
691         goto exit;
692 
693     slot->attr.bits = (psa_key_bits_t) PSA_BYTES_TO_BITS(
694         vdb_mbedtls_rsa_get_len( rsa ) );
695 
696     /* Re-export the data to PSA export format, such that we can store export
697      * representation in the key slot. Export representation in case of RSA is
698      * the smallest representation that's allowed as input, so a straight-up
699      * allocation of the same size as the input buffer will be large enough. */
700     output = vdb_mbedtls_calloc( 1, data_length );
701     if( output == NULL )
702     {
703         status = PSA_ERROR_INSUFFICIENT_MEMORY;
704         goto exit;
705     }
706 
707     status = psa_export_rsa_key( slot->attr.type,
708                                  rsa,
709                                  output,
710                                  data_length,
711                                  &data_length);
712 exit:
713     /* Always free the RSA object */
714     vdb_mbedtls_rsa_free( rsa );
715     vdb_mbedtls_free( rsa );
716 
717     /* Free the allocated buffer only on error. */
718     if( status != PSA_SUCCESS )
719     {
720         vdb_mbedtls_free( output );
721         return( status );
722     }
723 
724     /* On success, store the allocated export-formatted key. */
725     slot->data.key.data = output;
726     slot->data.key.bytes = data_length;
727 
728     return( PSA_SUCCESS );
729 }
730 
731 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) ||
732         * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY) */
733 
734 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) || \
735     defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY) || \
736     defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
737     defined(MBEDTLS_PSA_BUILTIN_ALG_ECDH) || \
738     defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)
739 /** Load the contents of a key buffer into an internal ECP representation
740  *
741  * \param[in] type          The type of key contained in \p data.
742  * \param[in] data          The buffer from which to load the representation.
743  * \param[in] data_length   The size in bytes of \p data.
744  * \param[out] p_ecp        Returns a pointer to an ECP context on success.
745  *                          The caller is responsible for freeing both the
746  *                          contents of the context and the context itself
747  *                          when done.
748  */
psa_load_ecp_representation(psa_key_type_t type,const uint8_t * data,size_t data_length,mbedtls_ecp_keypair ** p_ecp)749 static psa_status_t psa_load_ecp_representation( psa_key_type_t type,
750                                                  const uint8_t *data,
751                                                  size_t data_length,
752                                                  mbedtls_ecp_keypair **p_ecp )
753 {
754     mbedtls_ecp_group_id grp_id = MBEDTLS_ECP_DP_NONE;
755     psa_status_t status;
756     mbedtls_ecp_keypair *ecp = NULL;
757     size_t curve_size = data_length;
758 
759     if( PSA_KEY_TYPE_IS_PUBLIC_KEY( type ) &&
760         PSA_KEY_TYPE_ECC_GET_FAMILY( type ) != PSA_ECC_FAMILY_MONTGOMERY )
761     {
762         /* A Weierstrass public key is represented as:
763          * - The byte 0x04;
764          * - `x_P` as a `ceiling(m/8)`-byte string, big-endian;
765          * - `y_P` as a `ceiling(m/8)`-byte string, big-endian.
766          * So its data length is 2m+1 where m is the curve size in bits.
767          */
768         if( ( data_length & 1 ) == 0 )
769             return( PSA_ERROR_INVALID_ARGUMENT );
770         curve_size = data_length / 2;
771 
772         /* Montgomery public keys are represented in compressed format, meaning
773          * their curve_size is equal to the amount of input. */
774 
775         /* Private keys are represented in uncompressed private random integer
776          * format, meaning their curve_size is equal to the amount of input. */
777     }
778 
779     /* Allocate and initialize a key representation. */
780     ecp = vdb_mbedtls_calloc( 1, sizeof( mbedtls_ecp_keypair ) );
781     if( ecp == NULL )
782         return( PSA_ERROR_INSUFFICIENT_MEMORY );
783     vdb_mbedtls_ecp_keypair_init( ecp );
784 
785     /* Load the group. */
786     grp_id = vdb_mbedtls_ecc_group_of_psa( PSA_KEY_TYPE_ECC_GET_FAMILY( type ),
787                                        curve_size );
788     if( grp_id == MBEDTLS_ECP_DP_NONE )
789     {
790         status = PSA_ERROR_INVALID_ARGUMENT;
791         goto exit;
792     }
793 
794     status = mbedtls_to_psa_error(
795                 vdb_mbedtls_ecp_group_load( &ecp->grp, grp_id ) );
796     if( status != PSA_SUCCESS )
797         goto exit;
798 
799     /* Load the key material. */
800     if( PSA_KEY_TYPE_IS_PUBLIC_KEY( type ) )
801     {
802         /* Load the public value. */
803         status = mbedtls_to_psa_error(
804             vdb_mbedtls_ecp_point_read_binary( &ecp->grp, &ecp->Q,
805                                            data,
806                                            data_length ) );
807         if( status != PSA_SUCCESS )
808             goto exit;
809 
810         /* Check that the point is on the curve. */
811         status = mbedtls_to_psa_error(
812             vdb_mbedtls_ecp_check_pubkey( &ecp->grp, &ecp->Q ) );
813         if( status != PSA_SUCCESS )
814             goto exit;
815     }
816     else
817     {
818         /* Load and validate the secret value. */
819         status = mbedtls_to_psa_error(
820             vdb_mbedtls_ecp_read_key( ecp->grp.id,
821                                   ecp,
822                                   data,
823                                   data_length ) );
824         if( status != PSA_SUCCESS )
825             goto exit;
826     }
827 
828     *p_ecp = ecp;
829 exit:
830     if( status != PSA_SUCCESS )
831     {
832         vdb_mbedtls_ecp_keypair_free( ecp );
833         vdb_mbedtls_free( ecp );
834     }
835 
836     return( status );
837 }
838 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) ||
839         * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY) ||
840         * defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
841         * defined(MBEDTLS_PSA_BUILTIN_ALG_ECDH) ||
842         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) */
843 
844 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) || \
845     defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY)
846 /** Export an ECP key to export representation
847  *
848  * \param[in] type          The type of key (public/private) to export
849  * \param[in] ecp           The internal ECP representation from which to export
850  * \param[out] data         The buffer to export to
851  * \param[in] data_size     The length of the buffer to export to
852  * \param[out] data_length  The amount of bytes written to \p data
853  */
psa_export_ecp_key(psa_key_type_t type,mbedtls_ecp_keypair * ecp,uint8_t * data,size_t data_size,size_t * data_length)854 static psa_status_t psa_export_ecp_key( psa_key_type_t type,
855                                         mbedtls_ecp_keypair *ecp,
856                                         uint8_t *data,
857                                         size_t data_size,
858                                         size_t *data_length )
859 {
860     psa_status_t status;
861 
862     if( PSA_KEY_TYPE_IS_PUBLIC_KEY( type ) )
863     {
864         /* Check whether the public part is loaded */
865         if( vdb_mbedtls_ecp_is_zero( &ecp->Q ) )
866         {
867             /* Calculate the public key */
868             status = mbedtls_to_psa_error(
869                 vdb_mbedtls_ecp_mul( &ecp->grp, &ecp->Q, &ecp->d, &ecp->grp.G,
870                                  vdb_mbedtls_ctr_drbg_random, &global_data.ctr_drbg ) );
871             if( status != PSA_SUCCESS )
872                 return( status );
873         }
874 
875         status = mbedtls_to_psa_error(
876                     vdb_mbedtls_ecp_point_write_binary( &ecp->grp, &ecp->Q,
877                                                     MBEDTLS_ECP_PF_UNCOMPRESSED,
878                                                     data_length,
879                                                     data,
880                                                     data_size ) );
881         if( status != PSA_SUCCESS )
882             memset( data, 0, data_size );
883 
884         return( status );
885     }
886     else
887     {
888         if( data_size < PSA_BITS_TO_BYTES( ecp->grp.nbits ) )
889             return( PSA_ERROR_BUFFER_TOO_SMALL );
890 
891         status = mbedtls_to_psa_error(
892                     vdb_mbedtls_ecp_write_key( ecp,
893                                            data,
894                                            PSA_BITS_TO_BYTES( ecp->grp.nbits ) ) );
895         if( status == PSA_SUCCESS )
896             *data_length = PSA_BITS_TO_BYTES( ecp->grp.nbits );
897         else
898             memset( data, 0, data_size );
899 
900         return( status );
901     }
902 }
903 
904 /** Import an ECP key from import representation to a slot
905  *
906  * \param[in,out] slot      The slot where to store the export representation to
907  * \param[in] data          The buffer containing the import representation
908  * \param[in] data_length   The amount of bytes in \p data
909  */
psa_import_ecp_key(psa_key_slot_t * slot,const uint8_t * data,size_t data_length)910 static psa_status_t psa_import_ecp_key( psa_key_slot_t *slot,
911                                         const uint8_t *data,
912                                         size_t data_length )
913 {
914     psa_status_t status;
915     uint8_t* output = NULL;
916     mbedtls_ecp_keypair *ecp = NULL;
917 
918     /* Parse input */
919     status = psa_load_ecp_representation( slot->attr.type,
920                                           data,
921                                           data_length,
922                                           &ecp );
923     if( status != PSA_SUCCESS )
924         goto exit;
925 
926     if( PSA_KEY_TYPE_ECC_GET_FAMILY( slot->attr.type ) == PSA_ECC_FAMILY_MONTGOMERY)
927         slot->attr.bits = (psa_key_bits_t) ecp->grp.nbits + 1;
928     else
929         slot->attr.bits = (psa_key_bits_t) ecp->grp.nbits;
930 
931     /* Re-export the data to PSA export format. There is currently no support
932      * for other input formats then the export format, so this is a 1-1
933      * copy operation. */
934     output = vdb_mbedtls_calloc( 1, data_length );
935     if( output == NULL )
936     {
937         status = PSA_ERROR_INSUFFICIENT_MEMORY;
938         goto exit;
939     }
940 
941     status = psa_export_ecp_key( slot->attr.type,
942                                  ecp,
943                                  output,
944                                  data_length,
945                                  &data_length);
946 exit:
947     /* Always free the PK object (will also free contained ECP context) */
948     vdb_mbedtls_ecp_keypair_free( ecp );
949     vdb_mbedtls_free( ecp );
950 
951     /* Free the allocated buffer only on error. */
952     if( status != PSA_SUCCESS )
953     {
954         vdb_mbedtls_free( output );
955         return( status );
956     }
957 
958     /* On success, store the allocated export-formatted key. */
959     slot->data.key.data = output;
960     slot->data.key.bytes = data_length;
961 
962     return( PSA_SUCCESS );
963 }
964 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) ||
965         * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY) */
966 
967 /** Return the size of the key in the given slot, in bits.
968  *
969  * \param[in] slot      A key slot.
970  *
971  * \return The key size in bits, read from the metadata in the slot.
972  */
psa_get_key_slot_bits(const psa_key_slot_t * slot)973 static inline size_t psa_get_key_slot_bits( const psa_key_slot_t *slot )
974 {
975     return( slot->attr.bits );
976 }
977 
978 /** Try to allocate a buffer to an empty key slot.
979  *
980  * \param[in,out] slot          Key slot to attach buffer to.
981  * \param[in] buffer_length     Requested size of the buffer.
982  *
983  * \retval #PSA_SUCCESS
984  *         The buffer has been successfully allocated.
985  * \retval #PSA_ERROR_INSUFFICIENT_MEMORY
986  *         Not enough memory was available for allocation.
987  * \retval #PSA_ERROR_ALREADY_EXISTS
988  *         Trying to allocate a buffer to a non-empty key slot.
989  */
psa_allocate_buffer_to_slot(psa_key_slot_t * slot,size_t buffer_length)990 static psa_status_t psa_allocate_buffer_to_slot( psa_key_slot_t *slot,
991                                                  size_t buffer_length )
992 {
993     if( slot->data.key.data != NULL )
994         return( PSA_ERROR_ALREADY_EXISTS );
995 
996     slot->data.key.data = vdb_mbedtls_calloc( 1, buffer_length );
997     if( slot->data.key.data == NULL )
998         return( PSA_ERROR_INSUFFICIENT_MEMORY );
999 
1000     slot->data.key.bytes = buffer_length;
1001     return( PSA_SUCCESS );
1002 }
1003 
psa_copy_key_material_into_slot(psa_key_slot_t * slot,const uint8_t * data,size_t data_length)1004 psa_status_t psa_copy_key_material_into_slot( psa_key_slot_t *slot,
1005                                               const uint8_t* data,
1006                                               size_t data_length )
1007 {
1008     psa_status_t status = psa_allocate_buffer_to_slot( slot,
1009                                                        data_length );
1010     if( status != PSA_SUCCESS )
1011         return( status );
1012 
1013     memcpy( slot->data.key.data, data, data_length );
1014     return( PSA_SUCCESS );
1015 }
1016 
1017 /** Import key data into a slot.
1018  *
1019  * `slot->type` must have been set previously.
1020  * This function assumes that the slot does not contain any key material yet.
1021  * On failure, the slot content is unchanged.
1022  *
1023  * Persistent storage is not affected.
1024  *
1025  * \param[in,out] slot  The key slot to import data into.
1026  *                      Its `type` field must have previously been set to
1027  *                      the desired key type.
1028  *                      It must not contain any key material yet.
1029  * \param[in] data      Buffer containing the key material to parse and import.
1030  * \param data_length   Size of \p data in bytes.
1031  *
1032  * \retval #PSA_SUCCESS
1033  * \retval #PSA_ERROR_INVALID_ARGUMENT
1034  * \retval #PSA_ERROR_NOT_SUPPORTED
1035  * \retval #PSA_ERROR_INSUFFICIENT_MEMORY
1036  */
psa_import_key_into_slot(psa_key_slot_t * slot,const uint8_t * data,size_t data_length)1037 static psa_status_t psa_import_key_into_slot( psa_key_slot_t *slot,
1038                                               const uint8_t *data,
1039                                               size_t data_length )
1040 {
1041     psa_status_t status = PSA_SUCCESS;
1042     size_t bit_size;
1043 
1044     /* zero-length keys are never supported. */
1045     if( data_length == 0 )
1046         return( PSA_ERROR_NOT_SUPPORTED );
1047 
1048     if( key_type_is_raw_bytes( slot->attr.type ) )
1049     {
1050         bit_size = PSA_BYTES_TO_BITS( data_length );
1051 
1052         /* Ensure that the bytes-to-bits conversion hasn't overflown. */
1053         if( data_length > SIZE_MAX / 8 )
1054             return( PSA_ERROR_NOT_SUPPORTED );
1055 
1056         /* Enforce a size limit, and in particular ensure that the bit
1057          * size fits in its representation type. */
1058         if( bit_size > PSA_MAX_KEY_BITS )
1059             return( PSA_ERROR_NOT_SUPPORTED );
1060 
1061         status = validate_unstructured_key_bit_size( slot->attr.type, bit_size );
1062         if( status != PSA_SUCCESS )
1063             return( status );
1064 
1065         /* Allocate memory for the key */
1066         status = psa_copy_key_material_into_slot( slot, data, data_length );
1067         if( status != PSA_SUCCESS )
1068             return( status );
1069 
1070         /* Write the actual key size to the slot.
1071          * psa_start_key_creation() wrote the size declared by the
1072          * caller, which may be 0 (meaning unspecified) or wrong. */
1073         slot->attr.bits = (psa_key_bits_t) bit_size;
1074 
1075         return( PSA_SUCCESS );
1076     }
1077     else if( PSA_KEY_TYPE_IS_ASYMMETRIC( slot->attr.type ) )
1078     {
1079         /* Try validation through accelerators first. */
1080         bit_size = slot->attr.bits;
1081         psa_key_attributes_t attributes = {
1082           .core = slot->attr
1083         };
1084         status = psa_driver_wrapper_validate_key( &attributes,
1085                                                   data,
1086                                                   data_length,
1087                                                   &bit_size );
1088         if( status == PSA_SUCCESS )
1089         {
1090             /* Key has been validated successfully by an accelerator.
1091              * Copy key material into slot. */
1092             status = psa_copy_key_material_into_slot( slot, data, data_length );
1093             if( status != PSA_SUCCESS )
1094                 return( status );
1095 
1096             slot->attr.bits = (psa_key_bits_t) bit_size;
1097             return( PSA_SUCCESS );
1098         }
1099         else if( status != PSA_ERROR_NOT_SUPPORTED )
1100             return( status );
1101 
1102         /* Key format is not supported by any accelerator, try software fallback
1103          * if present. */
1104 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) || \
1105     defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY)
1106         if( PSA_KEY_TYPE_IS_ECC( slot->attr.type ) )
1107         {
1108             return( psa_import_ecp_key( slot, data, data_length ) );
1109         }
1110 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) ||
1111         * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY) */
1112 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) || \
1113     defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY)
1114         if( PSA_KEY_TYPE_IS_RSA( slot->attr.type ) )
1115         {
1116             return( psa_import_rsa_key( slot, data, data_length ) );
1117         }
1118 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) ||
1119         * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY) */
1120 
1121         /* Fell through the fallback as well, so have nothing else to try. */
1122         return( PSA_ERROR_NOT_SUPPORTED );
1123     }
1124     else
1125     {
1126         /* Unknown key type */
1127         return( PSA_ERROR_NOT_SUPPORTED );
1128     }
1129 }
1130 
1131 /** Calculate the intersection of two algorithm usage policies.
1132  *
1133  * Return 0 (which allows no operation) on incompatibility.
1134  */
psa_key_policy_algorithm_intersection(psa_algorithm_t alg1,psa_algorithm_t alg2)1135 static psa_algorithm_t psa_key_policy_algorithm_intersection(
1136     psa_algorithm_t alg1,
1137     psa_algorithm_t alg2 )
1138 {
1139     /* Common case: both sides actually specify the same policy. */
1140     if( alg1 == alg2 )
1141         return( alg1 );
1142     /* If the policies are from the same hash-and-sign family, check
1143      * if one is a wildcard. If so the other has the specific algorithm. */
1144     if( PSA_ALG_IS_HASH_AND_SIGN( alg1 ) &&
1145         PSA_ALG_IS_HASH_AND_SIGN( alg2 ) &&
1146         ( alg1 & ~PSA_ALG_HASH_MASK ) == ( alg2 & ~PSA_ALG_HASH_MASK ) )
1147     {
1148         if( PSA_ALG_SIGN_GET_HASH( alg1 ) == PSA_ALG_ANY_HASH )
1149             return( alg2 );
1150         if( PSA_ALG_SIGN_GET_HASH( alg2 ) == PSA_ALG_ANY_HASH )
1151             return( alg1 );
1152     }
1153     /* If the policies are incompatible, allow nothing. */
1154     return( 0 );
1155 }
1156 
psa_key_algorithm_permits(psa_algorithm_t policy_alg,psa_algorithm_t requested_alg)1157 static int psa_key_algorithm_permits( psa_algorithm_t policy_alg,
1158                                       psa_algorithm_t requested_alg )
1159 {
1160     /* Common case: the policy only allows requested_alg. */
1161     if( requested_alg == policy_alg )
1162         return( 1 );
1163     /* If policy_alg is a hash-and-sign with a wildcard for the hash,
1164      * and requested_alg is the same hash-and-sign family with any hash,
1165      * then requested_alg is compliant with policy_alg. */
1166     if( PSA_ALG_IS_HASH_AND_SIGN( requested_alg ) &&
1167         PSA_ALG_SIGN_GET_HASH( policy_alg ) == PSA_ALG_ANY_HASH )
1168     {
1169         return( ( policy_alg & ~PSA_ALG_HASH_MASK ) ==
1170                 ( requested_alg & ~PSA_ALG_HASH_MASK ) );
1171     }
1172     /* If policy_alg is a generic key agreement operation, then using it for
1173      * a key derivation with that key agreement should also be allowed. This
1174      * behaviour is expected to be defined in a future specification version. */
1175     if( PSA_ALG_IS_RAW_KEY_AGREEMENT( policy_alg ) &&
1176         PSA_ALG_IS_KEY_AGREEMENT( requested_alg ) )
1177     {
1178         return( PSA_ALG_KEY_AGREEMENT_GET_BASE( requested_alg ) ==
1179                 policy_alg );
1180     }
1181     /* If it isn't permitted, it's forbidden. */
1182     return( 0 );
1183 }
1184 
1185 /** Test whether a policy permits an algorithm.
1186  *
1187  * The caller must test usage flags separately.
1188  */
psa_key_policy_permits(const psa_key_policy_t * policy,psa_algorithm_t alg)1189 static int psa_key_policy_permits( const psa_key_policy_t *policy,
1190                                    psa_algorithm_t alg )
1191 {
1192     return( psa_key_algorithm_permits( policy->alg, alg ) ||
1193             psa_key_algorithm_permits( policy->alg2, alg ) );
1194 }
1195 
1196 /** Restrict a key policy based on a constraint.
1197  *
1198  * \param[in,out] policy    The policy to restrict.
1199  * \param[in] constraint    The policy constraint to apply.
1200  *
1201  * \retval #PSA_SUCCESS
1202  *         \c *policy contains the intersection of the original value of
1203  *         \c *policy and \c *constraint.
1204  * \retval #PSA_ERROR_INVALID_ARGUMENT
1205  *         \c *policy and \c *constraint are incompatible.
1206  *         \c *policy is unchanged.
1207  */
psa_restrict_key_policy(psa_key_policy_t * policy,const psa_key_policy_t * constraint)1208 static psa_status_t psa_restrict_key_policy(
1209     psa_key_policy_t *policy,
1210     const psa_key_policy_t *constraint )
1211 {
1212     psa_algorithm_t intersection_alg =
1213         psa_key_policy_algorithm_intersection( policy->alg, constraint->alg );
1214     psa_algorithm_t intersection_alg2 =
1215         psa_key_policy_algorithm_intersection( policy->alg2, constraint->alg2 );
1216     if( intersection_alg == 0 && policy->alg != 0 && constraint->alg != 0 )
1217         return( PSA_ERROR_INVALID_ARGUMENT );
1218     if( intersection_alg2 == 0 && policy->alg2 != 0 && constraint->alg2 != 0 )
1219         return( PSA_ERROR_INVALID_ARGUMENT );
1220     policy->usage &= constraint->usage;
1221     policy->alg = intersection_alg;
1222     policy->alg2 = intersection_alg2;
1223     return( PSA_SUCCESS );
1224 }
1225 
1226 /** Get the description of a key given its identifier and policy constraints
1227  *  and lock it.
1228  *
1229  * The key must have allow all the usage flags set in \p usage. If \p alg is
1230  * nonzero, the key must allow operations with this algorithm.
1231  *
1232  * In case of a persistent key, the function loads the description of the key
1233  * into a key slot if not already done.
1234  *
1235  * On success, the returned key slot is locked. It is the responsibility of
1236  * the caller to unlock the key slot when it does not access it anymore.
1237  */
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)1238 static psa_status_t psa_get_and_lock_key_slot_with_policy(
1239     mbedtls_svc_key_id_t key,
1240     psa_key_slot_t **p_slot,
1241     psa_key_usage_t usage,
1242     psa_algorithm_t alg )
1243 {
1244     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
1245     psa_key_slot_t *slot;
1246 
1247     status = psa_get_and_lock_key_slot( key, p_slot );
1248     if( status != PSA_SUCCESS )
1249         return( status );
1250     slot = *p_slot;
1251 
1252     /* Enforce that usage policy for the key slot contains all the flags
1253      * required by the usage parameter. There is one exception: public
1254      * keys can always be exported, so we treat public key objects as
1255      * if they had the export flag. */
1256     if( PSA_KEY_TYPE_IS_PUBLIC_KEY( slot->attr.type ) )
1257         usage &= ~PSA_KEY_USAGE_EXPORT;
1258 
1259     status = PSA_ERROR_NOT_PERMITTED;
1260     if( ( slot->attr.policy.usage & usage ) != usage )
1261         goto error;
1262 
1263     /* Enforce that the usage policy permits the requested algortihm. */
1264     if( alg != 0 && ! psa_key_policy_permits( &slot->attr.policy, alg ) )
1265         goto error;
1266 
1267     return( PSA_SUCCESS );
1268 
1269 error:
1270     *p_slot = NULL;
1271     psa_unlock_key_slot( slot );
1272 
1273     return( status );
1274 }
1275 
1276 /** Get a key slot containing a transparent key and lock it.
1277  *
1278  * A transparent key is a key for which the key material is directly
1279  * available, as opposed to a key in a secure element.
1280  *
1281  * This is a temporary function to use instead of
1282  * psa_get_and_lock_key_slot_with_policy() until secure element support is
1283  * fully implemented.
1284  *
1285  * On success, the returned key slot is locked. It is the responsibility of the
1286  * caller to unlock the key slot when it does not access it anymore.
1287  */
1288 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
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)1289 static psa_status_t psa_get_and_lock_transparent_key_slot_with_policy(
1290     mbedtls_svc_key_id_t key,
1291     psa_key_slot_t **p_slot,
1292     psa_key_usage_t usage,
1293     psa_algorithm_t alg )
1294 {
1295     psa_status_t status = psa_get_and_lock_key_slot_with_policy( key, p_slot,
1296                                                                  usage, alg );
1297     if( status != PSA_SUCCESS )
1298         return( status );
1299 
1300     if( psa_key_slot_is_external( *p_slot ) )
1301     {
1302         psa_unlock_key_slot( *p_slot );
1303         *p_slot = NULL;
1304         return( PSA_ERROR_NOT_SUPPORTED );
1305     }
1306 
1307     return( PSA_SUCCESS );
1308 }
1309 #else /* MBEDTLS_PSA_CRYPTO_SE_C */
1310 /* With no secure element support, all keys are transparent. */
1311 #define psa_get_and_lock_transparent_key_slot_with_policy( key, p_slot, usage, alg )   \
1312     psa_get_and_lock_key_slot_with_policy( key, p_slot, usage, alg )
1313 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1314 
1315 /** Wipe key data from a slot. Preserve metadata such as the policy. */
psa_remove_key_data_from_memory(psa_key_slot_t * slot)1316 static psa_status_t psa_remove_key_data_from_memory( psa_key_slot_t *slot )
1317 {
1318 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1319     if( psa_key_slot_is_external( slot ) )
1320     {
1321         /* No key material to clean. */
1322     }
1323     else
1324 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1325     {
1326         /* Data pointer will always be either a valid pointer or NULL in an
1327          * initialized slot, so we can just free it. */
1328         if( slot->data.key.data != NULL )
1329             vdb_mbedtls_platform_zeroize( slot->data.key.data, slot->data.key.bytes);
1330         vdb_mbedtls_free( slot->data.key.data );
1331         slot->data.key.data = NULL;
1332         slot->data.key.bytes = 0;
1333     }
1334 
1335     return( PSA_SUCCESS );
1336 }
1337 
1338 /** Completely wipe a slot in memory, including its policy.
1339  * Persistent storage is not affected. */
psa_wipe_key_slot(psa_key_slot_t * slot)1340 psa_status_t psa_wipe_key_slot( psa_key_slot_t *slot )
1341 {
1342     psa_status_t status = psa_remove_key_data_from_memory( slot );
1343 
1344     /*
1345      * As the return error code may not be handled in case of multiple errors,
1346      * do our best to report an unexpected lock counter: if available
1347      * call MBEDTLS_PARAM_FAILED that may terminate execution (if called as
1348      * part of the execution of a test suite this will stop the test suite
1349      * execution).
1350      */
1351     if( slot->lock_count != 1 )
1352     {
1353 #ifdef MBEDTLS_CHECK_PARAMS
1354         MBEDTLS_PARAM_FAILED( slot->lock_count == 1 );
1355 #endif
1356         status = PSA_ERROR_CORRUPTION_DETECTED;
1357     }
1358 
1359     /* Multipart operations may still be using the key. This is safe
1360      * because all multipart operation objects are independent from
1361      * the key slot: if they need to access the key after the setup
1362      * phase, they have a copy of the key. Note that this means that
1363      * key material can linger until all operations are completed. */
1364     /* At this point, key material and other type-specific content has
1365      * been wiped. Clear remaining metadata. We can call memset and not
1366      * zeroize because the metadata is not particularly sensitive. */
1367     memset( slot, 0, sizeof( *slot ) );
1368     return( status );
1369 }
1370 
psa_destroy_key(mbedtls_svc_key_id_t key)1371 psa_status_t psa_destroy_key( mbedtls_svc_key_id_t key )
1372 {
1373     psa_key_slot_t *slot;
1374     psa_status_t status; /* status of the last operation */
1375     psa_status_t overall_status = PSA_SUCCESS;
1376 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1377     psa_se_drv_table_entry_t *driver;
1378 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1379 
1380     if( vdb_mbedtls_svc_key_id_is_null( key ) )
1381         return( PSA_SUCCESS );
1382 
1383     /*
1384      * Get the description of the key in a key slot. In case of a persistent
1385      * key, this will load the key description from persistent memory if not
1386      * done yet. We cannot avoid this loading as without it we don't know if
1387      * the key is operated by an SE or not and this information is needed by
1388      * the current implementation.
1389      */
1390     status = psa_get_and_lock_key_slot( key, &slot );
1391     if( status != PSA_SUCCESS )
1392         return( status );
1393 
1394     /*
1395      * If the key slot containing the key description is under access by the
1396      * library (apart from the present access), the key cannot be destroyed
1397      * yet. For the time being, just return in error. Eventually (to be
1398      * implemented), the key should be destroyed when all accesses have
1399      * stopped.
1400      */
1401     if( slot->lock_count > 1 )
1402     {
1403        psa_unlock_key_slot( slot );
1404        return( PSA_ERROR_GENERIC_ERROR );
1405     }
1406 
1407 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1408     driver = psa_get_se_driver_entry( slot->attr.lifetime );
1409     if( driver != NULL )
1410     {
1411         /* For a key in a secure element, we need to do three things:
1412          * remove the key file in internal storage, destroy the
1413          * key inside the secure element, and update the driver's
1414          * persistent data. Start a transaction that will encompass these
1415          * three actions. */
1416         psa_crypto_prepare_transaction( PSA_CRYPTO_TRANSACTION_DESTROY_KEY );
1417         psa_crypto_transaction.key.lifetime = slot->attr.lifetime;
1418         psa_crypto_transaction.key.slot = slot->data.se.slot_number;
1419         psa_crypto_transaction.key.id = slot->attr.id;
1420         status = psa_crypto_save_transaction( );
1421         if( status != PSA_SUCCESS )
1422         {
1423             (void) psa_crypto_stop_transaction( );
1424             /* We should still try to destroy the key in the secure
1425              * element and the key metadata in storage. This is especially
1426              * important if the error is that the storage is full.
1427              * But how to do it exactly without risking an inconsistent
1428              * state after a reset?
1429              * https://github.com/ARMmbed/mbed-crypto/issues/215
1430              */
1431             overall_status = status;
1432             goto exit;
1433         }
1434 
1435         status = psa_destroy_se_key( driver, slot->data.se.slot_number );
1436         if( overall_status == PSA_SUCCESS )
1437             overall_status = status;
1438     }
1439 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1440 
1441 #if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C)
1442     if( ! PSA_KEY_LIFETIME_IS_VOLATILE( slot->attr.lifetime ) )
1443     {
1444         status = psa_destroy_persistent_key( slot->attr.id );
1445         if( overall_status == PSA_SUCCESS )
1446             overall_status = status;
1447 
1448         /* TODO: other slots may have a copy of the same key. We should
1449          * invalidate them.
1450          * https://github.com/ARMmbed/mbed-crypto/issues/214
1451          */
1452     }
1453 #endif /* defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) */
1454 
1455 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1456     if( driver != NULL )
1457     {
1458         status = psa_save_se_persistent_data( driver );
1459         if( overall_status == PSA_SUCCESS )
1460             overall_status = status;
1461         status = psa_crypto_stop_transaction( );
1462         if( overall_status == PSA_SUCCESS )
1463             overall_status = status;
1464     }
1465 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1466 
1467 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1468 exit:
1469 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1470     status = psa_wipe_key_slot( slot );
1471     /* Prioritize CORRUPTION_DETECTED from wiping over a storage error */
1472     if( overall_status == PSA_SUCCESS )
1473         overall_status = status;
1474     return( overall_status );
1475 }
1476 
psa_reset_key_attributes(psa_key_attributes_t * attributes)1477 void psa_reset_key_attributes( psa_key_attributes_t *attributes )
1478 {
1479     vdb_mbedtls_free( attributes->domain_parameters );
1480     memset( attributes, 0, sizeof( *attributes ) );
1481 }
1482 
psa_set_key_domain_parameters(psa_key_attributes_t * attributes,psa_key_type_t type,const uint8_t * data,size_t data_length)1483 psa_status_t psa_set_key_domain_parameters( psa_key_attributes_t *attributes,
1484                                             psa_key_type_t type,
1485                                             const uint8_t *data,
1486                                             size_t data_length )
1487 {
1488     uint8_t *copy = NULL;
1489 
1490     if( data_length != 0 )
1491     {
1492         copy = vdb_mbedtls_calloc( 1, data_length );
1493         if( copy == NULL )
1494             return( PSA_ERROR_INSUFFICIENT_MEMORY );
1495         memcpy( copy, data, data_length );
1496     }
1497     /* After this point, this function is guaranteed to succeed, so it
1498      * can start modifying `*attributes`. */
1499 
1500     if( attributes->domain_parameters != NULL )
1501     {
1502         vdb_mbedtls_free( attributes->domain_parameters );
1503         attributes->domain_parameters = NULL;
1504         attributes->domain_parameters_size = 0;
1505     }
1506 
1507     attributes->domain_parameters = copy;
1508     attributes->domain_parameters_size = data_length;
1509     attributes->core.type = type;
1510     return( PSA_SUCCESS );
1511 }
1512 
psa_get_key_domain_parameters(const psa_key_attributes_t * attributes,uint8_t * data,size_t data_size,size_t * data_length)1513 psa_status_t psa_get_key_domain_parameters(
1514     const psa_key_attributes_t *attributes,
1515     uint8_t *data, size_t data_size, size_t *data_length )
1516 {
1517     if( attributes->domain_parameters_size > data_size )
1518         return( PSA_ERROR_BUFFER_TOO_SMALL );
1519     *data_length = attributes->domain_parameters_size;
1520     if( attributes->domain_parameters_size != 0 )
1521         memcpy( data, attributes->domain_parameters,
1522                 attributes->domain_parameters_size );
1523     return( PSA_SUCCESS );
1524 }
1525 
1526 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) || \
1527     defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY)
psa_get_rsa_public_exponent(const mbedtls_rsa_context * rsa,psa_key_attributes_t * attributes)1528 static psa_status_t psa_get_rsa_public_exponent(
1529     const mbedtls_rsa_context *rsa,
1530     psa_key_attributes_t *attributes )
1531 {
1532     mbedtls_mpi mpi;
1533     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1534     uint8_t *buffer = NULL;
1535     size_t buflen;
1536     vdb_mbedtls_mpi_init( &mpi );
1537 
1538     ret = vdb_mbedtls_rsa_export( rsa, NULL, NULL, NULL, NULL, &mpi );
1539     if( ret != 0 )
1540         goto exit;
1541     if( vdb_mbedtls_mpi_cmp_int( &mpi, 65537 ) == 0 )
1542     {
1543         /* It's the default value, which is reported as an empty string,
1544          * so there's nothing to do. */
1545         goto exit;
1546     }
1547 
1548     buflen = vdb_mbedtls_mpi_size( &mpi );
1549     buffer = vdb_mbedtls_calloc( 1, buflen );
1550     if( buffer == NULL )
1551     {
1552         ret = MBEDTLS_ERR_MPI_ALLOC_FAILED;
1553         goto exit;
1554     }
1555     ret = vdb_mbedtls_mpi_write_binary( &mpi, buffer, buflen );
1556     if( ret != 0 )
1557         goto exit;
1558     attributes->domain_parameters = buffer;
1559     attributes->domain_parameters_size = buflen;
1560 
1561 exit:
1562     vdb_mbedtls_mpi_free( &mpi );
1563     if( ret != 0 )
1564         vdb_mbedtls_free( buffer );
1565     return( mbedtls_to_psa_error( ret ) );
1566 }
1567 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) ||
1568         * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY) */
1569 
1570 /** Retrieve all the publicly-accessible attributes of a key.
1571  */
psa_get_key_attributes(mbedtls_svc_key_id_t key,psa_key_attributes_t * attributes)1572 psa_status_t psa_get_key_attributes( mbedtls_svc_key_id_t key,
1573                                      psa_key_attributes_t *attributes )
1574 {
1575     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
1576     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
1577     psa_key_slot_t *slot;
1578 
1579     psa_reset_key_attributes( attributes );
1580 
1581     status = psa_get_and_lock_key_slot_with_policy( key, &slot, 0, 0 );
1582     if( status != PSA_SUCCESS )
1583         return( status );
1584 
1585     attributes->core = slot->attr;
1586     attributes->core.flags &= ( MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY |
1587                                 MBEDTLS_PSA_KA_MASK_DUAL_USE );
1588 
1589 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1590     if( psa_key_slot_is_external( slot ) )
1591         psa_set_key_slot_number( attributes, slot->data.se.slot_number );
1592 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1593 
1594     switch( slot->attr.type )
1595     {
1596 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) || \
1597     defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY)
1598         case PSA_KEY_TYPE_RSA_KEY_PAIR:
1599         case PSA_KEY_TYPE_RSA_PUBLIC_KEY:
1600 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1601             /* TODO: reporting the public exponent for opaque keys
1602              * is not yet implemented.
1603              * https://github.com/ARMmbed/mbed-crypto/issues/216
1604              */
1605             if( psa_key_slot_is_external( slot ) )
1606                 break;
1607 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1608             {
1609                 mbedtls_rsa_context *rsa = NULL;
1610 
1611                 status = psa_load_rsa_representation( slot->attr.type,
1612                                                       slot->data.key.data,
1613                                                       slot->data.key.bytes,
1614                                                       &rsa );
1615                 if( status != PSA_SUCCESS )
1616                     break;
1617 
1618                 status = psa_get_rsa_public_exponent( rsa,
1619                                                       attributes );
1620                 vdb_mbedtls_rsa_free( rsa );
1621                 vdb_mbedtls_free( rsa );
1622             }
1623             break;
1624 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) ||
1625         * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY) */
1626         default:
1627             /* Nothing else to do. */
1628             break;
1629     }
1630 
1631     if( status != PSA_SUCCESS )
1632         psa_reset_key_attributes( attributes );
1633 
1634     unlock_status = psa_unlock_key_slot( slot );
1635 
1636     return( ( status == PSA_SUCCESS ) ? unlock_status : status );
1637 }
1638 
1639 #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)1640 psa_status_t psa_get_key_slot_number(
1641     const psa_key_attributes_t *attributes,
1642     psa_key_slot_number_t *slot_number )
1643 {
1644     if( attributes->core.flags & MBEDTLS_PSA_KA_FLAG_HAS_SLOT_NUMBER )
1645     {
1646         *slot_number = attributes->slot_number;
1647         return( PSA_SUCCESS );
1648     }
1649     else
1650         return( PSA_ERROR_INVALID_ARGUMENT );
1651 }
1652 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1653 
psa_internal_export_key_buffer(const psa_key_slot_t * slot,uint8_t * data,size_t data_size,size_t * data_length)1654 static psa_status_t psa_internal_export_key_buffer( const psa_key_slot_t *slot,
1655                                                     uint8_t *data,
1656                                                     size_t data_size,
1657                                                     size_t *data_length )
1658 {
1659     if( slot->data.key.bytes > data_size )
1660         return( PSA_ERROR_BUFFER_TOO_SMALL );
1661     memcpy( data, slot->data.key.data, slot->data.key.bytes );
1662     memset( data + slot->data.key.bytes, 0,
1663             data_size - slot->data.key.bytes );
1664     *data_length = slot->data.key.bytes;
1665     return( PSA_SUCCESS );
1666 }
1667 
psa_internal_export_key(const psa_key_slot_t * slot,uint8_t * data,size_t data_size,size_t * data_length,int export_public_key)1668 static psa_status_t psa_internal_export_key( const psa_key_slot_t *slot,
1669                                              uint8_t *data,
1670                                              size_t data_size,
1671                                              size_t *data_length,
1672                                              int export_public_key )
1673 {
1674 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1675     const psa_drv_se_t *drv;
1676     psa_drv_se_context_t *drv_context;
1677 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1678 
1679     *data_length = 0;
1680 
1681     if( export_public_key && ! PSA_KEY_TYPE_IS_ASYMMETRIC( slot->attr.type ) )
1682         return( PSA_ERROR_INVALID_ARGUMENT );
1683 
1684     /* Reject a zero-length output buffer now, since this can never be a
1685      * valid key representation. This way we know that data must be a valid
1686      * pointer and we can do things like memset(data, ..., data_size). */
1687     if( data_size == 0 )
1688         return( PSA_ERROR_BUFFER_TOO_SMALL );
1689 
1690 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1691     if( psa_get_se_driver( slot->attr.lifetime, &drv, &drv_context ) )
1692     {
1693         psa_drv_se_export_key_t method;
1694         if( drv->key_management == NULL )
1695             return( PSA_ERROR_NOT_SUPPORTED );
1696         method = ( export_public_key ?
1697                    drv->key_management->p_export_public :
1698                    drv->key_management->p_export );
1699         if( method == NULL )
1700             return( PSA_ERROR_NOT_SUPPORTED );
1701         return( method( drv_context,
1702                         slot->data.se.slot_number,
1703                         data, data_size, data_length ) );
1704     }
1705 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1706 
1707     if( key_type_is_raw_bytes( slot->attr.type ) )
1708     {
1709         return( psa_internal_export_key_buffer( slot, data, data_size, data_length ) );
1710     }
1711     else if( PSA_KEY_TYPE_IS_RSA( slot->attr.type ) ||
1712              PSA_KEY_TYPE_IS_ECC( slot->attr.type ) )
1713     {
1714         if( PSA_KEY_TYPE_IS_PUBLIC_KEY( slot->attr.type ) )
1715         {
1716             /* Exporting public -> public */
1717             return( psa_internal_export_key_buffer( slot, data, data_size, data_length ) );
1718         }
1719         else if( !export_public_key )
1720         {
1721             /* Exporting private -> private */
1722             return( psa_internal_export_key_buffer( slot, data, data_size, data_length ) );
1723         }
1724 
1725         /* Need to export the public part of a private key,
1726          * so conversion is needed. Try the accelerators first. */
1727         psa_status_t status = psa_driver_wrapper_export_public_key( slot,
1728                                                                     data,
1729                                                                     data_size,
1730                                                                     data_length );
1731 
1732         if( status != PSA_ERROR_NOT_SUPPORTED ||
1733             psa_key_lifetime_is_external( slot->attr.lifetime ) )
1734             return( status );
1735 
1736         if( PSA_KEY_TYPE_IS_RSA( slot->attr.type ) )
1737         {
1738 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) || \
1739     defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY)
1740             mbedtls_rsa_context *rsa = NULL;
1741             status = psa_load_rsa_representation(
1742                                     slot->attr.type,
1743                                     slot->data.key.data,
1744                                     slot->data.key.bytes,
1745                                     &rsa );
1746             if( status != PSA_SUCCESS )
1747                 return( status );
1748 
1749             status = psa_export_rsa_key( PSA_KEY_TYPE_RSA_PUBLIC_KEY,
1750                                          rsa,
1751                                          data,
1752                                          data_size,
1753                                          data_length );
1754 
1755             vdb_mbedtls_rsa_free( rsa );
1756             vdb_mbedtls_free( rsa );
1757 
1758             return( status );
1759 #else
1760             /* We don't know how to convert a private RSA key to public. */
1761             return( PSA_ERROR_NOT_SUPPORTED );
1762 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) ||
1763         * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY) */
1764         }
1765         else
1766         {
1767 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) || \
1768     defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY)
1769             mbedtls_ecp_keypair *ecp = NULL;
1770             status = psa_load_ecp_representation(
1771                                     slot->attr.type,
1772                                     slot->data.key.data,
1773                                     slot->data.key.bytes,
1774                                     &ecp );
1775             if( status != PSA_SUCCESS )
1776                 return( status );
1777 
1778             status = psa_export_ecp_key( PSA_KEY_TYPE_ECC_PUBLIC_KEY(
1779                                             PSA_KEY_TYPE_ECC_GET_FAMILY(
1780                                                 slot->attr.type ) ),
1781                                          ecp,
1782                                          data,
1783                                          data_size,
1784                                          data_length );
1785 
1786             vdb_mbedtls_ecp_keypair_free( ecp );
1787             vdb_mbedtls_free( ecp );
1788             return( status );
1789 #else
1790             /* We don't know how to convert a private ECC key to public */
1791             return( PSA_ERROR_NOT_SUPPORTED );
1792 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) ||
1793         * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY) */
1794         }
1795     }
1796     else
1797     {
1798         /* This shouldn't happen in the reference implementation, but
1799            it is valid for a special-purpose implementation to omit
1800            support for exporting certain key types. */
1801         return( PSA_ERROR_NOT_SUPPORTED );
1802     }
1803 }
1804 
psa_export_key(mbedtls_svc_key_id_t key,uint8_t * data,size_t data_size,size_t * data_length)1805 psa_status_t psa_export_key( mbedtls_svc_key_id_t key,
1806                              uint8_t *data,
1807                              size_t data_size,
1808                              size_t *data_length )
1809 {
1810     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
1811     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
1812     psa_key_slot_t *slot;
1813 
1814     /* Set the key to empty now, so that even when there are errors, we always
1815      * set data_length to a value between 0 and data_size. On error, setting
1816      * the key to empty is a good choice because an empty key representation is
1817      * unlikely to be accepted anywhere. */
1818     *data_length = 0;
1819 
1820     /* Export requires the EXPORT flag. There is an exception for public keys,
1821      * which don't require any flag, but
1822      * psa_get_and_lock_key_slot_with_policy() takes care of this.
1823      */
1824     status = psa_get_and_lock_key_slot_with_policy( key, &slot,
1825                                                     PSA_KEY_USAGE_EXPORT, 0 );
1826     if( status != PSA_SUCCESS )
1827         return( status );
1828 
1829     status = psa_internal_export_key( slot, data, data_size, data_length, 0 );
1830     unlock_status = psa_unlock_key_slot( slot );
1831 
1832     return( ( status == PSA_SUCCESS ) ? unlock_status : status );
1833 }
1834 
psa_export_public_key(mbedtls_svc_key_id_t key,uint8_t * data,size_t data_size,size_t * data_length)1835 psa_status_t psa_export_public_key( mbedtls_svc_key_id_t key,
1836                                     uint8_t *data,
1837                                     size_t data_size,
1838                                     size_t *data_length )
1839 {
1840     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
1841     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
1842     psa_key_slot_t *slot;
1843 
1844     /* Set the key to empty now, so that even when there are errors, we always
1845      * set data_length to a value between 0 and data_size. On error, setting
1846      * the key to empty is a good choice because an empty key representation is
1847      * unlikely to be accepted anywhere. */
1848     *data_length = 0;
1849 
1850     /* Exporting a public key doesn't require a usage flag. */
1851     status = psa_get_and_lock_key_slot_with_policy( key, &slot, 0, 0 );
1852     if( status != PSA_SUCCESS )
1853         return( status );
1854 
1855     status = psa_internal_export_key( slot, data, data_size, data_length, 1 );
1856     unlock_status = psa_unlock_key_slot( slot );
1857 
1858     return( ( status == PSA_SUCCESS ) ? unlock_status : status );
1859 }
1860 
1861 #if defined(static_assert)
1862 static_assert( ( MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY & MBEDTLS_PSA_KA_MASK_DUAL_USE ) == 0,
1863                "One or more key attribute flag is listed as both external-only and dual-use" );
1864 static_assert( ( PSA_KA_MASK_INTERNAL_ONLY & MBEDTLS_PSA_KA_MASK_DUAL_USE ) == 0,
1865                "One or more key attribute flag is listed as both internal-only and dual-use" );
1866 static_assert( ( PSA_KA_MASK_INTERNAL_ONLY & MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY ) == 0,
1867                "One or more key attribute flag is listed as both internal-only and external-only" );
1868 #endif
1869 
1870 /** Validate that a key policy is internally well-formed.
1871  *
1872  * This function only rejects invalid policies. It does not validate the
1873  * consistency of the policy with respect to other attributes of the key
1874  * such as the key type.
1875  */
psa_validate_key_policy(const psa_key_policy_t * policy)1876 static psa_status_t psa_validate_key_policy( const psa_key_policy_t *policy )
1877 {
1878     if( ( policy->usage & ~( PSA_KEY_USAGE_EXPORT |
1879                              PSA_KEY_USAGE_COPY |
1880                              PSA_KEY_USAGE_ENCRYPT |
1881                              PSA_KEY_USAGE_DECRYPT |
1882                              PSA_KEY_USAGE_SIGN_HASH |
1883                              PSA_KEY_USAGE_VERIFY_HASH |
1884                              PSA_KEY_USAGE_DERIVE ) ) != 0 )
1885         return( PSA_ERROR_INVALID_ARGUMENT );
1886 
1887     return( PSA_SUCCESS );
1888 }
1889 
1890 /** Validate the internal consistency of key attributes.
1891  *
1892  * This function only rejects invalid attribute values. If does not
1893  * validate the consistency of the attributes with any key data that may
1894  * be involved in the creation of the key.
1895  *
1896  * Call this function early in the key creation process.
1897  *
1898  * \param[in] attributes    Key attributes for the new key.
1899  * \param[out] p_drv        On any return, the driver for the key, if any.
1900  *                          NULL for a transparent key.
1901  *
1902  */
psa_validate_key_attributes(const psa_key_attributes_t * attributes,psa_se_drv_table_entry_t ** p_drv)1903 static psa_status_t psa_validate_key_attributes(
1904     const psa_key_attributes_t *attributes,
1905     psa_se_drv_table_entry_t **p_drv )
1906 {
1907     psa_status_t status = PSA_ERROR_INVALID_ARGUMENT;
1908     psa_key_lifetime_t lifetime = psa_get_key_lifetime( attributes );
1909     mbedtls_svc_key_id_t key = psa_get_key_id( attributes );
1910 
1911     status = psa_validate_key_location( lifetime, p_drv );
1912     if( status != PSA_SUCCESS )
1913         return( status );
1914 
1915     status = psa_validate_key_persistence( lifetime );
1916     if( status != PSA_SUCCESS )
1917         return( status );
1918 
1919     if ( PSA_KEY_LIFETIME_IS_VOLATILE( lifetime ) )
1920     {
1921         if( MBEDTLS_SVC_KEY_ID_GET_KEY_ID( key ) != 0 )
1922             return( PSA_ERROR_INVALID_ARGUMENT );
1923     }
1924     else
1925     {
1926         status = psa_validate_key_id( psa_get_key_id( attributes ), 0 );
1927         if( status != PSA_SUCCESS )
1928             return( status );
1929     }
1930 
1931     status = psa_validate_key_policy( &attributes->core.policy );
1932     if( status != PSA_SUCCESS )
1933         return( status );
1934 
1935     /* Refuse to create overly large keys.
1936      * Note that this doesn't trigger on import if the attributes don't
1937      * explicitly specify a size (so psa_get_key_bits returns 0), so
1938      * psa_import_key() needs its own checks. */
1939     if( psa_get_key_bits( attributes ) > PSA_MAX_KEY_BITS )
1940         return( PSA_ERROR_NOT_SUPPORTED );
1941 
1942     /* Reject invalid flags. These should not be reachable through the API. */
1943     if( attributes->core.flags & ~ ( MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY |
1944                                      MBEDTLS_PSA_KA_MASK_DUAL_USE ) )
1945         return( PSA_ERROR_INVALID_ARGUMENT );
1946 
1947     return( PSA_SUCCESS );
1948 }
1949 
1950 /** Prepare a key slot to receive key material.
1951  *
1952  * This function allocates a key slot and sets its metadata.
1953  *
1954  * If this function fails, call psa_fail_key_creation().
1955  *
1956  * This function is intended to be used as follows:
1957  * -# Call psa_start_key_creation() to allocate a key slot, prepare
1958  *    it with the specified attributes, and in case of a volatile key assign it
1959  *    a volatile key identifier.
1960  * -# Populate the slot with the key material.
1961  * -# Call psa_finish_key_creation() to finalize the creation of the slot.
1962  * In case of failure at any step, stop the sequence and call
1963  * psa_fail_key_creation().
1964  *
1965  * On success, the key slot is locked. It is the responsibility of the caller
1966  * to unlock the key slot when it does not access it anymore.
1967  *
1968  * \param method            An identification of the calling function.
1969  * \param[in] attributes    Key attributes for the new key.
1970  * \param[out] p_slot       On success, a pointer to the prepared slot.
1971  * \param[out] p_drv        On any return, the driver for the key, if any.
1972  *                          NULL for a transparent key.
1973  *
1974  * \retval #PSA_SUCCESS
1975  *         The key slot is ready to receive key material.
1976  * \return If this function fails, the key slot is an invalid state.
1977  *         You must call psa_fail_key_creation() to wipe and free the slot.
1978  */
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)1979 static psa_status_t psa_start_key_creation(
1980     psa_key_creation_method_t method,
1981     const psa_key_attributes_t *attributes,
1982     psa_key_slot_t **p_slot,
1983     psa_se_drv_table_entry_t **p_drv )
1984 {
1985     psa_status_t status;
1986     psa_key_id_t volatile_key_id;
1987     psa_key_slot_t *slot;
1988 
1989     (void) method;
1990     *p_drv = NULL;
1991 
1992     status = psa_validate_key_attributes( attributes, p_drv );
1993     if( status != PSA_SUCCESS )
1994         return( status );
1995 
1996     status = psa_get_empty_key_slot( &volatile_key_id, p_slot );
1997     if( status != PSA_SUCCESS )
1998         return( status );
1999     slot = *p_slot;
2000 
2001     /* We're storing the declared bit-size of the key. It's up to each
2002      * creation mechanism to verify that this information is correct.
2003      * It's automatically correct for mechanisms that use the bit-size as
2004      * an input (generate, device) but not for those where the bit-size
2005      * is optional (import, copy). In case of a volatile key, assign it the
2006      * volatile key identifier associated to the slot returned to contain its
2007      * definition. */
2008 
2009     slot->attr = attributes->core;
2010     if( PSA_KEY_LIFETIME_IS_VOLATILE( slot->attr.lifetime ) )
2011     {
2012 #if !defined(MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER)
2013         slot->attr.id = volatile_key_id;
2014 #else
2015         slot->attr.id.key_id = volatile_key_id;
2016 #endif
2017     }
2018 
2019     /* Erase external-only flags from the internal copy. To access
2020      * external-only flags, query `attributes`. Thanks to the check
2021      * in psa_validate_key_attributes(), this leaves the dual-use
2022      * flags and any internal flag that psa_get_empty_key_slot()
2023      * may have set. */
2024     slot->attr.flags &= ~MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY;
2025 
2026 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
2027     /* For a key in a secure element, we need to do three things
2028      * when creating or registering a persistent key:
2029      * create the key file in internal storage, create the
2030      * key inside the secure element, and update the driver's
2031      * persistent data. This is done by starting a transaction that will
2032      * encompass these three actions.
2033      * For registering a volatile key, we just need to find an appropriate
2034      * slot number inside the SE. Since the key is designated volatile, creating
2035      * a transaction is not required. */
2036     /* The first thing to do is to find a slot number for the new key.
2037      * We save the slot number in persistent storage as part of the
2038      * transaction data. It will be needed to recover if the power
2039      * fails during the key creation process, to clean up on the secure
2040      * element side after restarting. Obtaining a slot number from the
2041      * secure element driver updates its persistent state, but we do not yet
2042      * save the driver's persistent state, so that if the power fails,
2043      * we can roll back to a state where the key doesn't exist. */
2044     if( *p_drv != NULL )
2045     {
2046         status = psa_find_se_slot_for_key( attributes, method, *p_drv,
2047                                            &slot->data.se.slot_number );
2048         if( status != PSA_SUCCESS )
2049             return( status );
2050 
2051         if( ! PSA_KEY_LIFETIME_IS_VOLATILE( attributes->core.lifetime ) )
2052         {
2053             psa_crypto_prepare_transaction( PSA_CRYPTO_TRANSACTION_CREATE_KEY );
2054             psa_crypto_transaction.key.lifetime = slot->attr.lifetime;
2055             psa_crypto_transaction.key.slot = slot->data.se.slot_number;
2056             psa_crypto_transaction.key.id = slot->attr.id;
2057             status = psa_crypto_save_transaction( );
2058             if( status != PSA_SUCCESS )
2059             {
2060                 (void) psa_crypto_stop_transaction( );
2061                 return( status );
2062             }
2063         }
2064     }
2065 
2066     if( *p_drv == NULL && method == PSA_KEY_CREATION_REGISTER )
2067     {
2068         /* Key registration only makes sense with a secure element. */
2069         return( PSA_ERROR_INVALID_ARGUMENT );
2070     }
2071 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
2072 
2073     return( PSA_SUCCESS );
2074 }
2075 
2076 /** Finalize the creation of a key once its key material has been set.
2077  *
2078  * This entails writing the key to persistent storage.
2079  *
2080  * If this function fails, call psa_fail_key_creation().
2081  * See the documentation of psa_start_key_creation() for the intended use
2082  * of this function.
2083  *
2084  * If the finalization succeeds, the function unlocks the key slot (it was
2085  * locked by psa_start_key_creation()) and the key slot cannot be accessed
2086  * anymore as part of the key creation process.
2087  *
2088  * \param[in,out] slot  Pointer to the slot with key material.
2089  * \param[in] driver    The secure element driver for the key,
2090  *                      or NULL for a transparent key.
2091  * \param[out] key      On success, identifier of the key. Note that the
2092  *                      key identifier is also stored in the key slot.
2093  *
2094  * \retval #PSA_SUCCESS
2095  *         The key was successfully created.
2096  * \return If this function fails, the key slot is an invalid state.
2097  *         You must call psa_fail_key_creation() to wipe and free the slot.
2098  */
psa_finish_key_creation(psa_key_slot_t * slot,psa_se_drv_table_entry_t * driver,mbedtls_svc_key_id_t * key)2099 static psa_status_t psa_finish_key_creation(
2100     psa_key_slot_t *slot,
2101     psa_se_drv_table_entry_t *driver,
2102     mbedtls_svc_key_id_t *key)
2103 {
2104     psa_status_t status = PSA_SUCCESS;
2105     (void) slot;
2106     (void) driver;
2107 
2108 #if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C)
2109     if( ! PSA_KEY_LIFETIME_IS_VOLATILE( slot->attr.lifetime ) )
2110     {
2111 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
2112         if( driver != NULL )
2113         {
2114             psa_se_key_data_storage_t data;
2115 #if defined(static_assert)
2116             static_assert( sizeof( slot->data.se.slot_number ) ==
2117                            sizeof( data.slot_number ),
2118                            "Slot number size does not match psa_se_key_data_storage_t" );
2119 #endif
2120             memcpy( &data.slot_number, &slot->data.se.slot_number,
2121                     sizeof( slot->data.se.slot_number ) );
2122             status = psa_save_persistent_key( &slot->attr,
2123                                               (uint8_t*) &data,
2124                                               sizeof( data ) );
2125         }
2126         else
2127 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
2128         {
2129             /* Key material is saved in export representation in the slot, so
2130              * just pass the slot buffer for storage. */
2131             status = psa_save_persistent_key( &slot->attr,
2132                                               slot->data.key.data,
2133                                               slot->data.key.bytes );
2134         }
2135     }
2136 #endif /* defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) */
2137 
2138 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
2139     /* Finish the transaction for a key creation. This does not
2140      * happen when registering an existing key. Detect this case
2141      * by checking whether a transaction is in progress (actual
2142      * creation of a persistent key in a secure element requires a transaction,
2143      * but registration or volatile key creation doesn't use one). */
2144     if( driver != NULL &&
2145         psa_crypto_transaction.unknown.type == PSA_CRYPTO_TRANSACTION_CREATE_KEY )
2146     {
2147         status = psa_save_se_persistent_data( driver );
2148         if( status != PSA_SUCCESS )
2149         {
2150             psa_destroy_persistent_key( slot->attr.id );
2151             return( status );
2152         }
2153         status = psa_crypto_stop_transaction( );
2154     }
2155 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
2156 
2157     if( status == PSA_SUCCESS )
2158     {
2159         *key = slot->attr.id;
2160         status = psa_unlock_key_slot( slot );
2161         if( status != PSA_SUCCESS )
2162             *key = MBEDTLS_SVC_KEY_ID_INIT;
2163     }
2164 
2165     return( status );
2166 }
2167 
2168 /** Abort the creation of a key.
2169  *
2170  * You may call this function after calling psa_start_key_creation(),
2171  * or after psa_finish_key_creation() fails. In other circumstances, this
2172  * function may not clean up persistent storage.
2173  * See the documentation of psa_start_key_creation() for the intended use
2174  * of this function.
2175  *
2176  * \param[in,out] slot  Pointer to the slot with key material.
2177  * \param[in] driver    The secure element driver for the key,
2178  *                      or NULL for a transparent key.
2179  */
psa_fail_key_creation(psa_key_slot_t * slot,psa_se_drv_table_entry_t * driver)2180 static void psa_fail_key_creation( psa_key_slot_t *slot,
2181                                    psa_se_drv_table_entry_t *driver )
2182 {
2183     (void) driver;
2184 
2185     if( slot == NULL )
2186         return;
2187 
2188 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
2189     /* TODO: If the key has already been created in the secure
2190      * element, and the failure happened later (when saving metadata
2191      * to internal storage), we need to destroy the key in the secure
2192      * element.
2193      * https://github.com/ARMmbed/mbed-crypto/issues/217
2194      */
2195 
2196     /* Abort the ongoing transaction if any (there may not be one if
2197      * the creation process failed before starting one, or if the
2198      * key creation is a registration of a key in a secure element).
2199      * Earlier functions must already have done what it takes to undo any
2200      * partial creation. All that's left is to update the transaction data
2201      * itself. */
2202     (void) psa_crypto_stop_transaction( );
2203 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
2204 
2205     psa_wipe_key_slot( slot );
2206 }
2207 
2208 /** Validate optional attributes during key creation.
2209  *
2210  * Some key attributes are optional during key creation. If they are
2211  * specified in the attributes structure, check that they are consistent
2212  * with the data in the slot.
2213  *
2214  * This function should be called near the end of key creation, after
2215  * the slot in memory is fully populated but before saving persistent data.
2216  */
psa_validate_optional_attributes(const psa_key_slot_t * slot,const psa_key_attributes_t * attributes)2217 static psa_status_t psa_validate_optional_attributes(
2218     const psa_key_slot_t *slot,
2219     const psa_key_attributes_t *attributes )
2220 {
2221     if( attributes->core.type != 0 )
2222     {
2223         if( attributes->core.type != slot->attr.type )
2224             return( PSA_ERROR_INVALID_ARGUMENT );
2225     }
2226 
2227     if( attributes->domain_parameters_size != 0 )
2228     {
2229 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) || \
2230     defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY)
2231         if( PSA_KEY_TYPE_IS_RSA( slot->attr.type ) )
2232         {
2233             mbedtls_rsa_context *rsa = NULL;
2234             mbedtls_mpi actual, required;
2235             int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2236 
2237             psa_status_t status = psa_load_rsa_representation(
2238                                     slot->attr.type,
2239                                     slot->data.key.data,
2240                                     slot->data.key.bytes,
2241                                     &rsa );
2242             if( status != PSA_SUCCESS )
2243                 return( status );
2244 
2245             vdb_mbedtls_mpi_init( &actual );
2246             vdb_mbedtls_mpi_init( &required );
2247             ret = vdb_mbedtls_rsa_export( rsa,
2248                                       NULL, NULL, NULL, NULL, &actual );
2249             vdb_mbedtls_rsa_free( rsa );
2250             vdb_mbedtls_free( rsa );
2251             if( ret != 0 )
2252                 goto rsa_exit;
2253             ret = vdb_mbedtls_mpi_read_binary( &required,
2254                                            attributes->domain_parameters,
2255                                            attributes->domain_parameters_size );
2256             if( ret != 0 )
2257                 goto rsa_exit;
2258             if( vdb_mbedtls_mpi_cmp_mpi( &actual, &required ) != 0 )
2259                 ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2260         rsa_exit:
2261             vdb_mbedtls_mpi_free( &actual );
2262             vdb_mbedtls_mpi_free( &required );
2263             if( ret != 0)
2264                 return( mbedtls_to_psa_error( ret ) );
2265         }
2266         else
2267 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) ||
2268         * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY) */
2269         {
2270             return( PSA_ERROR_INVALID_ARGUMENT );
2271         }
2272     }
2273 
2274     if( attributes->core.bits != 0 )
2275     {
2276         if( attributes->core.bits != slot->attr.bits )
2277             return( PSA_ERROR_INVALID_ARGUMENT );
2278     }
2279 
2280     return( PSA_SUCCESS );
2281 }
2282 
psa_import_key(const psa_key_attributes_t * attributes,const uint8_t * data,size_t data_length,mbedtls_svc_key_id_t * key)2283 psa_status_t psa_import_key( const psa_key_attributes_t *attributes,
2284                              const uint8_t *data,
2285                              size_t data_length,
2286                              mbedtls_svc_key_id_t *key )
2287 {
2288     psa_status_t status;
2289     psa_key_slot_t *slot = NULL;
2290     psa_se_drv_table_entry_t *driver = NULL;
2291 
2292     *key = MBEDTLS_SVC_KEY_ID_INIT;
2293 
2294     /* Reject zero-length symmetric keys (including raw data key objects).
2295      * This also rejects any key which might be encoded as an empty string,
2296      * which is never valid. */
2297     if( data_length == 0 )
2298         return( PSA_ERROR_INVALID_ARGUMENT );
2299 
2300     status = psa_start_key_creation( PSA_KEY_CREATION_IMPORT, attributes,
2301                                      &slot, &driver );
2302     if( status != PSA_SUCCESS )
2303         goto exit;
2304 
2305 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
2306     if( driver != NULL )
2307     {
2308         const psa_drv_se_t *drv = psa_get_se_driver_methods( driver );
2309         /* The driver should set the number of key bits, however in
2310          * case it doesn't, we initialize bits to an invalid value. */
2311         size_t bits = PSA_MAX_KEY_BITS + 1;
2312         if( drv->key_management == NULL ||
2313             drv->key_management->p_import == NULL )
2314         {
2315             status = PSA_ERROR_NOT_SUPPORTED;
2316             goto exit;
2317         }
2318         status = drv->key_management->p_import(
2319             psa_get_se_driver_context( driver ),
2320             slot->data.se.slot_number, attributes, data, data_length,
2321             &bits );
2322         if( status != PSA_SUCCESS )
2323             goto exit;
2324         if( bits > PSA_MAX_KEY_BITS )
2325         {
2326             status = PSA_ERROR_NOT_SUPPORTED;
2327             goto exit;
2328         }
2329         slot->attr.bits = (psa_key_bits_t) bits;
2330     }
2331     else
2332 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
2333     {
2334         status = psa_import_key_into_slot( slot, data, data_length );
2335         if( status != PSA_SUCCESS )
2336             goto exit;
2337     }
2338     status = psa_validate_optional_attributes( slot, attributes );
2339     if( status != PSA_SUCCESS )
2340         goto exit;
2341 
2342     status = psa_finish_key_creation( slot, driver, key );
2343 exit:
2344     if( status != PSA_SUCCESS )
2345         psa_fail_key_creation( slot, driver );
2346 
2347     return( status );
2348 }
2349 
2350 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
mbedtls_psa_register_se_key(const psa_key_attributes_t * attributes)2351 psa_status_t mbedtls_psa_register_se_key(
2352     const psa_key_attributes_t *attributes )
2353 {
2354     psa_status_t status;
2355     psa_key_slot_t *slot = NULL;
2356     psa_se_drv_table_entry_t *driver = NULL;
2357     mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
2358 
2359     /* Leaving attributes unspecified is not currently supported.
2360      * It could make sense to query the key type and size from the
2361      * secure element, but not all secure elements support this
2362      * and the driver HAL doesn't currently support it. */
2363     if( psa_get_key_type( attributes ) == PSA_KEY_TYPE_NONE )
2364         return( PSA_ERROR_NOT_SUPPORTED );
2365     if( psa_get_key_bits( attributes ) == 0 )
2366         return( PSA_ERROR_NOT_SUPPORTED );
2367 
2368     status = psa_start_key_creation( PSA_KEY_CREATION_REGISTER, attributes,
2369                                      &slot, &driver );
2370     if( status != PSA_SUCCESS )
2371         goto exit;
2372 
2373     status = psa_finish_key_creation( slot, driver, &key );
2374 
2375 exit:
2376     if( status != PSA_SUCCESS )
2377         psa_fail_key_creation( slot, driver );
2378 
2379     /* Registration doesn't keep the key in RAM. */
2380     psa_close_key( key );
2381     return( status );
2382 }
2383 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
2384 
psa_copy_key_material(const psa_key_slot_t * source,psa_key_slot_t * target)2385 static psa_status_t psa_copy_key_material( const psa_key_slot_t *source,
2386                                            psa_key_slot_t *target )
2387 {
2388     psa_status_t status = psa_copy_key_material_into_slot( target,
2389                                                            source->data.key.data,
2390                                                            source->data.key.bytes );
2391     if( status != PSA_SUCCESS )
2392         return( status );
2393 
2394     target->attr.type = source->attr.type;
2395     target->attr.bits = source->attr.bits;
2396 
2397     return( PSA_SUCCESS );
2398 }
2399 
psa_copy_key(mbedtls_svc_key_id_t source_key,const psa_key_attributes_t * specified_attributes,mbedtls_svc_key_id_t * target_key)2400 psa_status_t psa_copy_key( mbedtls_svc_key_id_t source_key,
2401                            const psa_key_attributes_t *specified_attributes,
2402                            mbedtls_svc_key_id_t *target_key )
2403 {
2404     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2405     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
2406     psa_key_slot_t *source_slot = NULL;
2407     psa_key_slot_t *target_slot = NULL;
2408     psa_key_attributes_t actual_attributes = *specified_attributes;
2409     psa_se_drv_table_entry_t *driver = NULL;
2410 
2411     *target_key = MBEDTLS_SVC_KEY_ID_INIT;
2412 
2413     status = psa_get_and_lock_transparent_key_slot_with_policy(
2414                  source_key, &source_slot, PSA_KEY_USAGE_COPY, 0 );
2415     if( status != PSA_SUCCESS )
2416         goto exit;
2417 
2418     status = psa_validate_optional_attributes( source_slot,
2419                                                specified_attributes );
2420     if( status != PSA_SUCCESS )
2421         goto exit;
2422 
2423     status = psa_restrict_key_policy( &actual_attributes.core.policy,
2424                                       &source_slot->attr.policy );
2425     if( status != PSA_SUCCESS )
2426         goto exit;
2427 
2428     status = psa_start_key_creation( PSA_KEY_CREATION_COPY, &actual_attributes,
2429                                      &target_slot, &driver );
2430     if( status != PSA_SUCCESS )
2431         goto exit;
2432 
2433 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
2434     if( driver != NULL )
2435     {
2436         /* Copying to a secure element is not implemented yet. */
2437         status = PSA_ERROR_NOT_SUPPORTED;
2438         goto exit;
2439     }
2440 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
2441 
2442     status = psa_copy_key_material( source_slot, target_slot );
2443     if( status != PSA_SUCCESS )
2444         goto exit;
2445 
2446     status = psa_finish_key_creation( target_slot, driver, target_key );
2447 exit:
2448     if( status != PSA_SUCCESS )
2449         psa_fail_key_creation( target_slot, driver );
2450 
2451     unlock_status = psa_unlock_key_slot( source_slot );
2452 
2453     return( ( status == PSA_SUCCESS ) ? unlock_status : status );
2454 }
2455 
2456 
2457 
2458 /****************************************************************/
2459 /* Message digests */
2460 /****************************************************************/
2461 
2462 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) || \
2463     defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP) || \
2464     defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS) || \
2465     defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)
mbedtls_md_info_from_psa(psa_algorithm_t alg)2466 static const mbedtls_md_info_t *mbedtls_md_info_from_psa( psa_algorithm_t alg )
2467 {
2468     switch( alg )
2469     {
2470 #if defined(MBEDTLS_PSA_BUILTIN_ALG_MD2)
2471         case PSA_ALG_MD2:
2472             return( &vdb_mbedtls_md2_info );
2473 #endif
2474 #if defined(MBEDTLS_PSA_BUILTIN_ALG_MD4)
2475         case PSA_ALG_MD4:
2476             return( &vdb_mbedtls_md4_info );
2477 #endif
2478 #if defined(MBEDTLS_PSA_BUILTIN_ALG_MD5)
2479         case PSA_ALG_MD5:
2480             return( &vdb_mbedtls_md5_info );
2481 #endif
2482 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RIPEMD160)
2483         case PSA_ALG_RIPEMD160:
2484             return( &vdb_mbedtls_ripemd160_info );
2485 #endif
2486 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_1)
2487         case PSA_ALG_SHA_1:
2488             return( &vdb_mbedtls_sha1_info );
2489 #endif
2490 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_224)
2491         case PSA_ALG_SHA_224:
2492             return( &vdb_mbedtls_sha224_info );
2493 #endif
2494 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_256)
2495         case PSA_ALG_SHA_256:
2496             return( &vdb_mbedtls_sha256_info );
2497 #endif
2498 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_384)
2499         case PSA_ALG_SHA_384:
2500             return( &vdb_mbedtls_sha384_info );
2501 #endif
2502 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_512)
2503         case PSA_ALG_SHA_512:
2504             return( &vdb_mbedtls_sha512_info );
2505 #endif
2506         default:
2507             return( NULL );
2508     }
2509 }
2510 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) ||
2511         * defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP) ||
2512         * defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS) ||
2513         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) */
2514 
psa_hash_abort(psa_hash_operation_t * operation)2515 psa_status_t psa_hash_abort( psa_hash_operation_t *operation )
2516 {
2517     switch( operation->alg )
2518     {
2519         case 0:
2520             /* The object has (apparently) been initialized but it is not
2521              * in use. It's ok to call abort on such an object, and there's
2522              * nothing to do. */
2523             break;
2524 #if defined(MBEDTLS_PSA_BUILTIN_ALG_MD2)
2525         case PSA_ALG_MD2:
2526             vdb_mbedtls_md2_free( &operation->ctx.md2 );
2527             break;
2528 #endif
2529 #if defined(MBEDTLS_PSA_BUILTIN_ALG_MD4)
2530         case PSA_ALG_MD4:
2531             vdb_mbedtls_md4_free( &operation->ctx.md4 );
2532             break;
2533 #endif
2534 #if defined(MBEDTLS_PSA_BUILTIN_ALG_MD5)
2535         case PSA_ALG_MD5:
2536             vdb_mbedtls_md5_free( &operation->ctx.md5 );
2537             break;
2538 #endif
2539 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RIPEMD160)
2540         case PSA_ALG_RIPEMD160:
2541             vdb_mbedtls_ripemd160_free( &operation->ctx.ripemd160 );
2542             break;
2543 #endif
2544 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_1)
2545         case PSA_ALG_SHA_1:
2546             vdb_mbedtls_sha1_free( &operation->ctx.sha1 );
2547             break;
2548 #endif
2549 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_224)
2550         case PSA_ALG_SHA_224:
2551             vdb_mbedtls_sha256_free( &operation->ctx.sha256 );
2552             break;
2553 #endif
2554 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_256)
2555         case PSA_ALG_SHA_256:
2556             vdb_mbedtls_sha256_free( &operation->ctx.sha256 );
2557             break;
2558 #endif
2559 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_384)
2560         case PSA_ALG_SHA_384:
2561             vdb_mbedtls_sha512_free( &operation->ctx.sha512 );
2562             break;
2563 #endif
2564 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_512)
2565         case PSA_ALG_SHA_512:
2566             vdb_mbedtls_sha512_free( &operation->ctx.sha512 );
2567             break;
2568 #endif
2569         default:
2570             return( PSA_ERROR_BAD_STATE );
2571     }
2572     operation->alg = 0;
2573     return( PSA_SUCCESS );
2574 }
2575 
psa_hash_setup(psa_hash_operation_t * operation,psa_algorithm_t alg)2576 psa_status_t psa_hash_setup( psa_hash_operation_t *operation,
2577                              psa_algorithm_t alg )
2578 {
2579     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2580 
2581     /* A context must be freshly initialized before it can be set up. */
2582     if( operation->alg != 0 )
2583     {
2584         return( PSA_ERROR_BAD_STATE );
2585     }
2586 
2587     switch( alg )
2588     {
2589 #if defined(MBEDTLS_PSA_BUILTIN_ALG_MD2)
2590         case PSA_ALG_MD2:
2591             vdb_mbedtls_md2_init( &operation->ctx.md2 );
2592             ret = vdb_mbedtls_md2_starts_ret( &operation->ctx.md2 );
2593             break;
2594 #endif
2595 #if defined(MBEDTLS_PSA_BUILTIN_ALG_MD4)
2596         case PSA_ALG_MD4:
2597             vdb_mbedtls_md4_init( &operation->ctx.md4 );
2598             ret = vdb_mbedtls_md4_starts_ret( &operation->ctx.md4 );
2599             break;
2600 #endif
2601 #if defined(MBEDTLS_PSA_BUILTIN_ALG_MD5)
2602         case PSA_ALG_MD5:
2603             vdb_mbedtls_md5_init( &operation->ctx.md5 );
2604             ret = vdb_mbedtls_md5_starts_ret( &operation->ctx.md5 );
2605             break;
2606 #endif
2607 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RIPEMD160)
2608         case PSA_ALG_RIPEMD160:
2609             vdb_mbedtls_ripemd160_init( &operation->ctx.ripemd160 );
2610             ret = vdb_mbedtls_ripemd160_starts_ret( &operation->ctx.ripemd160 );
2611             break;
2612 #endif
2613 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_1)
2614         case PSA_ALG_SHA_1:
2615             vdb_mbedtls_sha1_init( &operation->ctx.sha1 );
2616             ret = vdb_mbedtls_sha1_starts_ret( &operation->ctx.sha1 );
2617             break;
2618 #endif
2619 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_224)
2620         case PSA_ALG_SHA_224:
2621             vdb_mbedtls_sha256_init( &operation->ctx.sha256 );
2622             ret = vdb_mbedtls_sha256_starts_ret( &operation->ctx.sha256, 1 );
2623             break;
2624 #endif
2625 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_256)
2626         case PSA_ALG_SHA_256:
2627             vdb_mbedtls_sha256_init( &operation->ctx.sha256 );
2628             ret = vdb_mbedtls_sha256_starts_ret( &operation->ctx.sha256, 0 );
2629             break;
2630 #endif
2631 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_384)
2632         case PSA_ALG_SHA_384:
2633             vdb_mbedtls_sha512_init( &operation->ctx.sha512 );
2634             ret = vdb_mbedtls_sha512_starts_ret( &operation->ctx.sha512, 1 );
2635             break;
2636 #endif
2637 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_512)
2638         case PSA_ALG_SHA_512:
2639             vdb_mbedtls_sha512_init( &operation->ctx.sha512 );
2640             ret = vdb_mbedtls_sha512_starts_ret( &operation->ctx.sha512, 0 );
2641             break;
2642 #endif
2643         default:
2644             return( PSA_ALG_IS_HASH( alg ) ?
2645                     PSA_ERROR_NOT_SUPPORTED :
2646                     PSA_ERROR_INVALID_ARGUMENT );
2647     }
2648     if( ret == 0 )
2649         operation->alg = alg;
2650     else
2651         psa_hash_abort( operation );
2652     return( mbedtls_to_psa_error( ret ) );
2653 }
2654 
psa_hash_update(psa_hash_operation_t * operation,const uint8_t * input,size_t input_length)2655 psa_status_t psa_hash_update( psa_hash_operation_t *operation,
2656                               const uint8_t *input,
2657                               size_t input_length )
2658 {
2659     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2660 
2661     /* Don't require hash implementations to behave correctly on a
2662      * zero-length input, which may have an invalid pointer. */
2663     if( input_length == 0 )
2664         return( PSA_SUCCESS );
2665 
2666     switch( operation->alg )
2667     {
2668 #if defined(MBEDTLS_PSA_BUILTIN_ALG_MD2)
2669         case PSA_ALG_MD2:
2670             ret = vdb_mbedtls_md2_update_ret( &operation->ctx.md2,
2671                                           input, input_length );
2672             break;
2673 #endif
2674 #if defined(MBEDTLS_PSA_BUILTIN_ALG_MD4)
2675         case PSA_ALG_MD4:
2676             ret = vdb_mbedtls_md4_update_ret( &operation->ctx.md4,
2677                                           input, input_length );
2678             break;
2679 #endif
2680 #if defined(MBEDTLS_PSA_BUILTIN_ALG_MD5)
2681         case PSA_ALG_MD5:
2682             ret = vdb_mbedtls_md5_update_ret( &operation->ctx.md5,
2683                                           input, input_length );
2684             break;
2685 #endif
2686 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RIPEMD160)
2687         case PSA_ALG_RIPEMD160:
2688             ret = vdb_mbedtls_ripemd160_update_ret( &operation->ctx.ripemd160,
2689                                                 input, input_length );
2690             break;
2691 #endif
2692 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_1)
2693         case PSA_ALG_SHA_1:
2694             ret = vdb_mbedtls_sha1_update_ret( &operation->ctx.sha1,
2695                                            input, input_length );
2696             break;
2697 #endif
2698 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_224)
2699         case PSA_ALG_SHA_224:
2700             ret = vdb_mbedtls_sha256_update_ret( &operation->ctx.sha256,
2701                                              input, input_length );
2702             break;
2703 #endif
2704 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_256)
2705         case PSA_ALG_SHA_256:
2706             ret = vdb_mbedtls_sha256_update_ret( &operation->ctx.sha256,
2707                                              input, input_length );
2708             break;
2709 #endif
2710 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_384)
2711         case PSA_ALG_SHA_384:
2712             ret = vdb_mbedtls_sha512_update_ret( &operation->ctx.sha512,
2713                                              input, input_length );
2714             break;
2715 #endif
2716 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_512)
2717         case PSA_ALG_SHA_512:
2718             ret = vdb_mbedtls_sha512_update_ret( &operation->ctx.sha512,
2719                                              input, input_length );
2720             break;
2721 #endif
2722         default:
2723             (void)input;
2724             return( PSA_ERROR_BAD_STATE );
2725     }
2726 
2727     if( ret != 0 )
2728         psa_hash_abort( operation );
2729     return( mbedtls_to_psa_error( ret ) );
2730 }
2731 
psa_hash_finish(psa_hash_operation_t * operation,uint8_t * hash,size_t hash_size,size_t * hash_length)2732 psa_status_t psa_hash_finish( psa_hash_operation_t *operation,
2733                               uint8_t *hash,
2734                               size_t hash_size,
2735                               size_t *hash_length )
2736 {
2737     psa_status_t status;
2738     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2739     size_t actual_hash_length = PSA_HASH_SIZE( operation->alg );
2740 
2741     /* Fill the output buffer with something that isn't a valid hash
2742      * (barring an attack on the hash and deliberately-crafted input),
2743      * in case the caller doesn't check the return status properly. */
2744     *hash_length = hash_size;
2745     /* If hash_size is 0 then hash may be NULL and then the
2746      * call to memset would have undefined behavior. */
2747     if( hash_size != 0 )
2748         memset( hash, '!', hash_size );
2749 
2750     if( hash_size < actual_hash_length )
2751     {
2752         status = PSA_ERROR_BUFFER_TOO_SMALL;
2753         goto exit;
2754     }
2755 
2756     switch( operation->alg )
2757     {
2758 #if defined(MBEDTLS_PSA_BUILTIN_ALG_MD2)
2759         case PSA_ALG_MD2:
2760             ret = vdb_mbedtls_md2_finish_ret( &operation->ctx.md2, hash );
2761             break;
2762 #endif
2763 #if defined(MBEDTLS_PSA_BUILTIN_ALG_MD4)
2764         case PSA_ALG_MD4:
2765             ret = vdb_mbedtls_md4_finish_ret( &operation->ctx.md4, hash );
2766             break;
2767 #endif
2768 #if defined(MBEDTLS_PSA_BUILTIN_ALG_MD5)
2769         case PSA_ALG_MD5:
2770             ret = vdb_mbedtls_md5_finish_ret( &operation->ctx.md5, hash );
2771             break;
2772 #endif
2773 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RIPEMD160)
2774         case PSA_ALG_RIPEMD160:
2775             ret = vdb_mbedtls_ripemd160_finish_ret( &operation->ctx.ripemd160, hash );
2776             break;
2777 #endif
2778 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_1)
2779         case PSA_ALG_SHA_1:
2780             ret = vdb_mbedtls_sha1_finish_ret( &operation->ctx.sha1, hash );
2781             break;
2782 #endif
2783 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_224)
2784         case PSA_ALG_SHA_224:
2785             ret = vdb_mbedtls_sha256_finish_ret( &operation->ctx.sha256, hash );
2786             break;
2787 #endif
2788 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_256)
2789         case PSA_ALG_SHA_256:
2790             ret = vdb_mbedtls_sha256_finish_ret( &operation->ctx.sha256, hash );
2791             break;
2792 #endif
2793 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_384)
2794         case PSA_ALG_SHA_384:
2795             ret = vdb_mbedtls_sha512_finish_ret( &operation->ctx.sha512, hash );
2796             break;
2797 #endif
2798 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_512)
2799         case PSA_ALG_SHA_512:
2800             ret = vdb_mbedtls_sha512_finish_ret( &operation->ctx.sha512, hash );
2801             break;
2802 #endif
2803         default:
2804             return( PSA_ERROR_BAD_STATE );
2805     }
2806     status = mbedtls_to_psa_error( ret );
2807 
2808 exit:
2809     if( status == PSA_SUCCESS )
2810     {
2811         *hash_length = actual_hash_length;
2812         return( psa_hash_abort( operation ) );
2813     }
2814     else
2815     {
2816         psa_hash_abort( operation );
2817         return( status );
2818     }
2819 }
2820 
psa_hash_verify(psa_hash_operation_t * operation,const uint8_t * hash,size_t hash_length)2821 psa_status_t psa_hash_verify( psa_hash_operation_t *operation,
2822                               const uint8_t *hash,
2823                               size_t hash_length )
2824 {
2825     uint8_t actual_hash[MBEDTLS_MD_MAX_SIZE];
2826     size_t actual_hash_length;
2827     psa_status_t status = psa_hash_finish( operation,
2828                                            actual_hash, sizeof( actual_hash ),
2829                                            &actual_hash_length );
2830     if( status != PSA_SUCCESS )
2831         return( status );
2832     if( actual_hash_length != hash_length )
2833         return( PSA_ERROR_INVALID_SIGNATURE );
2834     if( safer_memcmp( hash, actual_hash, actual_hash_length ) != 0 )
2835         return( PSA_ERROR_INVALID_SIGNATURE );
2836     return( PSA_SUCCESS );
2837 }
2838 
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)2839 psa_status_t psa_hash_compute( psa_algorithm_t alg,
2840                                const uint8_t *input, size_t input_length,
2841                                uint8_t *hash, size_t hash_size,
2842                                size_t *hash_length )
2843 {
2844     psa_hash_operation_t operation = PSA_HASH_OPERATION_INIT;
2845     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2846 
2847     *hash_length = hash_size;
2848     status = psa_hash_setup( &operation, alg );
2849     if( status != PSA_SUCCESS )
2850         goto exit;
2851     status = psa_hash_update( &operation, input, input_length );
2852     if( status != PSA_SUCCESS )
2853         goto exit;
2854     status = psa_hash_finish( &operation, hash, hash_size, hash_length );
2855     if( status != PSA_SUCCESS )
2856         goto exit;
2857 
2858 exit:
2859     if( status == PSA_SUCCESS )
2860         status = psa_hash_abort( &operation );
2861     else
2862         psa_hash_abort( &operation );
2863     return( status );
2864 }
2865 
psa_hash_compare(psa_algorithm_t alg,const uint8_t * input,size_t input_length,const uint8_t * hash,size_t hash_length)2866 psa_status_t psa_hash_compare( psa_algorithm_t alg,
2867                                const uint8_t *input, size_t input_length,
2868                                const uint8_t *hash, size_t hash_length )
2869 {
2870     psa_hash_operation_t operation = PSA_HASH_OPERATION_INIT;
2871     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2872 
2873     status = psa_hash_setup( &operation, alg );
2874     if( status != PSA_SUCCESS )
2875         goto exit;
2876     status = psa_hash_update( &operation, input, input_length );
2877     if( status != PSA_SUCCESS )
2878         goto exit;
2879     status = psa_hash_verify( &operation, hash, hash_length );
2880     if( status != PSA_SUCCESS )
2881         goto exit;
2882 
2883 exit:
2884     if( status == PSA_SUCCESS )
2885         status = psa_hash_abort( &operation );
2886     else
2887         psa_hash_abort( &operation );
2888     return( status );
2889 }
2890 
psa_hash_clone(const psa_hash_operation_t * source_operation,psa_hash_operation_t * target_operation)2891 psa_status_t psa_hash_clone( const psa_hash_operation_t *source_operation,
2892                              psa_hash_operation_t *target_operation )
2893 {
2894     if( target_operation->alg != 0 )
2895         return( PSA_ERROR_BAD_STATE );
2896 
2897     switch( source_operation->alg )
2898     {
2899         case 0:
2900             return( PSA_ERROR_BAD_STATE );
2901 #if defined(MBEDTLS_PSA_BUILTIN_ALG_MD2)
2902         case PSA_ALG_MD2:
2903             vdb_mbedtls_md2_clone( &target_operation->ctx.md2,
2904                                &source_operation->ctx.md2 );
2905             break;
2906 #endif
2907 #if defined(MBEDTLS_PSA_BUILTIN_ALG_MD4)
2908         case PSA_ALG_MD4:
2909             vdb_mbedtls_md4_clone( &target_operation->ctx.md4,
2910                                &source_operation->ctx.md4 );
2911             break;
2912 #endif
2913 #if defined(MBEDTLS_PSA_BUILTIN_ALG_MD5)
2914         case PSA_ALG_MD5:
2915             vdb_mbedtls_md5_clone( &target_operation->ctx.md5,
2916                                &source_operation->ctx.md5 );
2917             break;
2918 #endif
2919 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RIPEMD160)
2920         case PSA_ALG_RIPEMD160:
2921             vdb_mbedtls_ripemd160_clone( &target_operation->ctx.ripemd160,
2922                                      &source_operation->ctx.ripemd160 );
2923             break;
2924 #endif
2925 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_1)
2926         case PSA_ALG_SHA_1:
2927             vdb_mbedtls_sha1_clone( &target_operation->ctx.sha1,
2928                                 &source_operation->ctx.sha1 );
2929             break;
2930 #endif
2931 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_224)
2932         case PSA_ALG_SHA_224:
2933             vdb_mbedtls_sha256_clone( &target_operation->ctx.sha256,
2934                                   &source_operation->ctx.sha256 );
2935             break;
2936 #endif
2937 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_256)
2938         case PSA_ALG_SHA_256:
2939             vdb_mbedtls_sha256_clone( &target_operation->ctx.sha256,
2940                                   &source_operation->ctx.sha256 );
2941             break;
2942 #endif
2943 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_384)
2944         case PSA_ALG_SHA_384:
2945             vdb_mbedtls_sha512_clone( &target_operation->ctx.sha512,
2946                                   &source_operation->ctx.sha512 );
2947             break;
2948 #endif
2949 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_512)
2950         case PSA_ALG_SHA_512:
2951             vdb_mbedtls_sha512_clone( &target_operation->ctx.sha512,
2952                                   &source_operation->ctx.sha512 );
2953             break;
2954 #endif
2955         default:
2956             return( PSA_ERROR_NOT_SUPPORTED );
2957     }
2958 
2959     target_operation->alg = source_operation->alg;
2960     return( PSA_SUCCESS );
2961 }
2962 
2963 
2964 /****************************************************************/
2965 /* MAC */
2966 /****************************************************************/
2967 
mbedtls_cipher_info_from_psa(psa_algorithm_t alg,psa_key_type_t key_type,size_t key_bits,mbedtls_cipher_id_t * cipher_id)2968 static const mbedtls_cipher_info_t *mbedtls_cipher_info_from_psa(
2969     psa_algorithm_t alg,
2970     psa_key_type_t key_type,
2971     size_t key_bits,
2972     mbedtls_cipher_id_t* cipher_id )
2973 {
2974     mbedtls_cipher_mode_t mode;
2975     mbedtls_cipher_id_t cipher_id_tmp;
2976 
2977     if( PSA_ALG_IS_AEAD( alg ) )
2978         alg = PSA_ALG_AEAD_WITH_TAG_LENGTH( alg, 0 );
2979 
2980     if( PSA_ALG_IS_CIPHER( alg ) || PSA_ALG_IS_AEAD( alg ) )
2981     {
2982         switch( alg )
2983         {
2984             case PSA_ALG_STREAM_CIPHER:
2985                 mode = MBEDTLS_MODE_STREAM;
2986                 break;
2987             case PSA_ALG_CTR:
2988                 mode = MBEDTLS_MODE_CTR;
2989                 break;
2990             case PSA_ALG_CFB:
2991                 mode = MBEDTLS_MODE_CFB;
2992                 break;
2993             case PSA_ALG_OFB:
2994                 mode = MBEDTLS_MODE_OFB;
2995                 break;
2996             case PSA_ALG_ECB_NO_PADDING:
2997                 mode = MBEDTLS_MODE_ECB;
2998                 break;
2999             case PSA_ALG_CBC_NO_PADDING:
3000                 mode = MBEDTLS_MODE_CBC;
3001                 break;
3002             case PSA_ALG_CBC_PKCS7:
3003                 mode = MBEDTLS_MODE_CBC;
3004                 break;
3005             case PSA_ALG_AEAD_WITH_TAG_LENGTH( PSA_ALG_CCM, 0 ):
3006                 mode = MBEDTLS_MODE_CCM;
3007                 break;
3008             case PSA_ALG_AEAD_WITH_TAG_LENGTH( PSA_ALG_GCM, 0 ):
3009                 mode = MBEDTLS_MODE_GCM;
3010                 break;
3011             case PSA_ALG_AEAD_WITH_TAG_LENGTH( PSA_ALG_CHACHA20_POLY1305, 0 ):
3012                 mode = MBEDTLS_MODE_CHACHAPOLY;
3013                 break;
3014             default:
3015                 return( NULL );
3016         }
3017     }
3018     else if( alg == PSA_ALG_CMAC )
3019         mode = MBEDTLS_MODE_ECB;
3020     else
3021         return( NULL );
3022 
3023     switch( key_type )
3024     {
3025         case PSA_KEY_TYPE_AES:
3026             cipher_id_tmp = MBEDTLS_CIPHER_ID_AES;
3027             break;
3028         case PSA_KEY_TYPE_DES:
3029             /* key_bits is 64 for Single-DES, 128 for two-key Triple-DES,
3030              * and 192 for three-key Triple-DES. */
3031             if( key_bits == 64 )
3032                 cipher_id_tmp = MBEDTLS_CIPHER_ID_DES;
3033             else
3034                 cipher_id_tmp = MBEDTLS_CIPHER_ID_3DES;
3035             /* mbedtls doesn't recognize two-key Triple-DES as an algorithm,
3036              * but two-key Triple-DES is functionally three-key Triple-DES
3037              * with K1=K3, so that's how we present it to mbedtls. */
3038             if( key_bits == 128 )
3039                 key_bits = 192;
3040             break;
3041         case PSA_KEY_TYPE_CAMELLIA:
3042             cipher_id_tmp = MBEDTLS_CIPHER_ID_CAMELLIA;
3043             break;
3044         case PSA_KEY_TYPE_ARC4:
3045             cipher_id_tmp = MBEDTLS_CIPHER_ID_ARC4;
3046             break;
3047         case PSA_KEY_TYPE_CHACHA20:
3048             cipher_id_tmp = MBEDTLS_CIPHER_ID_CHACHA20;
3049             break;
3050         default:
3051             return( NULL );
3052     }
3053     if( cipher_id != NULL )
3054         *cipher_id = cipher_id_tmp;
3055 
3056     return( vdb_mbedtls_cipher_info_from_values( cipher_id_tmp,
3057                                              (int) key_bits, mode ) );
3058 }
3059 
3060 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HMAC)
psa_get_hash_block_size(psa_algorithm_t alg)3061 static size_t psa_get_hash_block_size( psa_algorithm_t alg )
3062 {
3063     switch( alg )
3064     {
3065         case PSA_ALG_MD2:
3066             return( 16 );
3067         case PSA_ALG_MD4:
3068             return( 64 );
3069         case PSA_ALG_MD5:
3070             return( 64 );
3071         case PSA_ALG_RIPEMD160:
3072             return( 64 );
3073         case PSA_ALG_SHA_1:
3074             return( 64 );
3075         case PSA_ALG_SHA_224:
3076             return( 64 );
3077         case PSA_ALG_SHA_256:
3078             return( 64 );
3079         case PSA_ALG_SHA_384:
3080             return( 128 );
3081         case PSA_ALG_SHA_512:
3082             return( 128 );
3083         default:
3084             return( 0 );
3085     }
3086 }
3087 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_HMAC) */
3088 
3089 /* Initialize the MAC operation structure. Once this function has been
3090  * called, psa_mac_abort can run and will do the right thing. */
psa_mac_init(psa_mac_operation_t * operation,psa_algorithm_t alg)3091 static psa_status_t psa_mac_init( psa_mac_operation_t *operation,
3092                                   psa_algorithm_t alg )
3093 {
3094     psa_status_t status = PSA_ERROR_NOT_SUPPORTED;
3095 
3096     operation->alg = alg;
3097     operation->key_set = 0;
3098     operation->iv_set = 0;
3099     operation->iv_required = 0;
3100     operation->has_input = 0;
3101     operation->is_sign = 0;
3102 
3103 #if defined(MBEDTLS_CMAC_C)
3104     if( alg == PSA_ALG_CMAC )
3105     {
3106         operation->iv_required = 0;
3107         vdb_mbedtls_cipher_init( &operation->ctx.cmac );
3108         status = PSA_SUCCESS;
3109     }
3110     else
3111 #endif /* MBEDTLS_CMAC_C */
3112 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HMAC)
3113     if( PSA_ALG_IS_HMAC( operation->alg ) )
3114     {
3115         /* We'll set up the hash operation later in psa_hmac_setup_internal. */
3116         operation->ctx.hmac.hash_ctx.alg = 0;
3117         status = PSA_SUCCESS;
3118     }
3119     else
3120 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HMAC */
3121     {
3122         if( ! PSA_ALG_IS_MAC( alg ) )
3123             status = PSA_ERROR_INVALID_ARGUMENT;
3124     }
3125 
3126     if( status != PSA_SUCCESS )
3127         memset( operation, 0, sizeof( *operation ) );
3128     return( status );
3129 }
3130 
3131 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HMAC)
psa_hmac_abort_internal(psa_hmac_internal_data * hmac)3132 static psa_status_t psa_hmac_abort_internal( psa_hmac_internal_data *hmac )
3133 {
3134     vdb_mbedtls_platform_zeroize( hmac->opad, sizeof( hmac->opad ) );
3135     return( psa_hash_abort( &hmac->hash_ctx ) );
3136 }
3137 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HMAC */
3138 
psa_mac_abort(psa_mac_operation_t * operation)3139 psa_status_t psa_mac_abort( psa_mac_operation_t *operation )
3140 {
3141     if( operation->alg == 0 )
3142     {
3143         /* The object has (apparently) been initialized but it is not
3144          * in use. It's ok to call abort on such an object, and there's
3145          * nothing to do. */
3146         return( PSA_SUCCESS );
3147     }
3148     else
3149 #if defined(MBEDTLS_CMAC_C)
3150     if( operation->alg == PSA_ALG_CMAC )
3151     {
3152         vdb_mbedtls_cipher_free( &operation->ctx.cmac );
3153     }
3154     else
3155 #endif /* MBEDTLS_CMAC_C */
3156 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HMAC)
3157     if( PSA_ALG_IS_HMAC( operation->alg ) )
3158     {
3159         psa_hmac_abort_internal( &operation->ctx.hmac );
3160     }
3161     else
3162 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HMAC */
3163     {
3164         /* Sanity check (shouldn't happen: operation->alg should
3165          * always have been initialized to a valid value). */
3166         goto bad_state;
3167     }
3168 
3169     operation->alg = 0;
3170     operation->key_set = 0;
3171     operation->iv_set = 0;
3172     operation->iv_required = 0;
3173     operation->has_input = 0;
3174     operation->is_sign = 0;
3175 
3176     return( PSA_SUCCESS );
3177 
3178 bad_state:
3179     /* If abort is called on an uninitialized object, we can't trust
3180      * anything. Wipe the object in case it contains confidential data.
3181      * This may result in a memory leak if a pointer gets overwritten,
3182      * but it's too late to do anything about this. */
3183     memset( operation, 0, sizeof( *operation ) );
3184     return( PSA_ERROR_BAD_STATE );
3185 }
3186 
3187 #if defined(MBEDTLS_CMAC_C)
psa_cmac_setup(psa_mac_operation_t * operation,size_t key_bits,psa_key_slot_t * slot,const mbedtls_cipher_info_t * cipher_info)3188 static int psa_cmac_setup( psa_mac_operation_t *operation,
3189                            size_t key_bits,
3190                            psa_key_slot_t *slot,
3191                            const mbedtls_cipher_info_t *cipher_info )
3192 {
3193     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3194 
3195     operation->mac_size = cipher_info->block_size;
3196 
3197     ret = vdb_mbedtls_cipher_setup( &operation->ctx.cmac, cipher_info );
3198     if( ret != 0 )
3199         return( ret );
3200 
3201     ret = vdb_mbedtls_cipher_cmac_starts( &operation->ctx.cmac,
3202                                       slot->data.key.data,
3203                                       key_bits );
3204     return( ret );
3205 }
3206 #endif /* MBEDTLS_CMAC_C */
3207 
3208 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HMAC)
psa_hmac_setup_internal(psa_hmac_internal_data * hmac,const uint8_t * key,size_t key_length,psa_algorithm_t hash_alg)3209 static psa_status_t psa_hmac_setup_internal( psa_hmac_internal_data *hmac,
3210                                              const uint8_t *key,
3211                                              size_t key_length,
3212                                              psa_algorithm_t hash_alg )
3213 {
3214     uint8_t ipad[PSA_HMAC_MAX_HASH_BLOCK_SIZE];
3215     size_t i;
3216     size_t hash_size = PSA_HASH_SIZE( hash_alg );
3217     size_t block_size = psa_get_hash_block_size( hash_alg );
3218     psa_status_t status;
3219 
3220     /* Sanity checks on block_size, to guarantee that there won't be a buffer
3221      * overflow below. This should never trigger if the hash algorithm
3222      * is implemented correctly. */
3223     /* The size checks against the ipad and opad buffers cannot be written
3224      * `block_size > sizeof( ipad ) || block_size > sizeof( hmac->opad )`
3225      * because that triggers -Wlogical-op on GCC 7.3. */
3226     if( block_size > sizeof( ipad ) )
3227         return( PSA_ERROR_NOT_SUPPORTED );
3228     if( block_size > sizeof( hmac->opad ) )
3229         return( PSA_ERROR_NOT_SUPPORTED );
3230     if( block_size < hash_size )
3231         return( PSA_ERROR_NOT_SUPPORTED );
3232 
3233     if( key_length > block_size )
3234     {
3235         status = psa_hash_compute( hash_alg, key, key_length,
3236                                    ipad, sizeof( ipad ), &key_length );
3237         if( status != PSA_SUCCESS )
3238             goto cleanup;
3239     }
3240     /* A 0-length key is not commonly used in HMAC when used as a MAC,
3241      * but it is permitted. It is common when HMAC is used in HKDF, for
3242      * example. Don't call `memcpy` in the 0-length because `key` could be
3243      * an invalid pointer which would make the behavior undefined. */
3244     else if( key_length != 0 )
3245         memcpy( ipad, key, key_length );
3246 
3247     /* ipad contains the key followed by garbage. Xor and fill with 0x36
3248      * to create the ipad value. */
3249     for( i = 0; i < key_length; i++ )
3250         ipad[i] ^= 0x36;
3251     memset( ipad + key_length, 0x36, block_size - key_length );
3252 
3253     /* Copy the key material from ipad to opad, flipping the requisite bits,
3254      * and filling the rest of opad with the requisite constant. */
3255     for( i = 0; i < key_length; i++ )
3256         hmac->opad[i] = ipad[i] ^ 0x36 ^ 0x5C;
3257     memset( hmac->opad + key_length, 0x5C, block_size - key_length );
3258 
3259     status = psa_hash_setup( &hmac->hash_ctx, hash_alg );
3260     if( status != PSA_SUCCESS )
3261         goto cleanup;
3262 
3263     status = psa_hash_update( &hmac->hash_ctx, ipad, block_size );
3264 
3265 cleanup:
3266     vdb_mbedtls_platform_zeroize( ipad, sizeof( ipad ) );
3267 
3268     return( status );
3269 }
3270 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HMAC */
3271 
psa_mac_setup(psa_mac_operation_t * operation,mbedtls_svc_key_id_t key,psa_algorithm_t alg,int is_sign)3272 static psa_status_t psa_mac_setup( psa_mac_operation_t *operation,
3273                                    mbedtls_svc_key_id_t key,
3274                                    psa_algorithm_t alg,
3275                                    int is_sign )
3276 {
3277     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3278     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
3279     psa_key_slot_t *slot;
3280     size_t key_bits;
3281     psa_key_usage_t usage =
3282         is_sign ? PSA_KEY_USAGE_SIGN_HASH : PSA_KEY_USAGE_VERIFY_HASH;
3283     uint8_t truncated = PSA_MAC_TRUNCATED_LENGTH( alg );
3284     psa_algorithm_t full_length_alg = PSA_ALG_FULL_LENGTH_MAC( alg );
3285 
3286     /* A context must be freshly initialized before it can be set up. */
3287     if( operation->alg != 0 )
3288     {
3289         return( PSA_ERROR_BAD_STATE );
3290     }
3291 
3292     status = psa_mac_init( operation, full_length_alg );
3293     if( status != PSA_SUCCESS )
3294         return( status );
3295     if( is_sign )
3296         operation->is_sign = 1;
3297 
3298     status = psa_get_and_lock_transparent_key_slot_with_policy(
3299                  key, &slot, usage, alg );
3300     if( status != PSA_SUCCESS )
3301         goto exit;
3302     key_bits = psa_get_key_slot_bits( slot );
3303 
3304 #if defined(MBEDTLS_CMAC_C)
3305     if( full_length_alg == PSA_ALG_CMAC )
3306     {
3307         const mbedtls_cipher_info_t *cipher_info =
3308             mbedtls_cipher_info_from_psa( full_length_alg,
3309                                           slot->attr.type, key_bits, NULL );
3310         int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3311         if( cipher_info == NULL )
3312         {
3313             status = PSA_ERROR_NOT_SUPPORTED;
3314             goto exit;
3315         }
3316         operation->mac_size = cipher_info->block_size;
3317         ret = psa_cmac_setup( operation, key_bits, slot, cipher_info );
3318         status = mbedtls_to_psa_error( ret );
3319     }
3320     else
3321 #endif /* MBEDTLS_CMAC_C */
3322 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HMAC)
3323     if( PSA_ALG_IS_HMAC( full_length_alg ) )
3324     {
3325         psa_algorithm_t hash_alg = PSA_ALG_HMAC_GET_HASH( alg );
3326         if( hash_alg == 0 )
3327         {
3328             status = PSA_ERROR_NOT_SUPPORTED;
3329             goto exit;
3330         }
3331 
3332         operation->mac_size = PSA_HASH_SIZE( hash_alg );
3333         /* Sanity check. This shouldn't fail on a valid configuration. */
3334         if( operation->mac_size == 0 ||
3335             operation->mac_size > sizeof( operation->ctx.hmac.opad ) )
3336         {
3337             status = PSA_ERROR_NOT_SUPPORTED;
3338             goto exit;
3339         }
3340 
3341         if( slot->attr.type != PSA_KEY_TYPE_HMAC )
3342         {
3343             status = PSA_ERROR_INVALID_ARGUMENT;
3344             goto exit;
3345         }
3346 
3347         status = psa_hmac_setup_internal( &operation->ctx.hmac,
3348                                           slot->data.key.data,
3349                                           slot->data.key.bytes,
3350                                           hash_alg );
3351     }
3352     else
3353 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HMAC */
3354     {
3355         (void) key_bits;
3356         status = PSA_ERROR_NOT_SUPPORTED;
3357     }
3358 
3359     if( truncated == 0 )
3360     {
3361         /* The "normal" case: untruncated algorithm. Nothing to do. */
3362     }
3363     else if( truncated < 4 )
3364     {
3365         /* A very short MAC is too short for security since it can be
3366          * brute-forced. Ancient protocols with 32-bit MACs do exist,
3367          * so we make this our minimum, even though 32 bits is still
3368          * too small for security. */
3369         status = PSA_ERROR_NOT_SUPPORTED;
3370     }
3371     else if( truncated > operation->mac_size )
3372     {
3373         /* It's impossible to "truncate" to a larger length. */
3374         status = PSA_ERROR_INVALID_ARGUMENT;
3375     }
3376     else
3377         operation->mac_size = truncated;
3378 
3379 exit:
3380     if( status != PSA_SUCCESS )
3381     {
3382         psa_mac_abort( operation );
3383     }
3384     else
3385     {
3386         operation->key_set = 1;
3387     }
3388 
3389     unlock_status = psa_unlock_key_slot( slot );
3390 
3391     return( ( status == PSA_SUCCESS ) ? unlock_status : status );
3392 }
3393 
psa_mac_sign_setup(psa_mac_operation_t * operation,mbedtls_svc_key_id_t key,psa_algorithm_t alg)3394 psa_status_t psa_mac_sign_setup( psa_mac_operation_t *operation,
3395                                  mbedtls_svc_key_id_t key,
3396                                  psa_algorithm_t alg )
3397 {
3398     return( psa_mac_setup( operation, key, alg, 1 ) );
3399 }
3400 
psa_mac_verify_setup(psa_mac_operation_t * operation,mbedtls_svc_key_id_t key,psa_algorithm_t alg)3401 psa_status_t psa_mac_verify_setup( psa_mac_operation_t *operation,
3402                                    mbedtls_svc_key_id_t key,
3403                                    psa_algorithm_t alg )
3404 {
3405     return( psa_mac_setup( operation, key, alg, 0 ) );
3406 }
3407 
psa_mac_update(psa_mac_operation_t * operation,const uint8_t * input,size_t input_length)3408 psa_status_t psa_mac_update( psa_mac_operation_t *operation,
3409                              const uint8_t *input,
3410                              size_t input_length )
3411 {
3412     psa_status_t status = PSA_ERROR_BAD_STATE;
3413     if( ! operation->key_set )
3414         return( PSA_ERROR_BAD_STATE );
3415     if( operation->iv_required && ! operation->iv_set )
3416         return( PSA_ERROR_BAD_STATE );
3417     operation->has_input = 1;
3418 
3419 #if defined(MBEDTLS_CMAC_C)
3420     if( operation->alg == PSA_ALG_CMAC )
3421     {
3422         int ret = vdb_mbedtls_cipher_cmac_update( &operation->ctx.cmac,
3423                                               input, input_length );
3424         status = mbedtls_to_psa_error( ret );
3425     }
3426     else
3427 #endif /* MBEDTLS_CMAC_C */
3428 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HMAC)
3429     if( PSA_ALG_IS_HMAC( operation->alg ) )
3430     {
3431         status = psa_hash_update( &operation->ctx.hmac.hash_ctx, input,
3432                                   input_length );
3433     }
3434     else
3435 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HMAC */
3436     {
3437         /* This shouldn't happen if `operation` was initialized by
3438          * a setup function. */
3439         return( PSA_ERROR_BAD_STATE );
3440     }
3441 
3442     if( status != PSA_SUCCESS )
3443         psa_mac_abort( operation );
3444     return( status );
3445 }
3446 
3447 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HMAC)
psa_hmac_finish_internal(psa_hmac_internal_data * hmac,uint8_t * mac,size_t mac_size)3448 static psa_status_t psa_hmac_finish_internal( psa_hmac_internal_data *hmac,
3449                                               uint8_t *mac,
3450                                               size_t mac_size )
3451 {
3452     uint8_t tmp[MBEDTLS_MD_MAX_SIZE];
3453     psa_algorithm_t hash_alg = hmac->hash_ctx.alg;
3454     size_t hash_size = 0;
3455     size_t block_size = psa_get_hash_block_size( hash_alg );
3456     psa_status_t status;
3457 
3458     status = psa_hash_finish( &hmac->hash_ctx, tmp, sizeof( tmp ), &hash_size );
3459     if( status != PSA_SUCCESS )
3460         return( status );
3461     /* From here on, tmp needs to be wiped. */
3462 
3463     status = psa_hash_setup( &hmac->hash_ctx, hash_alg );
3464     if( status != PSA_SUCCESS )
3465         goto exit;
3466 
3467     status = psa_hash_update( &hmac->hash_ctx, hmac->opad, block_size );
3468     if( status != PSA_SUCCESS )
3469         goto exit;
3470 
3471     status = psa_hash_update( &hmac->hash_ctx, tmp, hash_size );
3472     if( status != PSA_SUCCESS )
3473         goto exit;
3474 
3475     status = psa_hash_finish( &hmac->hash_ctx, tmp, sizeof( tmp ), &hash_size );
3476     if( status != PSA_SUCCESS )
3477         goto exit;
3478 
3479     memcpy( mac, tmp, mac_size );
3480 
3481 exit:
3482     vdb_mbedtls_platform_zeroize( tmp, hash_size );
3483     return( status );
3484 }
3485 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HMAC */
3486 
psa_mac_finish_internal(psa_mac_operation_t * operation,uint8_t * mac,size_t mac_size)3487 static psa_status_t psa_mac_finish_internal( psa_mac_operation_t *operation,
3488                                              uint8_t *mac,
3489                                              size_t mac_size )
3490 {
3491     if( ! operation->key_set )
3492         return( PSA_ERROR_BAD_STATE );
3493     if( operation->iv_required && ! operation->iv_set )
3494         return( PSA_ERROR_BAD_STATE );
3495 
3496     if( mac_size < operation->mac_size )
3497         return( PSA_ERROR_BUFFER_TOO_SMALL );
3498 
3499 #if defined(MBEDTLS_CMAC_C)
3500     if( operation->alg == PSA_ALG_CMAC )
3501     {
3502         uint8_t tmp[PSA_MAX_BLOCK_CIPHER_BLOCK_SIZE];
3503         int ret = vdb_mbedtls_cipher_cmac_finish( &operation->ctx.cmac, tmp );
3504         if( ret == 0 )
3505             memcpy( mac, tmp, operation->mac_size );
3506         vdb_mbedtls_platform_zeroize( tmp, sizeof( tmp ) );
3507         return( mbedtls_to_psa_error( ret ) );
3508     }
3509     else
3510 #endif /* MBEDTLS_CMAC_C */
3511 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HMAC)
3512     if( PSA_ALG_IS_HMAC( operation->alg ) )
3513     {
3514         return( psa_hmac_finish_internal( &operation->ctx.hmac,
3515                                           mac, operation->mac_size ) );
3516     }
3517     else
3518 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HMAC */
3519     {
3520         /* This shouldn't happen if `operation` was initialized by
3521          * a setup function. */
3522         return( PSA_ERROR_BAD_STATE );
3523     }
3524 }
3525 
psa_mac_sign_finish(psa_mac_operation_t * operation,uint8_t * mac,size_t mac_size,size_t * mac_length)3526 psa_status_t psa_mac_sign_finish( psa_mac_operation_t *operation,
3527                                   uint8_t *mac,
3528                                   size_t mac_size,
3529                                   size_t *mac_length )
3530 {
3531     psa_status_t status;
3532 
3533     if( operation->alg == 0 )
3534     {
3535         return( PSA_ERROR_BAD_STATE );
3536     }
3537 
3538     /* Fill the output buffer with something that isn't a valid mac
3539      * (barring an attack on the mac and deliberately-crafted input),
3540      * in case the caller doesn't check the return status properly. */
3541     *mac_length = mac_size;
3542     /* If mac_size is 0 then mac may be NULL and then the
3543      * call to memset would have undefined behavior. */
3544     if( mac_size != 0 )
3545         memset( mac, '!', mac_size );
3546 
3547     if( ! operation->is_sign )
3548     {
3549         return( PSA_ERROR_BAD_STATE );
3550     }
3551 
3552     status = psa_mac_finish_internal( operation, mac, mac_size );
3553 
3554     if( status == PSA_SUCCESS )
3555     {
3556         status = psa_mac_abort( operation );
3557         if( status == PSA_SUCCESS )
3558             *mac_length = operation->mac_size;
3559         else
3560             memset( mac, '!', mac_size );
3561     }
3562     else
3563         psa_mac_abort( operation );
3564     return( status );
3565 }
3566 
psa_mac_verify_finish(psa_mac_operation_t * operation,const uint8_t * mac,size_t mac_length)3567 psa_status_t psa_mac_verify_finish( psa_mac_operation_t *operation,
3568                                     const uint8_t *mac,
3569                                     size_t mac_length )
3570 {
3571     uint8_t actual_mac[PSA_MAC_MAX_SIZE];
3572     psa_status_t status;
3573 
3574     if( operation->alg == 0 )
3575     {
3576         return( PSA_ERROR_BAD_STATE );
3577     }
3578 
3579     if( operation->is_sign )
3580     {
3581         return( PSA_ERROR_BAD_STATE );
3582     }
3583     if( operation->mac_size != mac_length )
3584     {
3585         status = PSA_ERROR_INVALID_SIGNATURE;
3586         goto cleanup;
3587     }
3588 
3589     status = psa_mac_finish_internal( operation,
3590                                       actual_mac, sizeof( actual_mac ) );
3591     if( status != PSA_SUCCESS )
3592         goto cleanup;
3593 
3594     if( safer_memcmp( mac, actual_mac, mac_length ) != 0 )
3595         status = PSA_ERROR_INVALID_SIGNATURE;
3596 
3597 cleanup:
3598     if( status == PSA_SUCCESS )
3599         status = psa_mac_abort( operation );
3600     else
3601         psa_mac_abort( operation );
3602 
3603     vdb_mbedtls_platform_zeroize( actual_mac, sizeof( actual_mac ) );
3604 
3605     return( status );
3606 }
3607 
3608 
3609 
3610 /****************************************************************/
3611 /* Asymmetric cryptography */
3612 /****************************************************************/
3613 
3614 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) || \
3615     defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS)
3616 /* Decode the hash algorithm from alg and store the mbedtls encoding in
3617  * md_alg. Verify that the hash length is acceptable. */
psa_rsa_decode_md_type(psa_algorithm_t alg,size_t hash_length,mbedtls_md_type_t * md_alg)3618 static psa_status_t psa_rsa_decode_md_type( psa_algorithm_t alg,
3619                                             size_t hash_length,
3620                                             mbedtls_md_type_t *md_alg )
3621 {
3622     psa_algorithm_t hash_alg = PSA_ALG_SIGN_GET_HASH( alg );
3623     const mbedtls_md_info_t *md_info = mbedtls_md_info_from_psa( hash_alg );
3624     *md_alg = vdb_mbedtls_md_get_type( md_info );
3625 
3626     /* The Mbed TLS RSA module uses an unsigned int for hash length
3627      * parameters. Validate that it fits so that we don't risk an
3628      * overflow later. */
3629 #if SIZE_MAX > UINT_MAX
3630     if( hash_length > UINT_MAX )
3631         return( PSA_ERROR_INVALID_ARGUMENT );
3632 #endif
3633 
3634 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN)
3635     /* For PKCS#1 v1.5 signature, if using a hash, the hash length
3636      * must be correct. */
3637     if( PSA_ALG_IS_RSA_PKCS1V15_SIGN( alg ) &&
3638         alg != PSA_ALG_RSA_PKCS1V15_SIGN_RAW )
3639     {
3640         if( md_info == NULL )
3641             return( PSA_ERROR_NOT_SUPPORTED );
3642         if( vdb_mbedtls_md_get_size( md_info ) != hash_length )
3643             return( PSA_ERROR_INVALID_ARGUMENT );
3644     }
3645 #endif /* MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN */
3646 
3647 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS)
3648     /* PSS requires a hash internally. */
3649     if( PSA_ALG_IS_RSA_PSS( alg ) )
3650     {
3651         if( md_info == NULL )
3652             return( PSA_ERROR_NOT_SUPPORTED );
3653     }
3654 #endif /* MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS */
3655 
3656     return( PSA_SUCCESS );
3657 }
3658 
psa_rsa_sign(mbedtls_rsa_context * rsa,psa_algorithm_t alg,const uint8_t * hash,size_t hash_length,uint8_t * signature,size_t signature_size,size_t * signature_length)3659 static psa_status_t psa_rsa_sign( mbedtls_rsa_context *rsa,
3660                                   psa_algorithm_t alg,
3661                                   const uint8_t *hash,
3662                                   size_t hash_length,
3663                                   uint8_t *signature,
3664                                   size_t signature_size,
3665                                   size_t *signature_length )
3666 {
3667     psa_status_t status;
3668     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3669     mbedtls_md_type_t md_alg;
3670 
3671     status = psa_rsa_decode_md_type( alg, hash_length, &md_alg );
3672     if( status != PSA_SUCCESS )
3673         return( status );
3674 
3675     if( signature_size < vdb_mbedtls_rsa_get_len( rsa ) )
3676         return( PSA_ERROR_BUFFER_TOO_SMALL );
3677 
3678 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN)
3679     if( PSA_ALG_IS_RSA_PKCS1V15_SIGN( alg ) )
3680     {
3681         vdb_mbedtls_rsa_set_padding( rsa, MBEDTLS_RSA_PKCS_V15,
3682                                  MBEDTLS_MD_NONE );
3683         ret = vdb_mbedtls_rsa_pkcs1_sign( rsa,
3684                                       vdb_mbedtls_ctr_drbg_random,
3685                                       &global_data.ctr_drbg,
3686                                       MBEDTLS_RSA_PRIVATE,
3687                                       md_alg,
3688                                       (unsigned int) hash_length,
3689                                       hash,
3690                                       signature );
3691     }
3692     else
3693 #endif /* MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN */
3694 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS)
3695     if( PSA_ALG_IS_RSA_PSS( alg ) )
3696     {
3697         vdb_mbedtls_rsa_set_padding( rsa, MBEDTLS_RSA_PKCS_V21, md_alg );
3698         ret = vdb_mbedtls_rsa_rsassa_pss_sign( rsa,
3699                                            vdb_mbedtls_ctr_drbg_random,
3700                                            &global_data.ctr_drbg,
3701                                            MBEDTLS_RSA_PRIVATE,
3702                                            MBEDTLS_MD_NONE,
3703                                            (unsigned int) hash_length,
3704                                            hash,
3705                                            signature );
3706     }
3707     else
3708 #endif /* MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS */
3709     {
3710         return( PSA_ERROR_INVALID_ARGUMENT );
3711     }
3712 
3713     if( ret == 0 )
3714         *signature_length = vdb_mbedtls_rsa_get_len( rsa );
3715     return( mbedtls_to_psa_error( ret ) );
3716 }
3717 
psa_rsa_verify(mbedtls_rsa_context * rsa,psa_algorithm_t alg,const uint8_t * hash,size_t hash_length,const uint8_t * signature,size_t signature_length)3718 static psa_status_t psa_rsa_verify( mbedtls_rsa_context *rsa,
3719                                     psa_algorithm_t alg,
3720                                     const uint8_t *hash,
3721                                     size_t hash_length,
3722                                     const uint8_t *signature,
3723                                     size_t signature_length )
3724 {
3725     psa_status_t status;
3726     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3727     mbedtls_md_type_t md_alg;
3728 
3729     status = psa_rsa_decode_md_type( alg, hash_length, &md_alg );
3730     if( status != PSA_SUCCESS )
3731         return( status );
3732 
3733     if( signature_length != vdb_mbedtls_rsa_get_len( rsa ) )
3734         return( PSA_ERROR_INVALID_SIGNATURE );
3735 
3736 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN)
3737     if( PSA_ALG_IS_RSA_PKCS1V15_SIGN( alg ) )
3738     {
3739         vdb_mbedtls_rsa_set_padding( rsa, MBEDTLS_RSA_PKCS_V15,
3740                                  MBEDTLS_MD_NONE );
3741         ret = vdb_mbedtls_rsa_pkcs1_verify( rsa,
3742                                         vdb_mbedtls_ctr_drbg_random,
3743                                         &global_data.ctr_drbg,
3744                                         MBEDTLS_RSA_PUBLIC,
3745                                         md_alg,
3746                                         (unsigned int) hash_length,
3747                                         hash,
3748                                         signature );
3749     }
3750     else
3751 #endif /* MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN */
3752 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS)
3753     if( PSA_ALG_IS_RSA_PSS( alg ) )
3754     {
3755         vdb_mbedtls_rsa_set_padding( rsa, MBEDTLS_RSA_PKCS_V21, md_alg );
3756         ret = vdb_mbedtls_rsa_rsassa_pss_verify( rsa,
3757                                              vdb_mbedtls_ctr_drbg_random,
3758                                              &global_data.ctr_drbg,
3759                                              MBEDTLS_RSA_PUBLIC,
3760                                              MBEDTLS_MD_NONE,
3761                                              (unsigned int) hash_length,
3762                                              hash,
3763                                              signature );
3764     }
3765     else
3766 #endif /* MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS */
3767     {
3768         return( PSA_ERROR_INVALID_ARGUMENT );
3769     }
3770 
3771     /* Mbed TLS distinguishes "invalid padding" from "valid padding but
3772      * the rest of the signature is invalid". This has little use in
3773      * practice and PSA doesn't report this distinction. */
3774     if( ret == MBEDTLS_ERR_RSA_INVALID_PADDING )
3775         return( PSA_ERROR_INVALID_SIGNATURE );
3776     return( mbedtls_to_psa_error( ret ) );
3777 }
3778 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) ||
3779         * defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS) */
3780 
3781 #if defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
3782     defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)
3783 /* `ecp` cannot be const because `ecp->grp` needs to be non-const
3784  * for vdb_mbedtls_ecdsa_sign() and vdb_mbedtls_ecdsa_sign_det()
3785  * (even though these functions don't modify it). */
psa_ecdsa_sign(mbedtls_ecp_keypair * ecp,psa_algorithm_t alg,const uint8_t * hash,size_t hash_length,uint8_t * signature,size_t signature_size,size_t * signature_length)3786 static psa_status_t psa_ecdsa_sign( mbedtls_ecp_keypair *ecp,
3787                                     psa_algorithm_t alg,
3788                                     const uint8_t *hash,
3789                                     size_t hash_length,
3790                                     uint8_t *signature,
3791                                     size_t signature_size,
3792                                     size_t *signature_length )
3793 {
3794     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3795     mbedtls_mpi r, s;
3796     size_t curve_bytes = PSA_BITS_TO_BYTES( ecp->grp.pbits );
3797     vdb_mbedtls_mpi_init( &r );
3798     vdb_mbedtls_mpi_init( &s );
3799 
3800     if( signature_size < 2 * curve_bytes )
3801     {
3802         ret = MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL;
3803         goto cleanup;
3804     }
3805 
3806 #if defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)
3807     if( PSA_ALG_DSA_IS_DETERMINISTIC( alg ) )
3808     {
3809         psa_algorithm_t hash_alg = PSA_ALG_SIGN_GET_HASH( alg );
3810         const mbedtls_md_info_t *md_info = mbedtls_md_info_from_psa( hash_alg );
3811         mbedtls_md_type_t md_alg = vdb_mbedtls_md_get_type( md_info );
3812         MBEDTLS_MPI_CHK( vdb_mbedtls_ecdsa_sign_det_ext( &ecp->grp, &r, &s,
3813                                                      &ecp->d, hash,
3814                                                      hash_length, md_alg,
3815                                                      vdb_mbedtls_ctr_drbg_random,
3816                                                      &global_data.ctr_drbg ) );
3817     }
3818     else
3819 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) */
3820     {
3821         (void) alg;
3822         MBEDTLS_MPI_CHK( vdb_mbedtls_ecdsa_sign( &ecp->grp, &r, &s, &ecp->d,
3823                                              hash, hash_length,
3824                                              vdb_mbedtls_ctr_drbg_random,
3825                                              &global_data.ctr_drbg ) );
3826     }
3827 
3828     MBEDTLS_MPI_CHK( vdb_mbedtls_mpi_write_binary( &r,
3829                                                signature,
3830                                                curve_bytes ) );
3831     MBEDTLS_MPI_CHK( vdb_mbedtls_mpi_write_binary( &s,
3832                                                signature + curve_bytes,
3833                                                curve_bytes ) );
3834 
3835 cleanup:
3836     vdb_mbedtls_mpi_free( &r );
3837     vdb_mbedtls_mpi_free( &s );
3838     if( ret == 0 )
3839         *signature_length = 2 * curve_bytes;
3840     return( mbedtls_to_psa_error( ret ) );
3841 }
3842 
psa_ecdsa_verify(mbedtls_ecp_keypair * ecp,const uint8_t * hash,size_t hash_length,const uint8_t * signature,size_t signature_length)3843 static psa_status_t psa_ecdsa_verify( mbedtls_ecp_keypair *ecp,
3844                                       const uint8_t *hash,
3845                                       size_t hash_length,
3846                                       const uint8_t *signature,
3847                                       size_t signature_length )
3848 {
3849     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3850     mbedtls_mpi r, s;
3851     size_t curve_bytes = PSA_BITS_TO_BYTES( ecp->grp.pbits );
3852     vdb_mbedtls_mpi_init( &r );
3853     vdb_mbedtls_mpi_init( &s );
3854 
3855     if( signature_length != 2 * curve_bytes )
3856         return( PSA_ERROR_INVALID_SIGNATURE );
3857 
3858     MBEDTLS_MPI_CHK( vdb_mbedtls_mpi_read_binary( &r,
3859                                               signature,
3860                                               curve_bytes ) );
3861     MBEDTLS_MPI_CHK( vdb_mbedtls_mpi_read_binary( &s,
3862                                               signature + curve_bytes,
3863                                               curve_bytes ) );
3864 
3865     /* Check whether the public part is loaded. If not, load it. */
3866     if( vdb_mbedtls_ecp_is_zero( &ecp->Q ) )
3867     {
3868         MBEDTLS_MPI_CHK(
3869             vdb_mbedtls_ecp_mul( &ecp->grp, &ecp->Q, &ecp->d, &ecp->grp.G,
3870                              vdb_mbedtls_ctr_drbg_random, &global_data.ctr_drbg ) );
3871     }
3872 
3873     ret = vdb_mbedtls_ecdsa_verify( &ecp->grp, hash, hash_length,
3874                                 &ecp->Q, &r, &s );
3875 
3876 cleanup:
3877     vdb_mbedtls_mpi_free( &r );
3878     vdb_mbedtls_mpi_free( &s );
3879     return( mbedtls_to_psa_error( ret ) );
3880 }
3881 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
3882         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) */
3883 
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)3884 psa_status_t psa_sign_hash( mbedtls_svc_key_id_t key,
3885                             psa_algorithm_t alg,
3886                             const uint8_t *hash,
3887                             size_t hash_length,
3888                             uint8_t *signature,
3889                             size_t signature_size,
3890                             size_t *signature_length )
3891 {
3892     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3893     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
3894     psa_key_slot_t *slot;
3895 
3896     *signature_length = signature_size;
3897     /* Immediately reject a zero-length signature buffer. This guarantees
3898      * that signature must be a valid pointer. (On the other hand, the hash
3899      * buffer can in principle be empty since it doesn't actually have
3900      * to be a hash.) */
3901     if( signature_size == 0 )
3902         return( PSA_ERROR_BUFFER_TOO_SMALL );
3903 
3904     status = psa_get_and_lock_key_slot_with_policy( key, &slot,
3905                                                     PSA_KEY_USAGE_SIGN_HASH,
3906                                                     alg );
3907     if( status != PSA_SUCCESS )
3908         goto exit;
3909     if( ! PSA_KEY_TYPE_IS_KEY_PAIR( slot->attr.type ) )
3910     {
3911         status = PSA_ERROR_INVALID_ARGUMENT;
3912         goto exit;
3913     }
3914 
3915     /* Try any of the available accelerators first */
3916     status = psa_driver_wrapper_sign_hash( slot,
3917                                            alg,
3918                                            hash,
3919                                            hash_length,
3920                                            signature,
3921                                            signature_size,
3922                                            signature_length );
3923     if( status != PSA_ERROR_NOT_SUPPORTED ||
3924         psa_key_lifetime_is_external( slot->attr.lifetime ) )
3925         goto exit;
3926 
3927     /* If the operation was not supported by any accelerator, try fallback. */
3928 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) || \
3929     defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS)
3930     if( slot->attr.type == PSA_KEY_TYPE_RSA_KEY_PAIR )
3931     {
3932         mbedtls_rsa_context *rsa = NULL;
3933 
3934         status = psa_load_rsa_representation( slot->attr.type,
3935                                               slot->data.key.data,
3936                                               slot->data.key.bytes,
3937                                               &rsa );
3938         if( status != PSA_SUCCESS )
3939             goto exit;
3940 
3941         status = psa_rsa_sign( rsa,
3942                                alg,
3943                                hash, hash_length,
3944                                signature, signature_size,
3945                                signature_length );
3946 
3947         vdb_mbedtls_rsa_free( rsa );
3948         vdb_mbedtls_free( rsa );
3949     }
3950     else
3951 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) ||
3952         * defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS) */
3953     if( PSA_KEY_TYPE_IS_ECC( slot->attr.type ) )
3954     {
3955 #if defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
3956     defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)
3957         if(
3958 #if defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)
3959             PSA_ALG_IS_ECDSA( alg )
3960 #else
3961             PSA_ALG_IS_RANDOMIZED_ECDSA( alg )
3962 #endif
3963             )
3964         {
3965             mbedtls_ecp_keypair *ecp = NULL;
3966             status = psa_load_ecp_representation( slot->attr.type,
3967                                                   slot->data.key.data,
3968                                                   slot->data.key.bytes,
3969                                                   &ecp );
3970             if( status != PSA_SUCCESS )
3971                 goto exit;
3972             status = psa_ecdsa_sign( ecp,
3973                                      alg,
3974                                      hash, hash_length,
3975                                      signature, signature_size,
3976                                      signature_length );
3977             vdb_mbedtls_ecp_keypair_free( ecp );
3978             vdb_mbedtls_free( ecp );
3979         }
3980         else
3981 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
3982         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) */
3983         {
3984             status = PSA_ERROR_INVALID_ARGUMENT;
3985         }
3986     }
3987     else
3988     {
3989         status = PSA_ERROR_NOT_SUPPORTED;
3990     }
3991 
3992 exit:
3993     /* Fill the unused part of the output buffer (the whole buffer on error,
3994      * the trailing part on success) with something that isn't a valid mac
3995      * (barring an attack on the mac and deliberately-crafted input),
3996      * in case the caller doesn't check the return status properly. */
3997     if( status == PSA_SUCCESS )
3998         memset( signature + *signature_length, '!',
3999                 signature_size - *signature_length );
4000     else
4001         memset( signature, '!', signature_size );
4002     /* If signature_size is 0 then we have nothing to do. We must not call
4003      * memset because signature may be NULL in this case. */
4004 
4005     unlock_status = psa_unlock_key_slot( slot );
4006 
4007     return( ( status == PSA_SUCCESS ) ? unlock_status : status );
4008 }
4009 
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)4010 psa_status_t psa_verify_hash( mbedtls_svc_key_id_t key,
4011                               psa_algorithm_t alg,
4012                               const uint8_t *hash,
4013                               size_t hash_length,
4014                               const uint8_t *signature,
4015                               size_t signature_length )
4016 {
4017     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4018     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
4019     psa_key_slot_t *slot;
4020 
4021     status = psa_get_and_lock_key_slot_with_policy( key, &slot,
4022                                                     PSA_KEY_USAGE_VERIFY_HASH,
4023                                                     alg );
4024     if( status != PSA_SUCCESS )
4025         return( status );
4026 
4027     /* Try any of the available accelerators first */
4028     status = psa_driver_wrapper_verify_hash( slot,
4029                                              alg,
4030                                              hash,
4031                                              hash_length,
4032                                              signature,
4033                                              signature_length );
4034     if( status != PSA_ERROR_NOT_SUPPORTED ||
4035         psa_key_lifetime_is_external( slot->attr.lifetime ) )
4036         goto exit;
4037 
4038 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) || \
4039     defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS)
4040     if( PSA_KEY_TYPE_IS_RSA( slot->attr.type ) )
4041     {
4042         mbedtls_rsa_context *rsa = NULL;
4043 
4044         status = psa_load_rsa_representation( slot->attr.type,
4045                                               slot->data.key.data,
4046                                               slot->data.key.bytes,
4047                                               &rsa );
4048         if( status != PSA_SUCCESS )
4049             goto exit;
4050 
4051         status = psa_rsa_verify( rsa,
4052                                  alg,
4053                                  hash, hash_length,
4054                                  signature, signature_length );
4055         vdb_mbedtls_rsa_free( rsa );
4056         vdb_mbedtls_free( rsa );
4057         goto exit;
4058     }
4059     else
4060 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) ||
4061         * defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS) */
4062     if( PSA_KEY_TYPE_IS_ECC( slot->attr.type ) )
4063     {
4064 #if defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
4065     defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)
4066         if( PSA_ALG_IS_ECDSA( alg ) )
4067         {
4068             mbedtls_ecp_keypair *ecp = NULL;
4069             status = psa_load_ecp_representation( slot->attr.type,
4070                                                   slot->data.key.data,
4071                                                   slot->data.key.bytes,
4072                                                   &ecp );
4073             if( status != PSA_SUCCESS )
4074                 goto exit;
4075             status = psa_ecdsa_verify( ecp,
4076                                        hash, hash_length,
4077                                        signature, signature_length );
4078             vdb_mbedtls_ecp_keypair_free( ecp );
4079             vdb_mbedtls_free( ecp );
4080             goto exit;
4081         }
4082         else
4083 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
4084         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) */
4085         {
4086             status =  PSA_ERROR_INVALID_ARGUMENT;
4087             goto exit;
4088         }
4089     }
4090     else
4091     {
4092         status = PSA_ERROR_NOT_SUPPORTED;
4093     }
4094 
4095 exit:
4096     unlock_status = psa_unlock_key_slot( slot );
4097 
4098     return( ( status == PSA_SUCCESS ) ? unlock_status : status );
4099 }
4100 
4101 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
psa_rsa_oaep_set_padding_mode(psa_algorithm_t alg,mbedtls_rsa_context * rsa)4102 static void psa_rsa_oaep_set_padding_mode( psa_algorithm_t alg,
4103                                            mbedtls_rsa_context *rsa )
4104 {
4105     psa_algorithm_t hash_alg = PSA_ALG_RSA_OAEP_GET_HASH( alg );
4106     const mbedtls_md_info_t *md_info = mbedtls_md_info_from_psa( hash_alg );
4107     mbedtls_md_type_t md_alg = vdb_mbedtls_md_get_type( md_info );
4108     vdb_mbedtls_rsa_set_padding( rsa, MBEDTLS_RSA_PKCS_V21, md_alg );
4109 }
4110 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP) */
4111 
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)4112 psa_status_t psa_asymmetric_encrypt( mbedtls_svc_key_id_t key,
4113                                      psa_algorithm_t alg,
4114                                      const uint8_t *input,
4115                                      size_t input_length,
4116                                      const uint8_t *salt,
4117                                      size_t salt_length,
4118                                      uint8_t *output,
4119                                      size_t output_size,
4120                                      size_t *output_length )
4121 {
4122     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4123     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
4124     psa_key_slot_t *slot;
4125 
4126     (void) input;
4127     (void) input_length;
4128     (void) salt;
4129     (void) output;
4130     (void) output_size;
4131 
4132     *output_length = 0;
4133 
4134     if( ! PSA_ALG_IS_RSA_OAEP( alg ) && salt_length != 0 )
4135         return( PSA_ERROR_INVALID_ARGUMENT );
4136 
4137     status = psa_get_and_lock_transparent_key_slot_with_policy(
4138                  key, &slot, PSA_KEY_USAGE_ENCRYPT, alg );
4139     if( status != PSA_SUCCESS )
4140         return( status );
4141     if( ! ( PSA_KEY_TYPE_IS_PUBLIC_KEY( slot->attr.type ) ||
4142             PSA_KEY_TYPE_IS_KEY_PAIR( slot->attr.type ) ) )
4143     {
4144         status = PSA_ERROR_INVALID_ARGUMENT;
4145         goto exit;
4146     }
4147 
4148 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT) || \
4149     defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
4150     if( PSA_KEY_TYPE_IS_RSA( slot->attr.type ) )
4151     {
4152         mbedtls_rsa_context *rsa = NULL;
4153         status = psa_load_rsa_representation( slot->attr.type,
4154                                               slot->data.key.data,
4155                                               slot->data.key.bytes,
4156                                               &rsa );
4157         if( status != PSA_SUCCESS )
4158             goto rsa_exit;
4159 
4160         if( output_size < vdb_mbedtls_rsa_get_len( rsa ) )
4161         {
4162             status = PSA_ERROR_BUFFER_TOO_SMALL;
4163             goto rsa_exit;
4164         }
4165 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT)
4166         if( alg == PSA_ALG_RSA_PKCS1V15_CRYPT )
4167         {
4168             status = mbedtls_to_psa_error(
4169                     vdb_mbedtls_rsa_pkcs1_encrypt( rsa,
4170                                                vdb_mbedtls_ctr_drbg_random,
4171                                                &global_data.ctr_drbg,
4172                                                MBEDTLS_RSA_PUBLIC,
4173                                                input_length,
4174                                                input,
4175                                                output ) );
4176         }
4177         else
4178 #endif /* MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT */
4179 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
4180         if( PSA_ALG_IS_RSA_OAEP( alg ) )
4181         {
4182             psa_rsa_oaep_set_padding_mode( alg, rsa );
4183             status = mbedtls_to_psa_error(
4184                 vdb_mbedtls_rsa_rsaes_oaep_encrypt( rsa,
4185                                                 vdb_mbedtls_ctr_drbg_random,
4186                                                 &global_data.ctr_drbg,
4187                                                 MBEDTLS_RSA_PUBLIC,
4188                                                 salt, salt_length,
4189                                                 input_length,
4190                                                 input,
4191                                                 output ) );
4192         }
4193         else
4194 #endif /* MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP */
4195         {
4196             status = PSA_ERROR_INVALID_ARGUMENT;
4197             goto rsa_exit;
4198         }
4199 rsa_exit:
4200         if( status == PSA_SUCCESS )
4201             *output_length = vdb_mbedtls_rsa_get_len( rsa );
4202 
4203         vdb_mbedtls_rsa_free( rsa );
4204         vdb_mbedtls_free( rsa );
4205     }
4206     else
4207 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT) ||
4208         * defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP) */
4209     {
4210         status = PSA_ERROR_NOT_SUPPORTED;
4211     }
4212 
4213 exit:
4214     unlock_status = psa_unlock_key_slot( slot );
4215 
4216     return( ( status == PSA_SUCCESS ) ? unlock_status : status );
4217 }
4218 
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)4219 psa_status_t psa_asymmetric_decrypt( mbedtls_svc_key_id_t key,
4220                                      psa_algorithm_t alg,
4221                                      const uint8_t *input,
4222                                      size_t input_length,
4223                                      const uint8_t *salt,
4224                                      size_t salt_length,
4225                                      uint8_t *output,
4226                                      size_t output_size,
4227                                      size_t *output_length )
4228 {
4229     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4230     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
4231     psa_key_slot_t *slot;
4232 
4233     (void) input;
4234     (void) input_length;
4235     (void) salt;
4236     (void) output;
4237     (void) output_size;
4238 
4239     *output_length = 0;
4240 
4241     if( ! PSA_ALG_IS_RSA_OAEP( alg ) && salt_length != 0 )
4242         return( PSA_ERROR_INVALID_ARGUMENT );
4243 
4244     status = psa_get_and_lock_transparent_key_slot_with_policy(
4245                  key, &slot, PSA_KEY_USAGE_DECRYPT, alg );
4246     if( status != PSA_SUCCESS )
4247         return( status );
4248     if( ! PSA_KEY_TYPE_IS_KEY_PAIR( slot->attr.type ) )
4249     {
4250         status = PSA_ERROR_INVALID_ARGUMENT;
4251         goto exit;
4252     }
4253 
4254 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT) || \
4255     defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
4256     if( slot->attr.type == PSA_KEY_TYPE_RSA_KEY_PAIR )
4257     {
4258         mbedtls_rsa_context *rsa = NULL;
4259         status = psa_load_rsa_representation( slot->attr.type,
4260                                               slot->data.key.data,
4261                                               slot->data.key.bytes,
4262                                               &rsa );
4263         if( status != PSA_SUCCESS )
4264             goto exit;
4265 
4266         if( input_length != vdb_mbedtls_rsa_get_len( rsa ) )
4267         {
4268             status = PSA_ERROR_INVALID_ARGUMENT;
4269             goto rsa_exit;
4270         }
4271 
4272 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT)
4273         if( alg == PSA_ALG_RSA_PKCS1V15_CRYPT )
4274         {
4275             status = mbedtls_to_psa_error(
4276                 vdb_mbedtls_rsa_pkcs1_decrypt( rsa,
4277                                            vdb_mbedtls_ctr_drbg_random,
4278                                            &global_data.ctr_drbg,
4279                                            MBEDTLS_RSA_PRIVATE,
4280                                            output_length,
4281                                            input,
4282                                            output,
4283                                            output_size ) );
4284         }
4285         else
4286 #endif /* MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT */
4287 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
4288         if( PSA_ALG_IS_RSA_OAEP( alg ) )
4289         {
4290             psa_rsa_oaep_set_padding_mode( alg, rsa );
4291             status = mbedtls_to_psa_error(
4292                 vdb_mbedtls_rsa_rsaes_oaep_decrypt( rsa,
4293                                                 vdb_mbedtls_ctr_drbg_random,
4294                                                 &global_data.ctr_drbg,
4295                                                 MBEDTLS_RSA_PRIVATE,
4296                                                 salt, salt_length,
4297                                                 output_length,
4298                                                 input,
4299                                                 output,
4300                                                 output_size ) );
4301         }
4302         else
4303 #endif /* MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP */
4304         {
4305             status = PSA_ERROR_INVALID_ARGUMENT;
4306         }
4307 
4308 rsa_exit:
4309         vdb_mbedtls_rsa_free( rsa );
4310         vdb_mbedtls_free( rsa );
4311     }
4312     else
4313 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT) ||
4314         * defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP) */
4315     {
4316         status = PSA_ERROR_NOT_SUPPORTED;
4317     }
4318 
4319 exit:
4320     unlock_status = psa_unlock_key_slot( slot );
4321 
4322     return( ( status == PSA_SUCCESS ) ? unlock_status : status );
4323 }
4324 
4325 
4326 
4327 /****************************************************************/
4328 /* Symmetric cryptography */
4329 /****************************************************************/
4330 
psa_cipher_setup(psa_cipher_operation_t * operation,mbedtls_svc_key_id_t key,psa_algorithm_t alg,mbedtls_operation_t cipher_operation)4331 static psa_status_t psa_cipher_setup( psa_cipher_operation_t *operation,
4332                                       mbedtls_svc_key_id_t key,
4333                                       psa_algorithm_t alg,
4334                                       mbedtls_operation_t cipher_operation )
4335 {
4336     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4337     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
4338     int ret = 0;
4339     psa_key_slot_t *slot;
4340     size_t key_bits;
4341     const mbedtls_cipher_info_t *cipher_info = NULL;
4342     psa_key_usage_t usage = ( cipher_operation == MBEDTLS_ENCRYPT ?
4343                               PSA_KEY_USAGE_ENCRYPT :
4344                               PSA_KEY_USAGE_DECRYPT );
4345 
4346     /* A context must be freshly initialized before it can be set up. */
4347     if( operation->alg != 0 )
4348         return( PSA_ERROR_BAD_STATE );
4349 
4350     /* The requested algorithm must be one that can be processed by cipher. */
4351     if( ! PSA_ALG_IS_CIPHER( alg ) )
4352         return( PSA_ERROR_INVALID_ARGUMENT );
4353 
4354     /* Fetch key material from key storage. */
4355     status = psa_get_and_lock_key_slot_with_policy( key, &slot, usage, alg );
4356     if( status != PSA_SUCCESS )
4357         goto exit;
4358 
4359     /* Initialize the operation struct members, except for alg. The alg member
4360      * is used to indicate to psa_cipher_abort that there are resources to free,
4361      * so we only set it after resources have been allocated/initialized. */
4362     operation->key_set = 0;
4363     operation->iv_set = 0;
4364     operation->mbedtls_in_use = 0;
4365     operation->iv_size = 0;
4366     operation->block_size = 0;
4367     if( alg == PSA_ALG_ECB_NO_PADDING )
4368         operation->iv_required = 0;
4369     else
4370         operation->iv_required = 1;
4371 
4372     /* Try doing the operation through a driver before using software fallback. */
4373     if( cipher_operation == MBEDTLS_ENCRYPT )
4374         status = psa_driver_wrapper_cipher_encrypt_setup( &operation->ctx.driver,
4375                                                           slot,
4376                                                           alg );
4377     else
4378         status = psa_driver_wrapper_cipher_decrypt_setup( &operation->ctx.driver,
4379                                                           slot,
4380                                                           alg );
4381 
4382     if( status == PSA_SUCCESS )
4383     {
4384         /* Once the driver context is initialised, it needs to be freed using
4385         * psa_cipher_abort. Indicate this through setting alg. */
4386         operation->alg = alg;
4387     }
4388 
4389     if( status != PSA_ERROR_NOT_SUPPORTED ||
4390         psa_key_lifetime_is_external( slot->attr.lifetime ) )
4391         goto exit;
4392 
4393     /* Proceed with initializing an mbed TLS cipher context if no driver is
4394      * available for the given algorithm & key. */
4395     vdb_mbedtls_cipher_init( &operation->ctx.cipher );
4396 
4397     /* Once the cipher context is initialised, it needs to be freed using
4398      * psa_cipher_abort. Indicate there is something to be freed through setting
4399      * alg, and indicate the operation is being done using mbedtls crypto through
4400      * setting mbedtls_in_use. */
4401     operation->alg = alg;
4402     operation->mbedtls_in_use = 1;
4403 
4404     key_bits = psa_get_key_slot_bits( slot );
4405     cipher_info = mbedtls_cipher_info_from_psa( alg, slot->attr.type, key_bits, NULL );
4406     if( cipher_info == NULL )
4407     {
4408         status = PSA_ERROR_NOT_SUPPORTED;
4409         goto exit;
4410     }
4411 
4412     ret = vdb_mbedtls_cipher_setup( &operation->ctx.cipher, cipher_info );
4413     if( ret != 0 )
4414         goto exit;
4415 
4416 #if defined(MBEDTLS_DES_C)
4417     if( slot->attr.type == PSA_KEY_TYPE_DES && key_bits == 128 )
4418     {
4419         /* Two-key Triple-DES is 3-key Triple-DES with K1=K3 */
4420         uint8_t keys[24];
4421         memcpy( keys, slot->data.key.data, 16 );
4422         memcpy( keys + 16, slot->data.key.data, 8 );
4423         ret = vdb_mbedtls_cipher_setkey( &operation->ctx.cipher,
4424                                      keys,
4425                                      192, cipher_operation );
4426     }
4427     else
4428 #endif
4429     {
4430         ret = vdb_mbedtls_cipher_setkey( &operation->ctx.cipher,
4431                                      slot->data.key.data,
4432                                      (int) key_bits, cipher_operation );
4433     }
4434     if( ret != 0 )
4435         goto exit;
4436 
4437 #if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING)
4438     switch( alg )
4439     {
4440         case PSA_ALG_CBC_NO_PADDING:
4441             ret = vdb_mbedtls_cipher_set_padding_mode( &operation->ctx.cipher,
4442                                                    MBEDTLS_PADDING_NONE );
4443             break;
4444         case PSA_ALG_CBC_PKCS7:
4445             ret = vdb_mbedtls_cipher_set_padding_mode( &operation->ctx.cipher,
4446                                                    MBEDTLS_PADDING_PKCS7 );
4447             break;
4448         default:
4449             /* The algorithm doesn't involve padding. */
4450             ret = 0;
4451             break;
4452     }
4453     if( ret != 0 )
4454         goto exit;
4455 #endif //MBEDTLS_CIPHER_MODE_WITH_PADDING
4456 
4457     operation->block_size = ( PSA_ALG_IS_STREAM_CIPHER( alg ) ? 1 :
4458                               PSA_BLOCK_CIPHER_BLOCK_SIZE( slot->attr.type ) );
4459     if( ( alg & PSA_ALG_CIPHER_FROM_BLOCK_FLAG ) != 0 &&
4460         alg != PSA_ALG_ECB_NO_PADDING )
4461     {
4462         operation->iv_size = PSA_BLOCK_CIPHER_BLOCK_SIZE( slot->attr.type );
4463     }
4464 #if defined(MBEDTLS_CHACHA20_C)
4465     else
4466     if( alg == PSA_ALG_STREAM_CIPHER && slot->attr.type == PSA_KEY_TYPE_CHACHA20 )
4467         operation->iv_size = 12;
4468 #endif
4469 
4470     status = PSA_SUCCESS;
4471 
4472 exit:
4473     if( ret != 0 )
4474         status = mbedtls_to_psa_error( ret );
4475     if( status == PSA_SUCCESS )
4476     {
4477         /* Update operation flags for both driver and software implementations */
4478         operation->key_set = 1;
4479     }
4480     else
4481         psa_cipher_abort( operation );
4482 
4483     unlock_status = psa_unlock_key_slot( slot );
4484 
4485     return( ( status == PSA_SUCCESS ) ? unlock_status : status );
4486 }
4487 
psa_cipher_encrypt_setup(psa_cipher_operation_t * operation,mbedtls_svc_key_id_t key,psa_algorithm_t alg)4488 psa_status_t psa_cipher_encrypt_setup( psa_cipher_operation_t *operation,
4489                                        mbedtls_svc_key_id_t key,
4490                                        psa_algorithm_t alg )
4491 {
4492     return( psa_cipher_setup( operation, key, alg, MBEDTLS_ENCRYPT ) );
4493 }
4494 
psa_cipher_decrypt_setup(psa_cipher_operation_t * operation,mbedtls_svc_key_id_t key,psa_algorithm_t alg)4495 psa_status_t psa_cipher_decrypt_setup( psa_cipher_operation_t *operation,
4496                                        mbedtls_svc_key_id_t key,
4497                                        psa_algorithm_t alg )
4498 {
4499     return( psa_cipher_setup( operation, key, alg, MBEDTLS_DECRYPT ) );
4500 }
4501 
psa_cipher_generate_iv(psa_cipher_operation_t * operation,uint8_t * iv,size_t iv_size,size_t * iv_length)4502 psa_status_t psa_cipher_generate_iv( psa_cipher_operation_t *operation,
4503                                      uint8_t *iv,
4504                                      size_t iv_size,
4505                                      size_t *iv_length )
4506 {
4507     psa_status_t status;
4508     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
4509     if( operation->iv_set || ! operation->iv_required )
4510     {
4511         return( PSA_ERROR_BAD_STATE );
4512     }
4513 
4514     if( operation->mbedtls_in_use == 0 )
4515     {
4516         status = psa_driver_wrapper_cipher_generate_iv( &operation->ctx.driver,
4517                                                         iv,
4518                                                         iv_size,
4519                                                         iv_length );
4520         goto exit;
4521     }
4522 
4523     if( iv_size < operation->iv_size )
4524     {
4525         status = PSA_ERROR_BUFFER_TOO_SMALL;
4526         goto exit;
4527     }
4528     ret = vdb_mbedtls_ctr_drbg_random( &global_data.ctr_drbg,
4529                                    iv, operation->iv_size );
4530     if( ret != 0 )
4531     {
4532         status = mbedtls_to_psa_error( ret );
4533         goto exit;
4534     }
4535 
4536     *iv_length = operation->iv_size;
4537     status = psa_cipher_set_iv( operation, iv, *iv_length );
4538 
4539 exit:
4540     if( status == PSA_SUCCESS )
4541         operation->iv_set = 1;
4542     else
4543         psa_cipher_abort( operation );
4544     return( status );
4545 }
4546 
psa_cipher_set_iv(psa_cipher_operation_t * operation,const uint8_t * iv,size_t iv_length)4547 psa_status_t psa_cipher_set_iv( psa_cipher_operation_t *operation,
4548                                 const uint8_t *iv,
4549                                 size_t iv_length )
4550 {
4551     psa_status_t status;
4552     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
4553     if( operation->iv_set || ! operation->iv_required )
4554     {
4555         return( PSA_ERROR_BAD_STATE );
4556     }
4557 
4558     if( operation->mbedtls_in_use == 0 )
4559     {
4560         status = psa_driver_wrapper_cipher_set_iv( &operation->ctx.driver,
4561                                                    iv,
4562                                                    iv_length );
4563         goto exit;
4564     }
4565 
4566     if( iv_length != operation->iv_size )
4567     {
4568         status = PSA_ERROR_INVALID_ARGUMENT;
4569         goto exit;
4570     }
4571     ret = vdb_mbedtls_cipher_set_iv( &operation->ctx.cipher, iv, iv_length );
4572     status = mbedtls_to_psa_error( ret );
4573 exit:
4574     if( status == PSA_SUCCESS )
4575         operation->iv_set = 1;
4576     else
4577         psa_cipher_abort( operation );
4578     return( status );
4579 }
4580 
4581 /* Process input for which the algorithm is set to ECB mode. This requires
4582  * manual processing, since the PSA API is defined as being able to process
4583  * arbitrary-length calls to psa_cipher_update() with ECB mode, but the
4584  * underlying vdb_mbedtls_cipher_update only takes full blocks. */
psa_cipher_update_ecb_internal(mbedtls_cipher_context_t * ctx,const uint8_t * input,size_t input_length,uint8_t * output,size_t output_size,size_t * output_length)4585 static psa_status_t psa_cipher_update_ecb_internal(
4586     mbedtls_cipher_context_t *ctx,
4587     const uint8_t *input,
4588     size_t input_length,
4589     uint8_t *output,
4590     size_t output_size,
4591     size_t *output_length )
4592 {
4593     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4594     size_t block_size = ctx->cipher_info->block_size;
4595     size_t internal_output_length = 0;
4596     *output_length = 0;
4597 
4598     if( input_length == 0 )
4599     {
4600         status = PSA_SUCCESS;
4601         goto exit;
4602     }
4603 
4604     if( ctx->unprocessed_len > 0 )
4605     {
4606         /* Fill up to block size, and run the block if there's a full one. */
4607         size_t bytes_to_copy = block_size - ctx->unprocessed_len;
4608 
4609         if( input_length < bytes_to_copy )
4610             bytes_to_copy = input_length;
4611 
4612         memcpy( &( ctx->unprocessed_data[ctx->unprocessed_len] ),
4613                 input, bytes_to_copy );
4614         input_length -= bytes_to_copy;
4615         input += bytes_to_copy;
4616         ctx->unprocessed_len += bytes_to_copy;
4617 
4618         if( ctx->unprocessed_len == block_size )
4619         {
4620             status = mbedtls_to_psa_error(
4621                 vdb_mbedtls_cipher_update( ctx,
4622                                        ctx->unprocessed_data,
4623                                        block_size,
4624                                        output, &internal_output_length ) );
4625 
4626             if( status != PSA_SUCCESS )
4627                 goto exit;
4628 
4629             output += internal_output_length;
4630             output_size -= internal_output_length;
4631             *output_length += internal_output_length;
4632             ctx->unprocessed_len = 0;
4633         }
4634     }
4635 
4636     while( input_length >= block_size )
4637     {
4638         /* Run all full blocks we have, one by one */
4639         status = mbedtls_to_psa_error(
4640             vdb_mbedtls_cipher_update( ctx, input,
4641                                    block_size,
4642                                    output, &internal_output_length ) );
4643 
4644         if( status != PSA_SUCCESS )
4645             goto exit;
4646 
4647         input_length -= block_size;
4648         input += block_size;
4649 
4650         output += internal_output_length;
4651         output_size -= internal_output_length;
4652         *output_length += internal_output_length;
4653     }
4654 
4655     if( input_length > 0 )
4656     {
4657         /* Save unprocessed bytes for later processing */
4658         memcpy( &( ctx->unprocessed_data[ctx->unprocessed_len] ),
4659                 input, input_length );
4660         ctx->unprocessed_len += input_length;
4661     }
4662 
4663     status = PSA_SUCCESS;
4664 
4665 exit:
4666     return( status );
4667 }
4668 
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)4669 psa_status_t psa_cipher_update( psa_cipher_operation_t *operation,
4670                                 const uint8_t *input,
4671                                 size_t input_length,
4672                                 uint8_t *output,
4673                                 size_t output_size,
4674                                 size_t *output_length )
4675 {
4676     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4677     size_t expected_output_size;
4678     if( operation->alg == 0 )
4679     {
4680         return( PSA_ERROR_BAD_STATE );
4681     }
4682     if( operation->iv_required && ! operation->iv_set )
4683     {
4684         return( PSA_ERROR_BAD_STATE );
4685     }
4686 
4687     if( operation->mbedtls_in_use == 0 )
4688     {
4689         status = psa_driver_wrapper_cipher_update( &operation->ctx.driver,
4690                                                    input,
4691                                                    input_length,
4692                                                    output,
4693                                                    output_size,
4694                                                    output_length );
4695         goto exit;
4696     }
4697 
4698     if( ! PSA_ALG_IS_STREAM_CIPHER( operation->alg ) )
4699     {
4700         /* Take the unprocessed partial block left over from previous
4701          * update calls, if any, plus the input to this call. Remove
4702          * the last partial block, if any. You get the data that will be
4703          * output in this call. */
4704         expected_output_size =
4705             ( operation->ctx.cipher.unprocessed_len + input_length )
4706             / operation->block_size * operation->block_size;
4707     }
4708     else
4709     {
4710         expected_output_size = input_length;
4711     }
4712 
4713     if( output_size < expected_output_size )
4714     {
4715         status = PSA_ERROR_BUFFER_TOO_SMALL;
4716         goto exit;
4717     }
4718 
4719     if( operation->alg == PSA_ALG_ECB_NO_PADDING )
4720     {
4721         /* vdb_mbedtls_cipher_update has an API inconsistency: it will only
4722         * process a single block at a time in ECB mode. Abstract away that
4723         * inconsistency here to match the PSA API behaviour. */
4724         status = psa_cipher_update_ecb_internal( &operation->ctx.cipher,
4725                                                  input,
4726                                                  input_length,
4727                                                  output,
4728                                                  output_size,
4729                                                  output_length );
4730     }
4731     else
4732     {
4733         status = mbedtls_to_psa_error(
4734             vdb_mbedtls_cipher_update( &operation->ctx.cipher, input,
4735                                    input_length, output, output_length ) );
4736     }
4737 exit:
4738     if( status != PSA_SUCCESS )
4739         psa_cipher_abort( operation );
4740     return( status );
4741 }
4742 
psa_cipher_finish(psa_cipher_operation_t * operation,uint8_t * output,size_t output_size,size_t * output_length)4743 psa_status_t psa_cipher_finish( psa_cipher_operation_t *operation,
4744                                 uint8_t *output,
4745                                 size_t output_size,
4746                                 size_t *output_length )
4747 {
4748     psa_status_t status = PSA_ERROR_GENERIC_ERROR;
4749     uint8_t temp_output_buffer[MBEDTLS_MAX_BLOCK_LENGTH];
4750     if( operation->alg == 0 )
4751     {
4752         return( PSA_ERROR_BAD_STATE );
4753     }
4754     if( operation->iv_required && ! operation->iv_set )
4755     {
4756         return( PSA_ERROR_BAD_STATE );
4757     }
4758 
4759     if( operation->mbedtls_in_use == 0 )
4760     {
4761         status = psa_driver_wrapper_cipher_finish( &operation->ctx.driver,
4762                                                    output,
4763                                                    output_size,
4764                                                    output_length );
4765         goto exit;
4766     }
4767 
4768     if( operation->ctx.cipher.unprocessed_len != 0 )
4769     {
4770         if( operation->alg == PSA_ALG_ECB_NO_PADDING ||
4771             operation->alg == PSA_ALG_CBC_NO_PADDING )
4772         {
4773             status = PSA_ERROR_INVALID_ARGUMENT;
4774             goto exit;
4775         }
4776     }
4777 
4778     status = mbedtls_to_psa_error(
4779         vdb_mbedtls_cipher_finish( &operation->ctx.cipher,
4780                                temp_output_buffer,
4781                                output_length ) );
4782     if( status != PSA_SUCCESS )
4783         goto exit;
4784 
4785     if( *output_length == 0 )
4786         ; /* Nothing to copy. Note that output may be NULL in this case. */
4787     else if( output_size >= *output_length )
4788         memcpy( output, temp_output_buffer, *output_length );
4789     else
4790         status = PSA_ERROR_BUFFER_TOO_SMALL;
4791 
4792 exit:
4793     if( operation->mbedtls_in_use == 1 )
4794         vdb_mbedtls_platform_zeroize( temp_output_buffer, sizeof( temp_output_buffer ) );
4795 
4796     if( status == PSA_SUCCESS )
4797         return( psa_cipher_abort( operation ) );
4798     else
4799     {
4800         *output_length = 0;
4801         (void) psa_cipher_abort( operation );
4802 
4803         return( status );
4804     }
4805 }
4806 
psa_cipher_abort(psa_cipher_operation_t * operation)4807 psa_status_t psa_cipher_abort( psa_cipher_operation_t *operation )
4808 {
4809     if( operation->alg == 0 )
4810     {
4811         /* The object has (apparently) been initialized but it is not (yet)
4812          * in use. It's ok to call abort on such an object, and there's
4813          * nothing to do. */
4814         return( PSA_SUCCESS );
4815     }
4816 
4817     /* Sanity check (shouldn't happen: operation->alg should
4818      * always have been initialized to a valid value). */
4819     if( ! PSA_ALG_IS_CIPHER( operation->alg ) )
4820         return( PSA_ERROR_BAD_STATE );
4821 
4822     if( operation->mbedtls_in_use == 0 )
4823         psa_driver_wrapper_cipher_abort( &operation->ctx.driver );
4824     else
4825         vdb_mbedtls_cipher_free( &operation->ctx.cipher );
4826 
4827     operation->alg = 0;
4828     operation->key_set = 0;
4829     operation->iv_set = 0;
4830     operation->mbedtls_in_use = 0;
4831     operation->iv_size = 0;
4832     operation->block_size = 0;
4833     operation->iv_required = 0;
4834 
4835     return( PSA_SUCCESS );
4836 }
4837 
4838 
4839 
4840 
4841 /****************************************************************/
4842 /* AEAD */
4843 /****************************************************************/
4844 
4845 typedef struct
4846 {
4847     psa_key_slot_t *slot;
4848     const mbedtls_cipher_info_t *cipher_info;
4849     union
4850     {
4851         unsigned dummy; /* Make the union non-empty even with no supported algorithms. */
4852 #if defined(MBEDTLS_CCM_C)
4853         mbedtls_ccm_context ccm;
4854 #endif /* MBEDTLS_CCM_C */
4855 #if defined(MBEDTLS_GCM_C)
4856         mbedtls_gcm_context gcm;
4857 #endif /* MBEDTLS_GCM_C */
4858 #if defined(MBEDTLS_CHACHAPOLY_C)
4859         mbedtls_chachapoly_context chachapoly;
4860 #endif /* MBEDTLS_CHACHAPOLY_C */
4861     } ctx;
4862     psa_algorithm_t core_alg;
4863     uint8_t full_tag_length;
4864     uint8_t tag_length;
4865 } aead_operation_t;
4866 
4867 #define AEAD_OPERATION_INIT {0, 0, {0}, 0, 0, 0}
4868 
psa_aead_abort_internal(aead_operation_t * operation)4869 static void psa_aead_abort_internal( aead_operation_t *operation )
4870 {
4871     switch( operation->core_alg )
4872     {
4873 #if defined(MBEDTLS_CCM_C)
4874         case PSA_ALG_CCM:
4875             vdb_mbedtls_ccm_free( &operation->ctx.ccm );
4876             break;
4877 #endif /* MBEDTLS_CCM_C */
4878 #if defined(MBEDTLS_GCM_C)
4879         case PSA_ALG_GCM:
4880             vdb_mbedtls_gcm_free( &operation->ctx.gcm );
4881             break;
4882 #endif /* MBEDTLS_GCM_C */
4883     }
4884 
4885     psa_unlock_key_slot( operation->slot );
4886 }
4887 
psa_aead_setup(aead_operation_t * operation,mbedtls_svc_key_id_t key,psa_key_usage_t usage,psa_algorithm_t alg)4888 static psa_status_t psa_aead_setup( aead_operation_t *operation,
4889                                     mbedtls_svc_key_id_t key,
4890                                     psa_key_usage_t usage,
4891                                     psa_algorithm_t alg )
4892 {
4893     psa_status_t status;
4894     size_t key_bits;
4895     mbedtls_cipher_id_t cipher_id;
4896 
4897     status = psa_get_and_lock_transparent_key_slot_with_policy(
4898                  key, &operation->slot, usage, alg );
4899     if( status != PSA_SUCCESS )
4900         return( status );
4901 
4902     key_bits = psa_get_key_slot_bits( operation->slot );
4903 
4904     operation->cipher_info =
4905         mbedtls_cipher_info_from_psa( alg, operation->slot->attr.type, key_bits,
4906                                       &cipher_id );
4907     if( operation->cipher_info == NULL )
4908     {
4909         status = PSA_ERROR_NOT_SUPPORTED;
4910         goto cleanup;
4911     }
4912 
4913     switch( PSA_ALG_AEAD_WITH_TAG_LENGTH( alg, 0 ) )
4914     {
4915 #if defined(MBEDTLS_CCM_C)
4916         case PSA_ALG_AEAD_WITH_TAG_LENGTH( PSA_ALG_CCM, 0 ):
4917             operation->core_alg = PSA_ALG_CCM;
4918             operation->full_tag_length = 16;
4919             /* CCM allows the following tag lengths: 4, 6, 8, 10, 12, 14, 16.
4920              * The call to vdb_mbedtls_ccm_encrypt_and_tag or
4921              * vdb_mbedtls_ccm_auth_decrypt will validate the tag length. */
4922             if( PSA_BLOCK_CIPHER_BLOCK_SIZE( operation->slot->attr.type ) != 16 )
4923             {
4924                 status = PSA_ERROR_INVALID_ARGUMENT;
4925                 goto cleanup;
4926             }
4927             vdb_mbedtls_ccm_init( &operation->ctx.ccm );
4928             status = mbedtls_to_psa_error(
4929                 vdb_mbedtls_ccm_setkey( &operation->ctx.ccm, cipher_id,
4930                                     operation->slot->data.key.data,
4931                                     (unsigned int) key_bits ) );
4932             if( status != 0 )
4933                 goto cleanup;
4934             break;
4935 #endif /* MBEDTLS_CCM_C */
4936 
4937 #if defined(MBEDTLS_GCM_C)
4938         case PSA_ALG_AEAD_WITH_TAG_LENGTH( PSA_ALG_GCM, 0 ):
4939             operation->core_alg = PSA_ALG_GCM;
4940             operation->full_tag_length = 16;
4941             /* GCM allows the following tag lengths: 4, 8, 12, 13, 14, 15, 16.
4942              * The call to vdb_mbedtls_gcm_crypt_and_tag or
4943              * vdb_mbedtls_gcm_auth_decrypt will validate the tag length. */
4944             if( PSA_BLOCK_CIPHER_BLOCK_SIZE( operation->slot->attr.type ) != 16 )
4945             {
4946                 status = PSA_ERROR_INVALID_ARGUMENT;
4947                 goto cleanup;
4948             }
4949             vdb_mbedtls_gcm_init( &operation->ctx.gcm );
4950             status = mbedtls_to_psa_error(
4951                 vdb_mbedtls_gcm_setkey( &operation->ctx.gcm, cipher_id,
4952                                     operation->slot->data.key.data,
4953                                     (unsigned int) key_bits ) );
4954             if( status != 0 )
4955                 goto cleanup;
4956             break;
4957 #endif /* MBEDTLS_GCM_C */
4958 
4959 #if defined(MBEDTLS_CHACHAPOLY_C)
4960         case PSA_ALG_AEAD_WITH_TAG_LENGTH( PSA_ALG_CHACHA20_POLY1305, 0 ):
4961             operation->core_alg = PSA_ALG_CHACHA20_POLY1305;
4962             operation->full_tag_length = 16;
4963             /* We only support the default tag length. */
4964             if( alg != PSA_ALG_CHACHA20_POLY1305 )
4965             {
4966                 status = PSA_ERROR_NOT_SUPPORTED;
4967                 goto cleanup;
4968             }
4969             vdb_mbedtls_chachapoly_init( &operation->ctx.chachapoly );
4970             status = mbedtls_to_psa_error(
4971                 vdb_mbedtls_chachapoly_setkey( &operation->ctx.chachapoly,
4972                                            operation->slot->data.key.data ) );
4973             if( status != 0 )
4974                 goto cleanup;
4975             break;
4976 #endif /* MBEDTLS_CHACHAPOLY_C */
4977 
4978         default:
4979             status = PSA_ERROR_NOT_SUPPORTED;
4980             goto cleanup;
4981     }
4982 
4983     if( PSA_AEAD_TAG_LENGTH( alg ) > operation->full_tag_length )
4984     {
4985         status = PSA_ERROR_INVALID_ARGUMENT;
4986         goto cleanup;
4987     }
4988     operation->tag_length = PSA_AEAD_TAG_LENGTH( alg );
4989 
4990     return( PSA_SUCCESS );
4991 
4992 cleanup:
4993     psa_aead_abort_internal( operation );
4994     return( status );
4995 }
4996 
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)4997 psa_status_t psa_aead_encrypt( mbedtls_svc_key_id_t key,
4998                                psa_algorithm_t alg,
4999                                const uint8_t *nonce,
5000                                size_t nonce_length,
5001                                const uint8_t *additional_data,
5002                                size_t additional_data_length,
5003                                const uint8_t *plaintext,
5004                                size_t plaintext_length,
5005                                uint8_t *ciphertext,
5006                                size_t ciphertext_size,
5007                                size_t *ciphertext_length )
5008 {
5009     psa_status_t status;
5010     aead_operation_t operation = AEAD_OPERATION_INIT;
5011     uint8_t *tag;
5012 
5013     *ciphertext_length = 0;
5014 
5015     status = psa_aead_setup( &operation, key, PSA_KEY_USAGE_ENCRYPT, alg );
5016     if( status != PSA_SUCCESS )
5017         return( status );
5018 
5019     /* For all currently supported modes, the tag is at the end of the
5020      * ciphertext. */
5021     if( ciphertext_size < ( plaintext_length + operation.tag_length ) )
5022     {
5023         status = PSA_ERROR_BUFFER_TOO_SMALL;
5024         goto exit;
5025     }
5026     tag = ciphertext + plaintext_length;
5027 
5028 #if defined(MBEDTLS_GCM_C)
5029     if( operation.core_alg == PSA_ALG_GCM )
5030     {
5031         status = mbedtls_to_psa_error(
5032             vdb_mbedtls_gcm_crypt_and_tag( &operation.ctx.gcm,
5033                                        MBEDTLS_GCM_ENCRYPT,
5034                                        plaintext_length,
5035                                        nonce, nonce_length,
5036                                        additional_data, additional_data_length,
5037                                        plaintext, ciphertext,
5038                                        operation.tag_length, tag ) );
5039     }
5040     else
5041 #endif /* MBEDTLS_GCM_C */
5042 #if defined(MBEDTLS_CCM_C)
5043     if( operation.core_alg == PSA_ALG_CCM )
5044     {
5045         status = mbedtls_to_psa_error(
5046             vdb_mbedtls_ccm_encrypt_and_tag( &operation.ctx.ccm,
5047                                          plaintext_length,
5048                                          nonce, nonce_length,
5049                                          additional_data,
5050                                          additional_data_length,
5051                                          plaintext, ciphertext,
5052                                          tag, operation.tag_length ) );
5053     }
5054     else
5055 #endif /* MBEDTLS_CCM_C */
5056 #if defined(MBEDTLS_CHACHAPOLY_C)
5057     if( operation.core_alg == PSA_ALG_CHACHA20_POLY1305 )
5058     {
5059         if( nonce_length != 12 || operation.tag_length != 16 )
5060         {
5061             status = PSA_ERROR_NOT_SUPPORTED;
5062             goto exit;
5063         }
5064         status = mbedtls_to_psa_error(
5065             vdb_mbedtls_chachapoly_encrypt_and_tag( &operation.ctx.chachapoly,
5066                                                 plaintext_length,
5067                                                 nonce,
5068                                                 additional_data,
5069                                                 additional_data_length,
5070                                                 plaintext,
5071                                                 ciphertext,
5072                                                 tag ) );
5073     }
5074     else
5075 #endif /* MBEDTLS_CHACHAPOLY_C */
5076     {
5077         return( PSA_ERROR_NOT_SUPPORTED );
5078     }
5079 
5080     if( status != PSA_SUCCESS && ciphertext_size != 0 )
5081         memset( ciphertext, 0, ciphertext_size );
5082 
5083 exit:
5084     psa_aead_abort_internal( &operation );
5085     if( status == PSA_SUCCESS )
5086         *ciphertext_length = plaintext_length + operation.tag_length;
5087     return( status );
5088 }
5089 
5090 /* Locate the tag in a ciphertext buffer containing the encrypted data
5091  * followed by the tag. Return the length of the part preceding the tag in
5092  * *plaintext_length. This is the size of the plaintext in modes where
5093  * the encrypted data has the same size as the plaintext, such as
5094  * CCM and GCM. */
psa_aead_unpadded_locate_tag(size_t tag_length,const uint8_t * ciphertext,size_t ciphertext_length,size_t plaintext_size,const uint8_t ** p_tag)5095 static psa_status_t psa_aead_unpadded_locate_tag( size_t tag_length,
5096                                                   const uint8_t *ciphertext,
5097                                                   size_t ciphertext_length,
5098                                                   size_t plaintext_size,
5099                                                   const uint8_t **p_tag )
5100 {
5101     size_t payload_length;
5102     if( tag_length > ciphertext_length )
5103         return( PSA_ERROR_INVALID_ARGUMENT );
5104     payload_length = ciphertext_length - tag_length;
5105     if( payload_length > plaintext_size )
5106         return( PSA_ERROR_BUFFER_TOO_SMALL );
5107     *p_tag = ciphertext + payload_length;
5108     return( PSA_SUCCESS );
5109 }
5110 
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)5111 psa_status_t psa_aead_decrypt( mbedtls_svc_key_id_t key,
5112                                psa_algorithm_t alg,
5113                                const uint8_t *nonce,
5114                                size_t nonce_length,
5115                                const uint8_t *additional_data,
5116                                size_t additional_data_length,
5117                                const uint8_t *ciphertext,
5118                                size_t ciphertext_length,
5119                                uint8_t *plaintext,
5120                                size_t plaintext_size,
5121                                size_t *plaintext_length )
5122 {
5123     psa_status_t status;
5124     aead_operation_t operation = AEAD_OPERATION_INIT;
5125     const uint8_t *tag = NULL;
5126 
5127     *plaintext_length = 0;
5128 
5129     status = psa_aead_setup( &operation, key, PSA_KEY_USAGE_DECRYPT, alg );
5130     if( status != PSA_SUCCESS )
5131         return( status );
5132 
5133     status = psa_aead_unpadded_locate_tag( operation.tag_length,
5134                                            ciphertext, ciphertext_length,
5135                                            plaintext_size, &tag );
5136     if( status != PSA_SUCCESS )
5137         goto exit;
5138 
5139 #if defined(MBEDTLS_GCM_C)
5140     if( operation.core_alg == PSA_ALG_GCM )
5141     {
5142         status = mbedtls_to_psa_error(
5143             vdb_mbedtls_gcm_auth_decrypt( &operation.ctx.gcm,
5144                                       ciphertext_length - operation.tag_length,
5145                                       nonce, nonce_length,
5146                                       additional_data,
5147                                       additional_data_length,
5148                                       tag, operation.tag_length,
5149                                       ciphertext, plaintext ) );
5150     }
5151     else
5152 #endif /* MBEDTLS_GCM_C */
5153 #if defined(MBEDTLS_CCM_C)
5154     if( operation.core_alg == PSA_ALG_CCM )
5155     {
5156         status = mbedtls_to_psa_error(
5157             vdb_mbedtls_ccm_auth_decrypt( &operation.ctx.ccm,
5158                                       ciphertext_length - operation.tag_length,
5159                                       nonce, nonce_length,
5160                                       additional_data,
5161                                       additional_data_length,
5162                                       ciphertext, plaintext,
5163                                       tag, operation.tag_length ) );
5164     }
5165     else
5166 #endif /* MBEDTLS_CCM_C */
5167 #if defined(MBEDTLS_CHACHAPOLY_C)
5168     if( operation.core_alg == PSA_ALG_CHACHA20_POLY1305 )
5169     {
5170         if( nonce_length != 12 || operation.tag_length != 16 )
5171         {
5172             status = PSA_ERROR_NOT_SUPPORTED;
5173             goto exit;
5174         }
5175         status = mbedtls_to_psa_error(
5176             vdb_mbedtls_chachapoly_auth_decrypt( &operation.ctx.chachapoly,
5177                                              ciphertext_length - operation.tag_length,
5178                                              nonce,
5179                                              additional_data,
5180                                              additional_data_length,
5181                                              tag,
5182                                              ciphertext,
5183                                              plaintext ) );
5184     }
5185     else
5186 #endif /* MBEDTLS_CHACHAPOLY_C */
5187     {
5188         return( PSA_ERROR_NOT_SUPPORTED );
5189     }
5190 
5191     if( status != PSA_SUCCESS && plaintext_size != 0 )
5192         memset( plaintext, 0, plaintext_size );
5193 
5194 exit:
5195     psa_aead_abort_internal( &operation );
5196     if( status == PSA_SUCCESS )
5197         *plaintext_length = ciphertext_length - operation.tag_length;
5198     return( status );
5199 }
5200 
5201 
5202 
5203 /****************************************************************/
5204 /* Generators */
5205 /****************************************************************/
5206 
5207 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF) || \
5208     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
5209     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
5210 #define AT_LEAST_ONE_BUILTIN_KDF
5211 #endif
5212 
5213 #define HKDF_STATE_INIT 0 /* no input yet */
5214 #define HKDF_STATE_STARTED 1 /* got salt */
5215 #define HKDF_STATE_KEYED 2 /* got key */
5216 #define HKDF_STATE_OUTPUT 3 /* output started */
5217 
psa_key_derivation_get_kdf_alg(const psa_key_derivation_operation_t * operation)5218 static psa_algorithm_t psa_key_derivation_get_kdf_alg(
5219     const psa_key_derivation_operation_t *operation )
5220 {
5221     if ( PSA_ALG_IS_KEY_AGREEMENT( operation->alg ) )
5222         return( PSA_ALG_KEY_AGREEMENT_GET_KDF( operation->alg ) );
5223     else
5224         return( operation->alg );
5225 }
5226 
psa_key_derivation_abort(psa_key_derivation_operation_t * operation)5227 psa_status_t psa_key_derivation_abort( psa_key_derivation_operation_t *operation )
5228 {
5229     psa_status_t status = PSA_SUCCESS;
5230     psa_algorithm_t kdf_alg = psa_key_derivation_get_kdf_alg( operation );
5231     if( kdf_alg == 0 )
5232     {
5233         /* The object has (apparently) been initialized but it is not
5234          * in use. It's ok to call abort on such an object, and there's
5235          * nothing to do. */
5236     }
5237     else
5238 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF)
5239     if( PSA_ALG_IS_HKDF( kdf_alg ) )
5240     {
5241         vdb_mbedtls_free( operation->ctx.hkdf.info );
5242         status = psa_hmac_abort_internal( &operation->ctx.hkdf.hmac );
5243     }
5244     else
5245 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF */
5246 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
5247     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
5248     if( PSA_ALG_IS_TLS12_PRF( kdf_alg ) ||
5249              /* TLS-1.2 PSK-to-MS KDF uses the same core as TLS-1.2 PRF */
5250              PSA_ALG_IS_TLS12_PSK_TO_MS( kdf_alg ) )
5251     {
5252         if( operation->ctx.tls12_prf.seed != NULL )
5253         {
5254             vdb_mbedtls_platform_zeroize( operation->ctx.tls12_prf.seed,
5255                                       operation->ctx.tls12_prf.seed_length );
5256             vdb_mbedtls_free( operation->ctx.tls12_prf.seed );
5257         }
5258 
5259         if( operation->ctx.tls12_prf.label != NULL )
5260         {
5261             vdb_mbedtls_platform_zeroize( operation->ctx.tls12_prf.label,
5262                                       operation->ctx.tls12_prf.label_length );
5263             vdb_mbedtls_free( operation->ctx.tls12_prf.label );
5264         }
5265 
5266         status = psa_hmac_abort_internal( &operation->ctx.tls12_prf.hmac );
5267 
5268         /* We leave the fields Ai and output_block to be erased safely by the
5269          * vdb_mbedtls_platform_zeroize() in the end of this function. */
5270     }
5271     else
5272 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) ||
5273         * defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS) */
5274     {
5275         status = PSA_ERROR_BAD_STATE;
5276     }
5277     vdb_mbedtls_platform_zeroize( operation, sizeof( *operation ) );
5278     return( status );
5279 }
5280 
psa_key_derivation_get_capacity(const psa_key_derivation_operation_t * operation,size_t * capacity)5281 psa_status_t psa_key_derivation_get_capacity(const psa_key_derivation_operation_t *operation,
5282                                         size_t *capacity)
5283 {
5284     if( operation->alg == 0 )
5285     {
5286         /* This is a blank key derivation operation. */
5287         return( PSA_ERROR_BAD_STATE );
5288     }
5289 
5290     *capacity = operation->capacity;
5291     return( PSA_SUCCESS );
5292 }
5293 
psa_key_derivation_set_capacity(psa_key_derivation_operation_t * operation,size_t capacity)5294 psa_status_t psa_key_derivation_set_capacity( psa_key_derivation_operation_t *operation,
5295                                          size_t capacity )
5296 {
5297     if( operation->alg == 0 )
5298         return( PSA_ERROR_BAD_STATE );
5299     if( capacity > operation->capacity )
5300         return( PSA_ERROR_INVALID_ARGUMENT );
5301     operation->capacity = capacity;
5302     return( PSA_SUCCESS );
5303 }
5304 
5305 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF)
5306 /* Read some bytes from an HKDF-based operation. This performs a chunk
5307  * 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)5308 static psa_status_t psa_key_derivation_hkdf_read( psa_hkdf_key_derivation_t *hkdf,
5309                                              psa_algorithm_t hash_alg,
5310                                              uint8_t *output,
5311                                              size_t output_length )
5312 {
5313     uint8_t hash_length = PSA_HASH_SIZE( hash_alg );
5314     psa_status_t status;
5315 
5316     if( hkdf->state < HKDF_STATE_KEYED || ! hkdf->info_set )
5317         return( PSA_ERROR_BAD_STATE );
5318     hkdf->state = HKDF_STATE_OUTPUT;
5319 
5320     while( output_length != 0 )
5321     {
5322         /* Copy what remains of the current block */
5323         uint8_t n = hash_length - hkdf->offset_in_block;
5324         if( n > output_length )
5325             n = (uint8_t) output_length;
5326         memcpy( output, hkdf->output_block + hkdf->offset_in_block, n );
5327         output += n;
5328         output_length -= n;
5329         hkdf->offset_in_block += n;
5330         if( output_length == 0 )
5331             break;
5332         /* We can't be wanting more output after block 0xff, otherwise
5333          * the capacity check in psa_key_derivation_output_bytes() would have
5334          * prevented this call. It could happen only if the operation
5335          * object was corrupted or if this function is called directly
5336          * inside the library. */
5337         if( hkdf->block_number == 0xff )
5338             return( PSA_ERROR_BAD_STATE );
5339 
5340         /* We need a new block */
5341         ++hkdf->block_number;
5342         hkdf->offset_in_block = 0;
5343         status = psa_hmac_setup_internal( &hkdf->hmac,
5344                                           hkdf->prk, hash_length,
5345                                           hash_alg );
5346         if( status != PSA_SUCCESS )
5347             return( status );
5348         if( hkdf->block_number != 1 )
5349         {
5350             status = psa_hash_update( &hkdf->hmac.hash_ctx,
5351                                       hkdf->output_block,
5352                                       hash_length );
5353             if( status != PSA_SUCCESS )
5354                 return( status );
5355         }
5356         status = psa_hash_update( &hkdf->hmac.hash_ctx,
5357                                   hkdf->info,
5358                                   hkdf->info_length );
5359         if( status != PSA_SUCCESS )
5360             return( status );
5361         status = psa_hash_update( &hkdf->hmac.hash_ctx,
5362                                   &hkdf->block_number, 1 );
5363         if( status != PSA_SUCCESS )
5364             return( status );
5365         status = psa_hmac_finish_internal( &hkdf->hmac,
5366                                            hkdf->output_block,
5367                                            sizeof( hkdf->output_block ) );
5368         if( status != PSA_SUCCESS )
5369             return( status );
5370     }
5371 
5372     return( PSA_SUCCESS );
5373 }
5374 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF */
5375 
5376 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
5377     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)5378 static psa_status_t psa_key_derivation_tls12_prf_generate_next_block(
5379     psa_tls12_prf_key_derivation_t *tls12_prf,
5380     psa_algorithm_t alg )
5381 {
5382     psa_algorithm_t hash_alg = PSA_ALG_HKDF_GET_HASH( alg );
5383     uint8_t hash_length = PSA_HASH_SIZE( hash_alg );
5384     psa_hash_operation_t backup = PSA_HASH_OPERATION_INIT;
5385     psa_status_t status, cleanup_status;
5386 
5387     /* We can't be wanting more output after block 0xff, otherwise
5388      * the capacity check in psa_key_derivation_output_bytes() would have
5389      * prevented this call. It could happen only if the operation
5390      * object was corrupted or if this function is called directly
5391      * inside the library. */
5392     if( tls12_prf->block_number == 0xff )
5393         return( PSA_ERROR_CORRUPTION_DETECTED );
5394 
5395     /* We need a new block */
5396     ++tls12_prf->block_number;
5397     tls12_prf->left_in_block = hash_length;
5398 
5399     /* Recall the definition of the TLS-1.2-PRF from RFC 5246:
5400      *
5401      * PRF(secret, label, seed) = P_<hash>(secret, label + seed)
5402      *
5403      * P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
5404      *                        HMAC_hash(secret, A(2) + seed) +
5405      *                        HMAC_hash(secret, A(3) + seed) + ...
5406      *
5407      * A(0) = seed
5408      * A(i) = HMAC_hash(secret, A(i-1))
5409      *
5410      * The `psa_tls12_prf_key_derivation` structure saves the block
5411      * `HMAC_hash(secret, A(i) + seed)` from which the output
5412      * is currently extracted as `output_block` and where i is
5413      * `block_number`.
5414      */
5415 
5416     /* Save the hash context before using it, to preserve the hash state with
5417      * only the inner padding in it. We need this, because inner padding depends
5418      * on the key (secret in the RFC's terminology). */
5419     status = psa_hash_clone( &tls12_prf->hmac.hash_ctx, &backup );
5420     if( status != PSA_SUCCESS )
5421         goto cleanup;
5422 
5423     /* Calculate A(i) where i = tls12_prf->block_number. */
5424     if( tls12_prf->block_number == 1 )
5425     {
5426         /* A(1) = HMAC_hash(secret, A(0)), where A(0) = seed. (The RFC overloads
5427          * the variable seed and in this instance means it in the context of the
5428          * P_hash function, where seed = label + seed.) */
5429         status = psa_hash_update( &tls12_prf->hmac.hash_ctx,
5430                                   tls12_prf->label, tls12_prf->label_length );
5431         if( status != PSA_SUCCESS )
5432             goto cleanup;
5433         status = psa_hash_update( &tls12_prf->hmac.hash_ctx,
5434                                   tls12_prf->seed, tls12_prf->seed_length );
5435         if( status != PSA_SUCCESS )
5436             goto cleanup;
5437     }
5438     else
5439     {
5440         /* A(i) = HMAC_hash(secret, A(i-1)) */
5441         status = psa_hash_update( &tls12_prf->hmac.hash_ctx,
5442                                   tls12_prf->Ai, hash_length );
5443         if( status != PSA_SUCCESS )
5444             goto cleanup;
5445     }
5446 
5447     status = psa_hmac_finish_internal( &tls12_prf->hmac,
5448                                        tls12_prf->Ai, hash_length );
5449     if( status != PSA_SUCCESS )
5450         goto cleanup;
5451     status = psa_hash_clone( &backup, &tls12_prf->hmac.hash_ctx );
5452     if( status != PSA_SUCCESS )
5453         goto cleanup;
5454 
5455     /* Calculate HMAC_hash(secret, A(i) + label + seed). */
5456     status = psa_hash_update( &tls12_prf->hmac.hash_ctx,
5457                               tls12_prf->Ai, hash_length );
5458     if( status != PSA_SUCCESS )
5459         goto cleanup;
5460     status = psa_hash_update( &tls12_prf->hmac.hash_ctx,
5461                               tls12_prf->label, tls12_prf->label_length );
5462     if( status != PSA_SUCCESS )
5463         goto cleanup;
5464     status = psa_hash_update( &tls12_prf->hmac.hash_ctx,
5465                               tls12_prf->seed, tls12_prf->seed_length );
5466     if( status != PSA_SUCCESS )
5467         goto cleanup;
5468     status = psa_hmac_finish_internal( &tls12_prf->hmac,
5469                                        tls12_prf->output_block, hash_length );
5470     if( status != PSA_SUCCESS )
5471         goto cleanup;
5472     status = psa_hash_clone( &backup, &tls12_prf->hmac.hash_ctx );
5473     if( status != PSA_SUCCESS )
5474         goto cleanup;
5475 
5476 
5477 cleanup:
5478 
5479     cleanup_status = psa_hash_abort( &backup );
5480     if( status == PSA_SUCCESS && cleanup_status != PSA_SUCCESS )
5481         status = cleanup_status;
5482 
5483     return( status );
5484 }
5485 
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)5486 static psa_status_t psa_key_derivation_tls12_prf_read(
5487     psa_tls12_prf_key_derivation_t *tls12_prf,
5488     psa_algorithm_t alg,
5489     uint8_t *output,
5490     size_t output_length )
5491 {
5492     psa_algorithm_t hash_alg = PSA_ALG_TLS12_PRF_GET_HASH( alg );
5493     uint8_t hash_length = PSA_HASH_SIZE( hash_alg );
5494     psa_status_t status;
5495     uint8_t offset, length;
5496 
5497     while( output_length != 0 )
5498     {
5499         /* Check if we have fully processed the current block. */
5500         if( tls12_prf->left_in_block == 0 )
5501         {
5502             status = psa_key_derivation_tls12_prf_generate_next_block( tls12_prf,
5503                                                                        alg );
5504             if( status != PSA_SUCCESS )
5505                 return( status );
5506 
5507             continue;
5508         }
5509 
5510         if( tls12_prf->left_in_block > output_length )
5511             length = (uint8_t) output_length;
5512         else
5513             length = tls12_prf->left_in_block;
5514 
5515         offset = hash_length - tls12_prf->left_in_block;
5516         memcpy( output, tls12_prf->output_block + offset, length );
5517         output += length;
5518         output_length -= length;
5519         tls12_prf->left_in_block -= length;
5520     }
5521 
5522     return( PSA_SUCCESS );
5523 }
5524 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF ||
5525         * MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
5526 
psa_key_derivation_output_bytes(psa_key_derivation_operation_t * operation,uint8_t * output,size_t output_length)5527 psa_status_t psa_key_derivation_output_bytes(
5528     psa_key_derivation_operation_t *operation,
5529     uint8_t *output,
5530     size_t output_length )
5531 {
5532     psa_status_t status;
5533     psa_algorithm_t kdf_alg = psa_key_derivation_get_kdf_alg( operation );
5534 
5535     if( operation->alg == 0 )
5536     {
5537         /* This is a blank operation. */
5538         return( PSA_ERROR_BAD_STATE );
5539     }
5540 
5541     if( output_length > operation->capacity )
5542     {
5543         operation->capacity = 0;
5544         /* Go through the error path to wipe all confidential data now
5545          * that the operation object is useless. */
5546         status = PSA_ERROR_INSUFFICIENT_DATA;
5547         goto exit;
5548     }
5549     if( output_length == 0 && operation->capacity == 0 )
5550     {
5551         /* Edge case: this is a finished operation, and 0 bytes
5552          * were requested. The right error in this case could
5553          * be either INSUFFICIENT_CAPACITY or BAD_STATE. Return
5554          * INSUFFICIENT_CAPACITY, which is right for a finished
5555          * operation, for consistency with the case when
5556          * output_length > 0. */
5557         return( PSA_ERROR_INSUFFICIENT_DATA );
5558     }
5559     operation->capacity -= output_length;
5560 
5561 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF)
5562     if( PSA_ALG_IS_HKDF( kdf_alg ) )
5563     {
5564         psa_algorithm_t hash_alg = PSA_ALG_HKDF_GET_HASH( kdf_alg );
5565         status = psa_key_derivation_hkdf_read( &operation->ctx.hkdf, hash_alg,
5566                                           output, output_length );
5567     }
5568     else
5569 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF */
5570 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
5571     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
5572     if( PSA_ALG_IS_TLS12_PRF( kdf_alg ) ||
5573         PSA_ALG_IS_TLS12_PSK_TO_MS( kdf_alg ) )
5574     {
5575         status = psa_key_derivation_tls12_prf_read( &operation->ctx.tls12_prf,
5576                                                kdf_alg, output,
5577                                                output_length );
5578     }
5579     else
5580 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF ||
5581         * MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
5582     {
5583         return( PSA_ERROR_BAD_STATE );
5584     }
5585 
5586 exit:
5587     if( status != PSA_SUCCESS )
5588     {
5589         /* Preserve the algorithm upon errors, but clear all sensitive state.
5590          * This allows us to differentiate between exhausted operations and
5591          * blank operations, so we can return PSA_ERROR_BAD_STATE on blank
5592          * operations. */
5593         psa_algorithm_t alg = operation->alg;
5594         psa_key_derivation_abort( operation );
5595         operation->alg = alg;
5596         memset( output, '!', output_length );
5597     }
5598     return( status );
5599 }
5600 
5601 #if defined(MBEDTLS_DES_C)
psa_des_set_key_parity(uint8_t * data,size_t data_size)5602 static void psa_des_set_key_parity( uint8_t *data, size_t data_size )
5603 {
5604     if( data_size >= 8 )
5605         vdb_mbedtls_des_key_set_parity( data );
5606     if( data_size >= 16 )
5607         vdb_mbedtls_des_key_set_parity( data + 8 );
5608     if( data_size >= 24 )
5609         vdb_mbedtls_des_key_set_parity( data + 16 );
5610 }
5611 #endif /* MBEDTLS_DES_C */
5612 
psa_generate_derived_key_internal(psa_key_slot_t * slot,size_t bits,psa_key_derivation_operation_t * operation)5613 static psa_status_t psa_generate_derived_key_internal(
5614     psa_key_slot_t *slot,
5615     size_t bits,
5616     psa_key_derivation_operation_t *operation )
5617 {
5618     uint8_t *data = NULL;
5619     size_t bytes = PSA_BITS_TO_BYTES( bits );
5620     psa_status_t status;
5621 
5622     if( ! key_type_is_raw_bytes( slot->attr.type ) )
5623         return( PSA_ERROR_INVALID_ARGUMENT );
5624     if( bits % 8 != 0 )
5625         return( PSA_ERROR_INVALID_ARGUMENT );
5626     data = vdb_mbedtls_calloc( 1, bytes );
5627     if( data == NULL )
5628         return( PSA_ERROR_INSUFFICIENT_MEMORY );
5629 
5630     status = psa_key_derivation_output_bytes( operation, data, bytes );
5631     if( status != PSA_SUCCESS )
5632         goto exit;
5633 #if defined(MBEDTLS_DES_C)
5634     if( slot->attr.type == PSA_KEY_TYPE_DES )
5635         psa_des_set_key_parity( data, bytes );
5636 #endif /* MBEDTLS_DES_C */
5637     status = psa_import_key_into_slot( slot, data, bytes );
5638 
5639 exit:
5640     vdb_mbedtls_free( data );
5641     return( status );
5642 }
5643 
psa_key_derivation_output_key(const psa_key_attributes_t * attributes,psa_key_derivation_operation_t * operation,mbedtls_svc_key_id_t * key)5644 psa_status_t psa_key_derivation_output_key( const psa_key_attributes_t *attributes,
5645                                        psa_key_derivation_operation_t *operation,
5646                                        mbedtls_svc_key_id_t *key )
5647 {
5648     psa_status_t status;
5649     psa_key_slot_t *slot = NULL;
5650     psa_se_drv_table_entry_t *driver = NULL;
5651 
5652     *key = MBEDTLS_SVC_KEY_ID_INIT;
5653 
5654     /* Reject any attempt to create a zero-length key so that we don't
5655      * risk tripping up later, e.g. on a malloc(0) that returns NULL. */
5656     if( psa_get_key_bits( attributes ) == 0 )
5657         return( PSA_ERROR_INVALID_ARGUMENT );
5658 
5659     if( ! operation->can_output_key )
5660         return( PSA_ERROR_NOT_PERMITTED );
5661 
5662     status = psa_start_key_creation( PSA_KEY_CREATION_DERIVE, attributes,
5663                                      &slot, &driver );
5664 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
5665     if( driver != NULL )
5666     {
5667         /* Deriving a key in a secure element is not implemented yet. */
5668         status = PSA_ERROR_NOT_SUPPORTED;
5669     }
5670 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
5671     if( status == PSA_SUCCESS )
5672     {
5673         status = psa_generate_derived_key_internal( slot,
5674                                                     attributes->core.bits,
5675                                                     operation );
5676     }
5677     if( status == PSA_SUCCESS )
5678         status = psa_finish_key_creation( slot, driver, key );
5679     if( status != PSA_SUCCESS )
5680         psa_fail_key_creation( slot, driver );
5681 
5682     return( status );
5683 }
5684 
5685 
5686 
5687 /****************************************************************/
5688 /* Key derivation */
5689 /****************************************************************/
5690 
5691 #ifdef AT_LEAST_ONE_BUILTIN_KDF
psa_key_derivation_setup_kdf(psa_key_derivation_operation_t * operation,psa_algorithm_t kdf_alg)5692 static psa_status_t psa_key_derivation_setup_kdf(
5693     psa_key_derivation_operation_t *operation,
5694     psa_algorithm_t kdf_alg )
5695 {
5696     int is_kdf_alg_supported;
5697 
5698     /* Make sure that operation->ctx is properly zero-initialised. (Macro
5699      * initialisers for this union leave some bytes unspecified.) */
5700     memset( &operation->ctx, 0, sizeof( operation->ctx ) );
5701 
5702     /* Make sure that kdf_alg is a supported key derivation algorithm. */
5703 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF)
5704     if( PSA_ALG_IS_HKDF( kdf_alg ) )
5705         is_kdf_alg_supported = 1;
5706     else
5707 #endif
5708 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF)
5709     if( PSA_ALG_IS_TLS12_PRF( kdf_alg ) )
5710         is_kdf_alg_supported = 1;
5711     else
5712 #endif
5713 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
5714     if( PSA_ALG_IS_TLS12_PSK_TO_MS( kdf_alg ) )
5715         is_kdf_alg_supported = 1;
5716     else
5717 #endif
5718     is_kdf_alg_supported = 0;
5719 
5720     if( is_kdf_alg_supported )
5721     {
5722         psa_algorithm_t hash_alg = PSA_ALG_HKDF_GET_HASH( kdf_alg );
5723         size_t hash_size = PSA_HASH_SIZE( hash_alg );
5724         if( hash_size == 0 )
5725             return( PSA_ERROR_NOT_SUPPORTED );
5726         if( ( PSA_ALG_IS_TLS12_PRF( kdf_alg ) ||
5727               PSA_ALG_IS_TLS12_PSK_TO_MS( kdf_alg ) ) &&
5728             ! ( hash_alg == PSA_ALG_SHA_256 || hash_alg == PSA_ALG_SHA_384 ) )
5729         {
5730             return( PSA_ERROR_NOT_SUPPORTED );
5731         }
5732         operation->capacity = 255 * hash_size;
5733         return( PSA_SUCCESS );
5734     }
5735 
5736     return( PSA_ERROR_NOT_SUPPORTED );
5737 }
5738 #endif /* AT_LEAST_ONE_BUILTIN_KDF */
5739 
psa_key_derivation_setup(psa_key_derivation_operation_t * operation,psa_algorithm_t alg)5740 psa_status_t psa_key_derivation_setup( psa_key_derivation_operation_t *operation,
5741                                        psa_algorithm_t alg )
5742 {
5743     psa_status_t status;
5744 
5745     if( operation->alg != 0 )
5746         return( PSA_ERROR_BAD_STATE );
5747 
5748     if( PSA_ALG_IS_RAW_KEY_AGREEMENT( alg ) )
5749         return( PSA_ERROR_INVALID_ARGUMENT );
5750 #ifdef AT_LEAST_ONE_BUILTIN_KDF
5751     else if( PSA_ALG_IS_KEY_AGREEMENT( alg ) )
5752     {
5753         psa_algorithm_t kdf_alg = PSA_ALG_KEY_AGREEMENT_GET_KDF( alg );
5754         status = psa_key_derivation_setup_kdf( operation, kdf_alg );
5755     }
5756     else if( PSA_ALG_IS_KEY_DERIVATION( alg ) )
5757     {
5758         status = psa_key_derivation_setup_kdf( operation, alg );
5759     }
5760 #endif
5761     else
5762         return( PSA_ERROR_INVALID_ARGUMENT );
5763 
5764     if( status == PSA_SUCCESS )
5765         operation->alg = alg;
5766     return( status );
5767 }
5768 
5769 #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)5770 static psa_status_t psa_hkdf_input( psa_hkdf_key_derivation_t *hkdf,
5771                                     psa_algorithm_t hash_alg,
5772                                     psa_key_derivation_step_t step,
5773                                     const uint8_t *data,
5774                                     size_t data_length )
5775 {
5776     psa_status_t status;
5777     switch( step )
5778     {
5779         case PSA_KEY_DERIVATION_INPUT_SALT:
5780             if( hkdf->state != HKDF_STATE_INIT )
5781                 return( PSA_ERROR_BAD_STATE );
5782             status = psa_hmac_setup_internal( &hkdf->hmac,
5783                                               data, data_length,
5784                                               hash_alg );
5785             if( status != PSA_SUCCESS )
5786                 return( status );
5787             hkdf->state = HKDF_STATE_STARTED;
5788             return( PSA_SUCCESS );
5789         case PSA_KEY_DERIVATION_INPUT_SECRET:
5790             /* If no salt was provided, use an empty salt. */
5791             if( hkdf->state == HKDF_STATE_INIT )
5792             {
5793                 status = psa_hmac_setup_internal( &hkdf->hmac,
5794                                                   NULL, 0,
5795                                                   hash_alg );
5796                 if( status != PSA_SUCCESS )
5797                     return( status );
5798                 hkdf->state = HKDF_STATE_STARTED;
5799             }
5800             if( hkdf->state != HKDF_STATE_STARTED )
5801                 return( PSA_ERROR_BAD_STATE );
5802             status = psa_hash_update( &hkdf->hmac.hash_ctx,
5803                                       data, data_length );
5804             if( status != PSA_SUCCESS )
5805                 return( status );
5806             status = psa_hmac_finish_internal( &hkdf->hmac,
5807                                                hkdf->prk,
5808                                                sizeof( hkdf->prk ) );
5809             if( status != PSA_SUCCESS )
5810                 return( status );
5811             hkdf->offset_in_block = PSA_HASH_SIZE( hash_alg );
5812             hkdf->block_number = 0;
5813             hkdf->state = HKDF_STATE_KEYED;
5814             return( PSA_SUCCESS );
5815         case PSA_KEY_DERIVATION_INPUT_INFO:
5816             if( hkdf->state == HKDF_STATE_OUTPUT )
5817                 return( PSA_ERROR_BAD_STATE );
5818             if( hkdf->info_set )
5819                 return( PSA_ERROR_BAD_STATE );
5820             hkdf->info_length = data_length;
5821             if( data_length != 0 )
5822             {
5823                 hkdf->info = vdb_mbedtls_calloc( 1, data_length );
5824                 if( hkdf->info == NULL )
5825                     return( PSA_ERROR_INSUFFICIENT_MEMORY );
5826                 memcpy( hkdf->info, data, data_length );
5827             }
5828             hkdf->info_set = 1;
5829             return( PSA_SUCCESS );
5830         default:
5831             return( PSA_ERROR_INVALID_ARGUMENT );
5832     }
5833 }
5834 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF */
5835 
5836 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
5837     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)5838 static psa_status_t psa_tls12_prf_set_seed( psa_tls12_prf_key_derivation_t *prf,
5839                                             const uint8_t *data,
5840                                             size_t data_length )
5841 {
5842     if( prf->state != TLS12_PRF_STATE_INIT )
5843         return( PSA_ERROR_BAD_STATE );
5844 
5845     if( data_length != 0 )
5846     {
5847         prf->seed = vdb_mbedtls_calloc( 1, data_length );
5848         if( prf->seed == NULL )
5849             return( PSA_ERROR_INSUFFICIENT_MEMORY );
5850 
5851         memcpy( prf->seed, data, data_length );
5852         prf->seed_length = data_length;
5853     }
5854 
5855     prf->state = TLS12_PRF_STATE_SEED_SET;
5856 
5857     return( PSA_SUCCESS );
5858 }
5859 
psa_tls12_prf_set_key(psa_tls12_prf_key_derivation_t * prf,psa_algorithm_t hash_alg,const uint8_t * data,size_t data_length)5860 static psa_status_t psa_tls12_prf_set_key( psa_tls12_prf_key_derivation_t *prf,
5861                                            psa_algorithm_t hash_alg,
5862                                            const uint8_t *data,
5863                                            size_t data_length )
5864 {
5865     psa_status_t status;
5866     if( prf->state != TLS12_PRF_STATE_SEED_SET )
5867         return( PSA_ERROR_BAD_STATE );
5868 
5869     status = psa_hmac_setup_internal( &prf->hmac, data, data_length, hash_alg );
5870     if( status != PSA_SUCCESS )
5871         return( status );
5872 
5873     prf->state = TLS12_PRF_STATE_KEY_SET;
5874 
5875     return( PSA_SUCCESS );
5876 }
5877 
psa_tls12_prf_set_label(psa_tls12_prf_key_derivation_t * prf,const uint8_t * data,size_t data_length)5878 static psa_status_t psa_tls12_prf_set_label( psa_tls12_prf_key_derivation_t *prf,
5879                                              const uint8_t *data,
5880                                              size_t data_length )
5881 {
5882     if( prf->state != TLS12_PRF_STATE_KEY_SET )
5883         return( PSA_ERROR_BAD_STATE );
5884 
5885     if( data_length != 0 )
5886     {
5887         prf->label = vdb_mbedtls_calloc( 1, data_length );
5888         if( prf->label == NULL )
5889             return( PSA_ERROR_INSUFFICIENT_MEMORY );
5890 
5891         memcpy( prf->label, data, data_length );
5892         prf->label_length = data_length;
5893     }
5894 
5895     prf->state = TLS12_PRF_STATE_LABEL_SET;
5896 
5897     return( PSA_SUCCESS );
5898 }
5899 
psa_tls12_prf_input(psa_tls12_prf_key_derivation_t * prf,psa_algorithm_t hash_alg,psa_key_derivation_step_t step,const uint8_t * data,size_t data_length)5900 static psa_status_t psa_tls12_prf_input( psa_tls12_prf_key_derivation_t *prf,
5901                                          psa_algorithm_t hash_alg,
5902                                          psa_key_derivation_step_t step,
5903                                          const uint8_t *data,
5904                                          size_t data_length )
5905 {
5906     switch( step )
5907     {
5908         case PSA_KEY_DERIVATION_INPUT_SEED:
5909             return( psa_tls12_prf_set_seed( prf, data, data_length ) );
5910         case PSA_KEY_DERIVATION_INPUT_SECRET:
5911             return( psa_tls12_prf_set_key( prf, hash_alg, data, data_length ) );
5912         case PSA_KEY_DERIVATION_INPUT_LABEL:
5913             return( psa_tls12_prf_set_label( prf, data, data_length ) );
5914         default:
5915             return( PSA_ERROR_INVALID_ARGUMENT );
5916     }
5917 }
5918 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) ||
5919         * MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
5920 
5921 #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,psa_algorithm_t hash_alg,const uint8_t * data,size_t data_length)5922 static psa_status_t psa_tls12_prf_psk_to_ms_set_key(
5923     psa_tls12_prf_key_derivation_t *prf,
5924     psa_algorithm_t hash_alg,
5925     const uint8_t *data,
5926     size_t data_length )
5927 {
5928     psa_status_t status;
5929     uint8_t pms[ 4 + 2 * PSA_ALG_TLS12_PSK_TO_MS_MAX_PSK_LEN ];
5930     uint8_t *cur = pms;
5931 
5932     if( data_length > PSA_ALG_TLS12_PSK_TO_MS_MAX_PSK_LEN )
5933         return( PSA_ERROR_INVALID_ARGUMENT );
5934 
5935     /* Quoting RFC 4279, Section 2:
5936      *
5937      * The premaster secret is formed as follows: if the PSK is N octets
5938      * long, concatenate a uint16 with the value N, N zero octets, a second
5939      * uint16 with the value N, and the PSK itself.
5940      */
5941 
5942     *cur++ = ( data_length >> 8 ) & 0xff;
5943     *cur++ = ( data_length >> 0 ) & 0xff;
5944     memset( cur, 0, data_length );
5945     cur += data_length;
5946     *cur++ = pms[0];
5947     *cur++ = pms[1];
5948     memcpy( cur, data, data_length );
5949     cur += data_length;
5950 
5951     status = psa_tls12_prf_set_key( prf, hash_alg, pms, cur - pms );
5952 
5953     vdb_mbedtls_platform_zeroize( pms, sizeof( pms ) );
5954     return( status );
5955 }
5956 
psa_tls12_prf_psk_to_ms_input(psa_tls12_prf_key_derivation_t * prf,psa_algorithm_t hash_alg,psa_key_derivation_step_t step,const uint8_t * data,size_t data_length)5957 static psa_status_t psa_tls12_prf_psk_to_ms_input(
5958     psa_tls12_prf_key_derivation_t *prf,
5959     psa_algorithm_t hash_alg,
5960     psa_key_derivation_step_t step,
5961     const uint8_t *data,
5962     size_t data_length )
5963 {
5964     if( step == PSA_KEY_DERIVATION_INPUT_SECRET )
5965     {
5966         return( psa_tls12_prf_psk_to_ms_set_key( prf, hash_alg,
5967                                                  data, data_length ) );
5968     }
5969 
5970     return( psa_tls12_prf_input( prf, hash_alg, step, data, data_length ) );
5971 }
5972 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
5973 
5974 /** Check whether the given key type is acceptable for the given
5975  * input step of a key derivation.
5976  *
5977  * Secret inputs must have the type #PSA_KEY_TYPE_DERIVE.
5978  * Non-secret inputs must have the type #PSA_KEY_TYPE_RAW_DATA.
5979  * Both secret and non-secret inputs can alternatively have the type
5980  * #PSA_KEY_TYPE_NONE, which is never the type of a key object, meaning
5981  * that the input was passed as a buffer rather than via a key object.
5982  */
psa_key_derivation_check_input_type(psa_key_derivation_step_t step,psa_key_type_t key_type)5983 static int psa_key_derivation_check_input_type(
5984     psa_key_derivation_step_t step,
5985     psa_key_type_t key_type )
5986 {
5987     switch( step )
5988     {
5989         case PSA_KEY_DERIVATION_INPUT_SECRET:
5990             if( key_type == PSA_KEY_TYPE_DERIVE )
5991                 return( PSA_SUCCESS );
5992             if( key_type == PSA_KEY_TYPE_NONE )
5993                 return( PSA_SUCCESS );
5994             break;
5995         case PSA_KEY_DERIVATION_INPUT_LABEL:
5996         case PSA_KEY_DERIVATION_INPUT_SALT:
5997         case PSA_KEY_DERIVATION_INPUT_INFO:
5998         case PSA_KEY_DERIVATION_INPUT_SEED:
5999             if( key_type == PSA_KEY_TYPE_RAW_DATA )
6000                 return( PSA_SUCCESS );
6001             if( key_type == PSA_KEY_TYPE_NONE )
6002                 return( PSA_SUCCESS );
6003             break;
6004     }
6005     return( PSA_ERROR_INVALID_ARGUMENT );
6006 }
6007 
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)6008 static psa_status_t psa_key_derivation_input_internal(
6009     psa_key_derivation_operation_t *operation,
6010     psa_key_derivation_step_t step,
6011     psa_key_type_t key_type,
6012     const uint8_t *data,
6013     size_t data_length )
6014 {
6015     psa_status_t status;
6016     psa_algorithm_t kdf_alg = psa_key_derivation_get_kdf_alg( operation );
6017 
6018     status = psa_key_derivation_check_input_type( step, key_type );
6019     if( status != PSA_SUCCESS )
6020         goto exit;
6021 
6022 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF)
6023     if( PSA_ALG_IS_HKDF( kdf_alg ) )
6024     {
6025         status = psa_hkdf_input( &operation->ctx.hkdf,
6026                                  PSA_ALG_HKDF_GET_HASH( kdf_alg ),
6027                                  step, data, data_length );
6028     }
6029     else
6030 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF */
6031 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF)
6032     if( PSA_ALG_IS_TLS12_PRF( kdf_alg ) )
6033     {
6034         status = psa_tls12_prf_input( &operation->ctx.tls12_prf,
6035                                       PSA_ALG_HKDF_GET_HASH( kdf_alg ),
6036                                       step, data, data_length );
6037     }
6038     else
6039 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF */
6040 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
6041     if( PSA_ALG_IS_TLS12_PSK_TO_MS( kdf_alg ) )
6042     {
6043         status = psa_tls12_prf_psk_to_ms_input( &operation->ctx.tls12_prf,
6044                                                 PSA_ALG_HKDF_GET_HASH( kdf_alg ),
6045                                                 step, data, data_length );
6046     }
6047     else
6048 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
6049     {
6050         /* This can't happen unless the operation object was not initialized */
6051         return( PSA_ERROR_BAD_STATE );
6052     }
6053 
6054 exit:
6055     if( status != PSA_SUCCESS )
6056         psa_key_derivation_abort( operation );
6057     return( status );
6058 }
6059 
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)6060 psa_status_t psa_key_derivation_input_bytes(
6061     psa_key_derivation_operation_t *operation,
6062     psa_key_derivation_step_t step,
6063     const uint8_t *data,
6064     size_t data_length )
6065 {
6066     return( psa_key_derivation_input_internal( operation, step,
6067                                                PSA_KEY_TYPE_NONE,
6068                                                data, data_length ) );
6069 }
6070 
psa_key_derivation_input_key(psa_key_derivation_operation_t * operation,psa_key_derivation_step_t step,mbedtls_svc_key_id_t key)6071 psa_status_t psa_key_derivation_input_key(
6072     psa_key_derivation_operation_t *operation,
6073     psa_key_derivation_step_t step,
6074     mbedtls_svc_key_id_t key )
6075 {
6076     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
6077     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
6078     psa_key_slot_t *slot;
6079 
6080     status = psa_get_and_lock_transparent_key_slot_with_policy(
6081                  key, &slot, PSA_KEY_USAGE_DERIVE, operation->alg );
6082     if( status != PSA_SUCCESS )
6083     {
6084         psa_key_derivation_abort( operation );
6085         return( status );
6086     }
6087 
6088     /* Passing a key object as a SECRET input unlocks the permission
6089      * to output to a key object. */
6090     if( step == PSA_KEY_DERIVATION_INPUT_SECRET )
6091         operation->can_output_key = 1;
6092 
6093     status = psa_key_derivation_input_internal( operation,
6094                                                 step, slot->attr.type,
6095                                                 slot->data.key.data,
6096                                                 slot->data.key.bytes );
6097 
6098     unlock_status = psa_unlock_key_slot( slot );
6099 
6100     return( ( status == PSA_SUCCESS ) ? unlock_status : status );
6101 }
6102 
6103 
6104 
6105 /****************************************************************/
6106 /* Key agreement */
6107 /****************************************************************/
6108 
6109 #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)6110 static psa_status_t psa_key_agreement_ecdh( const uint8_t *peer_key,
6111                                             size_t peer_key_length,
6112                                             const mbedtls_ecp_keypair *our_key,
6113                                             uint8_t *shared_secret,
6114                                             size_t shared_secret_size,
6115                                             size_t *shared_secret_length )
6116 {
6117     mbedtls_ecp_keypair *their_key = NULL;
6118     mbedtls_ecdh_context ecdh;
6119     psa_status_t status;
6120     size_t bits = 0;
6121     psa_ecc_family_t curve = vdb_mbedtls_ecc_group_to_psa( our_key->grp.id, &bits );
6122     vdb_mbedtls_ecdh_init( &ecdh );
6123 
6124     status = psa_load_ecp_representation( PSA_KEY_TYPE_ECC_PUBLIC_KEY(curve),
6125                                           peer_key,
6126                                           peer_key_length,
6127                                           &their_key );
6128     if( status != PSA_SUCCESS )
6129         goto exit;
6130 
6131     status = mbedtls_to_psa_error(
6132         vdb_mbedtls_ecdh_get_params( &ecdh, their_key, MBEDTLS_ECDH_THEIRS ) );
6133     if( status != PSA_SUCCESS )
6134         goto exit;
6135     status = mbedtls_to_psa_error(
6136         vdb_mbedtls_ecdh_get_params( &ecdh, our_key, MBEDTLS_ECDH_OURS ) );
6137     if( status != PSA_SUCCESS )
6138         goto exit;
6139 
6140     status = mbedtls_to_psa_error(
6141         vdb_mbedtls_ecdh_calc_secret( &ecdh,
6142                                   shared_secret_length,
6143                                   shared_secret, shared_secret_size,
6144                                   vdb_mbedtls_ctr_drbg_random,
6145                                   &global_data.ctr_drbg ) );
6146     if( status != PSA_SUCCESS )
6147         goto exit;
6148     if( PSA_BITS_TO_BYTES( bits ) != *shared_secret_length )
6149         status = PSA_ERROR_CORRUPTION_DETECTED;
6150 
6151 exit:
6152     if( status != PSA_SUCCESS )
6153         vdb_mbedtls_platform_zeroize( shared_secret, shared_secret_size );
6154     vdb_mbedtls_ecdh_free( &ecdh );
6155     vdb_mbedtls_ecp_keypair_free( their_key );
6156     vdb_mbedtls_free( their_key );
6157 
6158     return( status );
6159 }
6160 #endif /* MBEDTLS_PSA_BUILTIN_ALG_ECDH */
6161 
6162 #define PSA_KEY_AGREEMENT_MAX_SHARED_SECRET_SIZE MBEDTLS_ECP_MAX_BYTES
6163 
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)6164 static psa_status_t psa_key_agreement_raw_internal( psa_algorithm_t alg,
6165                                                     psa_key_slot_t *private_key,
6166                                                     const uint8_t *peer_key,
6167                                                     size_t peer_key_length,
6168                                                     uint8_t *shared_secret,
6169                                                     size_t shared_secret_size,
6170                                                     size_t *shared_secret_length )
6171 {
6172     switch( alg )
6173     {
6174 #if defined(MBEDTLS_PSA_BUILTIN_ALG_ECDH)
6175         case PSA_ALG_ECDH:
6176             if( ! PSA_KEY_TYPE_IS_ECC_KEY_PAIR( private_key->attr.type ) )
6177                 return( PSA_ERROR_INVALID_ARGUMENT );
6178             mbedtls_ecp_keypair *ecp = NULL;
6179             psa_status_t status = psa_load_ecp_representation(
6180                                     private_key->attr.type,
6181                                     private_key->data.key.data,
6182                                     private_key->data.key.bytes,
6183                                     &ecp );
6184             if( status != PSA_SUCCESS )
6185                 return( status );
6186             status = psa_key_agreement_ecdh( peer_key, peer_key_length,
6187                                              ecp,
6188                                              shared_secret, shared_secret_size,
6189                                              shared_secret_length );
6190             vdb_mbedtls_ecp_keypair_free( ecp );
6191             vdb_mbedtls_free( ecp );
6192             return( status );
6193 #endif /* MBEDTLS_PSA_BUILTIN_ALG_ECDH */
6194         default:
6195             (void) private_key;
6196             (void) peer_key;
6197             (void) peer_key_length;
6198             (void) shared_secret;
6199             (void) shared_secret_size;
6200             (void) shared_secret_length;
6201             return( PSA_ERROR_NOT_SUPPORTED );
6202     }
6203 }
6204 
6205 /* Note that if this function fails, you must call psa_key_derivation_abort()
6206  * to potentially free embedded data structures and wipe confidential data.
6207  */
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)6208 static psa_status_t psa_key_agreement_internal( psa_key_derivation_operation_t *operation,
6209                                                 psa_key_derivation_step_t step,
6210                                                 psa_key_slot_t *private_key,
6211                                                 const uint8_t *peer_key,
6212                                                 size_t peer_key_length )
6213 {
6214     psa_status_t status;
6215     uint8_t shared_secret[PSA_KEY_AGREEMENT_MAX_SHARED_SECRET_SIZE];
6216     size_t shared_secret_length = 0;
6217     psa_algorithm_t ka_alg = PSA_ALG_KEY_AGREEMENT_GET_BASE( operation->alg );
6218 
6219     /* Step 1: run the secret agreement algorithm to generate the shared
6220      * secret. */
6221     status = psa_key_agreement_raw_internal( ka_alg,
6222                                              private_key,
6223                                              peer_key, peer_key_length,
6224                                              shared_secret,
6225                                              sizeof( shared_secret ),
6226                                              &shared_secret_length );
6227     if( status != PSA_SUCCESS )
6228         goto exit;
6229 
6230     /* Step 2: set up the key derivation to generate key material from
6231      * the shared secret. A shared secret is permitted wherever a key
6232      * of type DERIVE is permitted. */
6233     status = psa_key_derivation_input_internal( operation, step,
6234                                                 PSA_KEY_TYPE_DERIVE,
6235                                                 shared_secret,
6236                                                 shared_secret_length );
6237 exit:
6238     vdb_mbedtls_platform_zeroize( shared_secret, shared_secret_length );
6239     return( status );
6240 }
6241 
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)6242 psa_status_t psa_key_derivation_key_agreement( psa_key_derivation_operation_t *operation,
6243                                                psa_key_derivation_step_t step,
6244                                                mbedtls_svc_key_id_t private_key,
6245                                                const uint8_t *peer_key,
6246                                                size_t peer_key_length )
6247 {
6248     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
6249     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
6250     psa_key_slot_t *slot;
6251 
6252     if( ! PSA_ALG_IS_KEY_AGREEMENT( operation->alg ) )
6253         return( PSA_ERROR_INVALID_ARGUMENT );
6254     status = psa_get_and_lock_transparent_key_slot_with_policy(
6255                  private_key, &slot, PSA_KEY_USAGE_DERIVE, operation->alg );
6256     if( status != PSA_SUCCESS )
6257         return( status );
6258     status = psa_key_agreement_internal( operation, step,
6259                                          slot,
6260                                          peer_key, peer_key_length );
6261     if( status != PSA_SUCCESS )
6262         psa_key_derivation_abort( operation );
6263     else
6264     {
6265         /* If a private key has been added as SECRET, we allow the derived
6266          * key material to be used as a key in PSA Crypto. */
6267         if( step == PSA_KEY_DERIVATION_INPUT_SECRET )
6268             operation->can_output_key = 1;
6269     }
6270 
6271     unlock_status = psa_unlock_key_slot( slot );
6272 
6273     return( ( status == PSA_SUCCESS ) ? unlock_status : status );
6274 }
6275 
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)6276 psa_status_t psa_raw_key_agreement( psa_algorithm_t alg,
6277                                     mbedtls_svc_key_id_t private_key,
6278                                     const uint8_t *peer_key,
6279                                     size_t peer_key_length,
6280                                     uint8_t *output,
6281                                     size_t output_size,
6282                                     size_t *output_length )
6283 {
6284     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
6285     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
6286     psa_key_slot_t *slot = NULL;
6287 
6288     if( ! PSA_ALG_IS_KEY_AGREEMENT( alg ) )
6289     {
6290         status = PSA_ERROR_INVALID_ARGUMENT;
6291         goto exit;
6292     }
6293     status = psa_get_and_lock_transparent_key_slot_with_policy(
6294                  private_key, &slot, PSA_KEY_USAGE_DERIVE, alg );
6295     if( status != PSA_SUCCESS )
6296         goto exit;
6297 
6298     status = psa_key_agreement_raw_internal( alg, slot,
6299                                              peer_key, peer_key_length,
6300                                              output, output_size,
6301                                              output_length );
6302 
6303 exit:
6304     if( status != PSA_SUCCESS )
6305     {
6306         /* If an error happens and is not handled properly, the output
6307          * may be used as a key to protect sensitive data. Arrange for such
6308          * a key to be random, which is likely to result in decryption or
6309          * verification errors. This is better than filling the buffer with
6310          * some constant data such as zeros, which would result in the data
6311          * being protected with a reproducible, easily knowable key.
6312          */
6313         psa_generate_random( output, output_size );
6314         *output_length = output_size;
6315     }
6316 
6317     unlock_status = psa_unlock_key_slot( slot );
6318 
6319     return( ( status == PSA_SUCCESS ) ? unlock_status : status );
6320 }
6321 
6322 
6323 /****************************************************************/
6324 /* Random generation */
6325 /****************************************************************/
6326 
psa_generate_random(uint8_t * output,size_t output_size)6327 psa_status_t psa_generate_random( uint8_t *output,
6328                                   size_t output_size )
6329 {
6330     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
6331     GUARD_MODULE_INITIALIZED;
6332 
6333     while( output_size > MBEDTLS_CTR_DRBG_MAX_REQUEST )
6334     {
6335         ret = vdb_mbedtls_ctr_drbg_random( &global_data.ctr_drbg,
6336                                        output,
6337                                        MBEDTLS_CTR_DRBG_MAX_REQUEST );
6338         if( ret != 0 )
6339             return( mbedtls_to_psa_error( ret ) );
6340         output += MBEDTLS_CTR_DRBG_MAX_REQUEST;
6341         output_size -= MBEDTLS_CTR_DRBG_MAX_REQUEST;
6342     }
6343 
6344     ret = vdb_mbedtls_ctr_drbg_random( &global_data.ctr_drbg, output, output_size );
6345     return( mbedtls_to_psa_error( ret ) );
6346 }
6347 
6348 #if defined(MBEDTLS_PSA_INJECT_ENTROPY)
6349 #include "mbedtls/entropy_poll.h"
6350 
mbedtls_psa_inject_entropy(const uint8_t * seed,size_t seed_size)6351 psa_status_t mbedtls_psa_inject_entropy( const uint8_t *seed,
6352                                          size_t seed_size )
6353 {
6354     if( global_data.initialized )
6355         return( PSA_ERROR_NOT_PERMITTED );
6356 
6357     if( ( ( seed_size < MBEDTLS_ENTROPY_MIN_PLATFORM ) ||
6358           ( seed_size < MBEDTLS_ENTROPY_BLOCK_SIZE ) ) ||
6359           ( seed_size > MBEDTLS_ENTROPY_MAX_SEED_SIZE ) )
6360             return( PSA_ERROR_INVALID_ARGUMENT );
6361 
6362     return( mbedtls_psa_storage_inject_entropy( seed, seed_size ) );
6363 }
6364 #endif /* MBEDTLS_PSA_INJECT_ENTROPY */
6365 
6366 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR)
psa_read_rsa_exponent(const uint8_t * domain_parameters,size_t domain_parameters_size,int * exponent)6367 static psa_status_t psa_read_rsa_exponent( const uint8_t *domain_parameters,
6368                                            size_t domain_parameters_size,
6369                                            int *exponent )
6370 {
6371     size_t i;
6372     uint32_t acc = 0;
6373 
6374     if( domain_parameters_size == 0 )
6375     {
6376         *exponent = 65537;
6377         return( PSA_SUCCESS );
6378     }
6379 
6380     /* Mbed TLS encodes the public exponent as an int. For simplicity, only
6381      * support values that fit in a 32-bit integer, which is larger than
6382      * int on just about every platform anyway. */
6383     if( domain_parameters_size > sizeof( acc ) )
6384         return( PSA_ERROR_NOT_SUPPORTED );
6385     for( i = 0; i < domain_parameters_size; i++ )
6386         acc = ( acc << 8 ) | domain_parameters[i];
6387     if( acc > INT_MAX )
6388         return( PSA_ERROR_NOT_SUPPORTED );
6389     *exponent = acc;
6390     return( PSA_SUCCESS );
6391 }
6392 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) */
6393 
psa_generate_key_internal(psa_key_slot_t * slot,size_t bits,const uint8_t * domain_parameters,size_t domain_parameters_size)6394 static psa_status_t psa_generate_key_internal(
6395     psa_key_slot_t *slot, size_t bits,
6396     const uint8_t *domain_parameters, size_t domain_parameters_size )
6397 {
6398     psa_key_type_t type = slot->attr.type;
6399 
6400     if( domain_parameters == NULL && domain_parameters_size != 0 )
6401         return( PSA_ERROR_INVALID_ARGUMENT );
6402 
6403     if( key_type_is_raw_bytes( type ) )
6404     {
6405         psa_status_t status;
6406 
6407         status = validate_unstructured_key_bit_size( slot->attr.type, bits );
6408         if( status != PSA_SUCCESS )
6409             return( status );
6410 
6411         /* Allocate memory for the key */
6412         status = psa_allocate_buffer_to_slot( slot, PSA_BITS_TO_BYTES( bits ) );
6413         if( status != PSA_SUCCESS )
6414             return( status );
6415 
6416         status = psa_generate_random( slot->data.key.data,
6417                                       slot->data.key.bytes );
6418         if( status != PSA_SUCCESS )
6419             return( status );
6420 
6421         slot->attr.bits = (psa_key_bits_t) bits;
6422 #if defined(MBEDTLS_DES_C)
6423         if( type == PSA_KEY_TYPE_DES )
6424             psa_des_set_key_parity( slot->data.key.data,
6425                                     slot->data.key.bytes );
6426 #endif /* MBEDTLS_DES_C */
6427     }
6428     else
6429 
6430 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR)
6431     if ( type == PSA_KEY_TYPE_RSA_KEY_PAIR )
6432     {
6433         mbedtls_rsa_context rsa;
6434         int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
6435         int exponent;
6436         psa_status_t status;
6437         if( bits > PSA_VENDOR_RSA_MAX_KEY_BITS )
6438             return( PSA_ERROR_NOT_SUPPORTED );
6439         /* Accept only byte-aligned keys, for the same reasons as
6440          * in psa_import_rsa_key(). */
6441         if( bits % 8 != 0 )
6442             return( PSA_ERROR_NOT_SUPPORTED );
6443         status = psa_read_rsa_exponent( domain_parameters,
6444                                         domain_parameters_size,
6445                                         &exponent );
6446         if( status != PSA_SUCCESS )
6447             return( status );
6448         vdb_mbedtls_rsa_init( &rsa, MBEDTLS_RSA_PKCS_V15, MBEDTLS_MD_NONE );
6449         ret = vdb_mbedtls_rsa_gen_key( &rsa,
6450                                    vdb_mbedtls_ctr_drbg_random,
6451                                    &global_data.ctr_drbg,
6452                                    (unsigned int) bits,
6453                                    exponent );
6454         if( ret != 0 )
6455             return( mbedtls_to_psa_error( ret ) );
6456 
6457         /* Make sure to always have an export representation available */
6458         size_t bytes = PSA_KEY_EXPORT_RSA_KEY_PAIR_MAX_SIZE( bits );
6459 
6460         status = psa_allocate_buffer_to_slot( slot, bytes );
6461         if( status != PSA_SUCCESS )
6462         {
6463             vdb_mbedtls_rsa_free( &rsa );
6464             return( status );
6465         }
6466 
6467         status = psa_export_rsa_key( type,
6468                                      &rsa,
6469                                      slot->data.key.data,
6470                                      bytes,
6471                                      &slot->data.key.bytes );
6472         vdb_mbedtls_rsa_free( &rsa );
6473         if( status != PSA_SUCCESS )
6474             psa_remove_key_data_from_memory( slot );
6475         return( status );
6476     }
6477     else
6478 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) */
6479 
6480 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR)
6481     if ( PSA_KEY_TYPE_IS_ECC( type ) && PSA_KEY_TYPE_IS_KEY_PAIR( type ) )
6482     {
6483         psa_ecc_family_t curve = PSA_KEY_TYPE_ECC_GET_FAMILY( type );
6484         mbedtls_ecp_group_id grp_id =
6485             vdb_mbedtls_ecc_group_of_psa( curve, PSA_BITS_TO_BYTES( bits ) );
6486         const mbedtls_ecp_curve_info *curve_info =
6487             vdb_mbedtls_ecp_curve_info_from_grp_id( grp_id );
6488         mbedtls_ecp_keypair ecp;
6489         int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
6490         if( domain_parameters_size != 0 )
6491             return( PSA_ERROR_NOT_SUPPORTED );
6492         if( grp_id == MBEDTLS_ECP_DP_NONE || curve_info == NULL )
6493             return( PSA_ERROR_NOT_SUPPORTED );
6494         vdb_mbedtls_ecp_keypair_init( &ecp );
6495         ret = vdb_mbedtls_ecp_gen_key( grp_id, &ecp,
6496                                    vdb_mbedtls_ctr_drbg_random,
6497                                    &global_data.ctr_drbg );
6498         if( ret != 0 )
6499         {
6500             vdb_mbedtls_ecp_keypair_free( &ecp );
6501             return( mbedtls_to_psa_error( ret ) );
6502         }
6503 
6504 
6505         /* Make sure to always have an export representation available */
6506         size_t bytes = PSA_BITS_TO_BYTES( bits );
6507         psa_status_t status = psa_allocate_buffer_to_slot( slot, bytes );
6508         if( status != PSA_SUCCESS )
6509         {
6510             vdb_mbedtls_ecp_keypair_free( &ecp );
6511             return( status );
6512         }
6513 
6514         status = mbedtls_to_psa_error(
6515             vdb_mbedtls_ecp_write_key( &ecp, slot->data.key.data, bytes ) );
6516 
6517         vdb_mbedtls_ecp_keypair_free( &ecp );
6518         if( status != PSA_SUCCESS ) {
6519             memset( slot->data.key.data, 0, bytes );
6520             psa_remove_key_data_from_memory( slot );
6521         }
6522         return( status );
6523     }
6524     else
6525 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) */
6526     {
6527         return( PSA_ERROR_NOT_SUPPORTED );
6528     }
6529 
6530     return( PSA_SUCCESS );
6531 }
6532 
psa_generate_key(const psa_key_attributes_t * attributes,mbedtls_svc_key_id_t * key)6533 psa_status_t psa_generate_key( const psa_key_attributes_t *attributes,
6534                                mbedtls_svc_key_id_t *key )
6535 {
6536     psa_status_t status;
6537     psa_key_slot_t *slot = NULL;
6538     psa_se_drv_table_entry_t *driver = NULL;
6539 
6540     *key = MBEDTLS_SVC_KEY_ID_INIT;
6541 
6542     /* Reject any attempt to create a zero-length key so that we don't
6543      * risk tripping up later, e.g. on a malloc(0) that returns NULL. */
6544     if( psa_get_key_bits( attributes ) == 0 )
6545         return( PSA_ERROR_INVALID_ARGUMENT );
6546 
6547     status = psa_start_key_creation( PSA_KEY_CREATION_GENERATE, attributes,
6548                                      &slot, &driver );
6549     if( status != PSA_SUCCESS )
6550         goto exit;
6551 
6552     status = psa_driver_wrapper_generate_key( attributes,
6553                                               slot );
6554     if( status != PSA_ERROR_NOT_SUPPORTED ||
6555         psa_key_lifetime_is_external( attributes->core.lifetime ) )
6556         goto exit;
6557 
6558     status = psa_generate_key_internal(
6559         slot, attributes->core.bits,
6560         attributes->domain_parameters, attributes->domain_parameters_size );
6561 
6562 exit:
6563     if( status == PSA_SUCCESS )
6564         status = psa_finish_key_creation( slot, driver, key );
6565     if( status != PSA_SUCCESS )
6566         psa_fail_key_creation( slot, driver );
6567 
6568     return( status );
6569 }
6570 
6571 
6572 
6573 /****************************************************************/
6574 /* Module setup */
6575 /****************************************************************/
6576 
mbedtls_psa_crypto_configure_entropy_sources(void (* entropy_init)(mbedtls_entropy_context * ctx),void (* entropy_free)(mbedtls_entropy_context * ctx))6577 psa_status_t mbedtls_psa_crypto_configure_entropy_sources(
6578     void (* entropy_init )( mbedtls_entropy_context *ctx ),
6579     void (* entropy_free )( mbedtls_entropy_context *ctx ) )
6580 {
6581     if( global_data.rng_state != RNG_NOT_INITIALIZED )
6582         return( PSA_ERROR_BAD_STATE );
6583     global_data.entropy_init = entropy_init;
6584     global_data.entropy_free = entropy_free;
6585     return( PSA_SUCCESS );
6586 }
6587 
mbedtls_psa_crypto_free(void)6588 void mbedtls_psa_crypto_free( void )
6589 {
6590     psa_wipe_all_key_slots( );
6591     if( global_data.rng_state != RNG_NOT_INITIALIZED )
6592     {
6593         vdb_mbedtls_ctr_drbg_free( &global_data.ctr_drbg );
6594         global_data.entropy_free( &global_data.entropy );
6595     }
6596     /* Wipe all remaining data, including configuration.
6597      * In particular, this sets all state indicator to the value
6598      * indicating "uninitialized". */
6599     vdb_mbedtls_platform_zeroize( &global_data, sizeof( global_data ) );
6600 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
6601     /* Unregister all secure element drivers, so that we restart from
6602      * a pristine state. */
6603     psa_unregister_all_se_drivers( );
6604 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
6605 }
6606 
6607 #if defined(PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS)
6608 /** Recover a transaction that was interrupted by a power failure.
6609  *
6610  * This function is called during initialization, before psa_crypto_init()
6611  * returns. If this function returns a failure status, the initialization
6612  * fails.
6613  */
psa_crypto_recover_transaction(const psa_crypto_transaction_t * transaction)6614 static psa_status_t psa_crypto_recover_transaction(
6615     const psa_crypto_transaction_t *transaction )
6616 {
6617     switch( transaction->unknown.type )
6618     {
6619         case PSA_CRYPTO_TRANSACTION_CREATE_KEY:
6620         case PSA_CRYPTO_TRANSACTION_DESTROY_KEY:
6621             /* TODO - fall through to the failure case until this
6622              * is implemented.
6623              * https://github.com/ARMmbed/mbed-crypto/issues/218
6624              */
6625         default:
6626             /* We found an unsupported transaction in the storage.
6627              * We don't know what state the storage is in. Give up. */
6628             return( PSA_ERROR_STORAGE_FAILURE );
6629     }
6630 }
6631 #endif /* PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS */
6632 
psa_crypto_init(void)6633 psa_status_t psa_crypto_init( void )
6634 {
6635     psa_status_t status;
6636     const unsigned char drbg_seed[] = "PSA";
6637 
6638     /* Double initialization is explicitly allowed. */
6639     if( global_data.initialized != 0 )
6640         return( PSA_SUCCESS );
6641 
6642     /* Set default configuration if
6643      * mbedtls_psa_crypto_configure_entropy_sources() hasn't been called. */
6644     if( global_data.entropy_init == NULL )
6645         global_data.entropy_init = vdb_mbedtls_entropy_init;
6646     if( global_data.entropy_free == NULL )
6647         global_data.entropy_free = vdb_mbedtls_entropy_free;
6648 
6649     /* Initialize the random generator. */
6650     global_data.entropy_init( &global_data.entropy );
6651 #if defined(MBEDTLS_PSA_INJECT_ENTROPY) && \
6652     defined(MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES)
6653     /* The PSA entropy injection feature depends on using NV seed as an entropy
6654      * source. Add NV seed as an entropy source for PSA entropy injection. */
6655     vdb_mbedtls_entropy_add_source( &global_data.entropy,
6656                                 vdb_mbedtls_nv_seed_poll, NULL,
6657                                 MBEDTLS_ENTROPY_BLOCK_SIZE,
6658                                 MBEDTLS_ENTROPY_SOURCE_STRONG );
6659 #endif
6660     vdb_mbedtls_ctr_drbg_init( &global_data.ctr_drbg );
6661     global_data.rng_state = RNG_INITIALIZED;
6662     status = mbedtls_to_psa_error(
6663         vdb_mbedtls_ctr_drbg_seed( &global_data.ctr_drbg,
6664                                vdb_mbedtls_entropy_func,
6665                                &global_data.entropy,
6666                                drbg_seed, sizeof( drbg_seed ) - 1 ) );
6667     if( status != PSA_SUCCESS )
6668         goto exit;
6669     global_data.rng_state = RNG_SEEDED;
6670 
6671     status = psa_initialize_key_slots( );
6672     if( status != PSA_SUCCESS )
6673         goto exit;
6674 
6675 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
6676     status = psa_init_all_se_drivers( );
6677     if( status != PSA_SUCCESS )
6678         goto exit;
6679 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
6680 
6681 #if defined(PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS)
6682     status = psa_crypto_load_transaction( );
6683     if( status == PSA_SUCCESS )
6684     {
6685         status = psa_crypto_recover_transaction( &psa_crypto_transaction );
6686         if( status != PSA_SUCCESS )
6687             goto exit;
6688         status = psa_crypto_stop_transaction( );
6689     }
6690     else if( status == PSA_ERROR_DOES_NOT_EXIST )
6691     {
6692         /* There's no transaction to complete. It's all good. */
6693         status = PSA_SUCCESS;
6694     }
6695 #endif /* PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS */
6696 
6697     /* All done. */
6698     global_data.initialized = 1;
6699 
6700 exit:
6701     if( status != PSA_SUCCESS )
6702         mbedtls_psa_crypto_free( );
6703     return( status );
6704 }
6705 
6706 #endif /* MBEDTLS_PSA_CRYPTO_C */
6707