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