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 OR GPL-2.0-or-later
7  */
8 
9 #include "common.h"
10 #include "psa_crypto_core_common.h"
11 
12 #if defined(MBEDTLS_PSA_CRYPTO_C)
13 
14 #if defined(MBEDTLS_PSA_CRYPTO_CONFIG)
15 #include "check_crypto_config.h"
16 #endif
17 
18 #include "psa/crypto.h"
19 #include "psa/crypto_values.h"
20 
21 #include "psa_crypto_cipher.h"
22 #include "psa_crypto_core.h"
23 #include "psa_crypto_invasive.h"
24 #include "psa_crypto_driver_wrappers.h"
25 #include "psa_crypto_driver_wrappers_no_static.h"
26 #include "psa_crypto_ecp.h"
27 #include "psa_crypto_ffdh.h"
28 #include "psa_crypto_hash.h"
29 #include "psa_crypto_mac.h"
30 #include "psa_crypto_rsa.h"
31 #include "psa_crypto_ecp.h"
32 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
33 #include "psa_crypto_se.h"
34 #endif
35 #include "psa_crypto_slot_management.h"
36 /* Include internal declarations that are useful for implementing persistently
37  * stored keys. */
38 #include "psa_crypto_storage.h"
39 
40 #include "psa_crypto_random_impl.h"
41 
42 #include <stdlib.h>
43 #include <string.h>
44 #include "mbedtls/platform.h"
45 
46 #include "mbedtls/aes.h"
47 #include "mbedtls/asn1.h"
48 #include "mbedtls/asn1write.h"
49 #include "mbedtls/bignum.h"
50 #include "mbedtls/camellia.h"
51 #include "mbedtls/chacha20.h"
52 #include "mbedtls/chachapoly.h"
53 #include "mbedtls/cipher.h"
54 #include "mbedtls/ccm.h"
55 #include "mbedtls/cmac.h"
56 #include "mbedtls/constant_time.h"
57 #include "mbedtls/des.h"
58 #include "mbedtls/ecdh.h"
59 #include "mbedtls/ecp.h"
60 #include "mbedtls/entropy.h"
61 #include "mbedtls/error.h"
62 #include "mbedtls/gcm.h"
63 #include "mbedtls/md5.h"
64 #include "mbedtls/md.h"
65 #include "mbedtls/pk.h"
66 #include "pk_wrap.h"
67 #include "mbedtls/platform_util.h"
68 #include "mbedtls/error.h"
69 #include "mbedtls/ripemd160.h"
70 #include "mbedtls/rsa.h"
71 #include "mbedtls/sha1.h"
72 #include "mbedtls/sha256.h"
73 #include "mbedtls/sha512.h"
74 #include "md_psa.h"
75 
76 #if defined(PSA_CRYPTO_DRIVER_TFM_BUILTIN_KEY_LOADER)
77 #include "tfm_builtin_key_loader.h"
78 #endif /* PSA_CRYPTO_DRIVER_TFM_BUILTIN_KEY_LOADER */
79 
80 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF) ||          \
81     defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT) ||  \
82     defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXPAND)
83 #define BUILTIN_ALG_ANY_HKDF 1
84 #endif
85 
86 /****************************************************************/
87 /* Global data, support functions and library management */
88 /****************************************************************/
89 
key_type_is_raw_bytes(psa_key_type_t type)90 static int key_type_is_raw_bytes(psa_key_type_t type)
91 {
92     return PSA_KEY_TYPE_IS_UNSTRUCTURED(type);
93 }
94 
95 /* Values for psa_global_data_t::rng_state */
96 #define RNG_NOT_INITIALIZED 0
97 #define RNG_INITIALIZED 1
98 #define RNG_SEEDED 2
99 
100 typedef struct {
101     uint8_t initialized;
102     uint8_t rng_state;
103     uint8_t drivers_initialized;
104     mbedtls_psa_random_context_t rng;
105 } psa_global_data_t;
106 
107 static psa_global_data_t global_data;
108 
109 #if !defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
110 mbedtls_psa_drbg_context_t *const mbedtls_psa_random_state =
111     &global_data.rng.drbg;
112 #endif
113 
114 #define GUARD_MODULE_INITIALIZED        \
115     if (global_data.initialized == 0)  \
116     return PSA_ERROR_BAD_STATE;
117 
psa_can_do_hash(psa_algorithm_t hash_alg)118 int psa_can_do_hash(psa_algorithm_t hash_alg)
119 {
120     (void) hash_alg;
121     return 1;
122 }
123 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_KEY_PAIR_IMPORT) ||       \
124     defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_PUBLIC_KEY) ||     \
125     defined(PSA_WANT_KEY_TYPE_DH_KEY_PAIR_GENERATE)
psa_is_dh_key_size_valid(size_t bits)126 static int psa_is_dh_key_size_valid(size_t bits)
127 {
128     if (bits != 2048 && bits != 3072 && bits != 4096 &&
129         bits != 6144 && bits != 8192) {
130         return 0;
131     }
132 
133     return 1;
134 }
135 #endif /* MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_KEY_PAIR_IMPORT ||
136           MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_PUBLIC_KEY ||
137           PSA_WANT_KEY_TYPE_DH_KEY_PAIR_GENERATE */
138 
mbedtls_to_psa_error(int ret)139 psa_status_t mbedtls_to_psa_error(int ret)
140 {
141     /* Mbed TLS error codes can combine a high-level error code and a
142      * low-level error code. The low-level error usually reflects the
143      * root cause better, so dispatch on that preferably. */
144     int low_level_ret = -(-ret & 0x007f);
145     switch (low_level_ret != 0 ? low_level_ret : ret) {
146         case 0:
147             return PSA_SUCCESS;
148 
149 #if defined(MBEDTLS_AES_C)
150         case MBEDTLS_ERR_AES_INVALID_KEY_LENGTH:
151         case MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH:
152             return PSA_ERROR_NOT_SUPPORTED;
153         case MBEDTLS_ERR_AES_BAD_INPUT_DATA:
154             return PSA_ERROR_INVALID_ARGUMENT;
155 #endif
156 
157 #if defined(MBEDTLS_ASN1_PARSE_C) || defined(MBEDTLS_ASN1_WRITE_C)
158         case MBEDTLS_ERR_ASN1_OUT_OF_DATA:
159         case MBEDTLS_ERR_ASN1_UNEXPECTED_TAG:
160         case MBEDTLS_ERR_ASN1_INVALID_LENGTH:
161         case MBEDTLS_ERR_ASN1_LENGTH_MISMATCH:
162         case MBEDTLS_ERR_ASN1_INVALID_DATA:
163             return PSA_ERROR_INVALID_ARGUMENT;
164         case MBEDTLS_ERR_ASN1_ALLOC_FAILED:
165             return PSA_ERROR_INSUFFICIENT_MEMORY;
166         case MBEDTLS_ERR_ASN1_BUF_TOO_SMALL:
167             return PSA_ERROR_BUFFER_TOO_SMALL;
168 #endif
169 
170 #if defined(MBEDTLS_CAMELLIA_C)
171         case MBEDTLS_ERR_CAMELLIA_BAD_INPUT_DATA:
172         case MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH:
173             return PSA_ERROR_NOT_SUPPORTED;
174 #endif
175 
176 #if defined(MBEDTLS_CCM_C)
177         case MBEDTLS_ERR_CCM_BAD_INPUT:
178             return PSA_ERROR_INVALID_ARGUMENT;
179         case MBEDTLS_ERR_CCM_AUTH_FAILED:
180             return PSA_ERROR_INVALID_SIGNATURE;
181 #endif
182 
183 #if defined(MBEDTLS_CHACHA20_C)
184         case MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA:
185             return PSA_ERROR_INVALID_ARGUMENT;
186 #endif
187 
188 #if defined(MBEDTLS_CHACHAPOLY_C)
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 #endif
194 
195 #if defined(MBEDTLS_CIPHER_C)
196         case MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE:
197             return PSA_ERROR_NOT_SUPPORTED;
198         case MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA:
199             return PSA_ERROR_INVALID_ARGUMENT;
200         case MBEDTLS_ERR_CIPHER_ALLOC_FAILED:
201             return PSA_ERROR_INSUFFICIENT_MEMORY;
202         case MBEDTLS_ERR_CIPHER_INVALID_PADDING:
203             return PSA_ERROR_INVALID_PADDING;
204         case MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED:
205             return PSA_ERROR_INVALID_ARGUMENT;
206         case MBEDTLS_ERR_CIPHER_AUTH_FAILED:
207             return PSA_ERROR_INVALID_SIGNATURE;
208         case MBEDTLS_ERR_CIPHER_INVALID_CONTEXT:
209             return PSA_ERROR_CORRUPTION_DETECTED;
210 #endif
211 
212 #if !(defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG) ||      \
213             defined(MBEDTLS_PSA_HMAC_DRBG_MD_TYPE))
214         /* Only check CTR_DRBG error codes if underlying mbedtls_xxx
215          * functions are passed a CTR_DRBG instance. */
216         case MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED:
217             return PSA_ERROR_INSUFFICIENT_ENTROPY;
218         case MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG:
219         case MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG:
220             return PSA_ERROR_NOT_SUPPORTED;
221         case MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR:
222             return PSA_ERROR_INSUFFICIENT_ENTROPY;
223 #endif
224 
225 #if defined(MBEDTLS_DES_C)
226         case MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH:
227             return PSA_ERROR_NOT_SUPPORTED;
228 #endif
229 
230         case MBEDTLS_ERR_ENTROPY_NO_SOURCES_DEFINED:
231         case MBEDTLS_ERR_ENTROPY_NO_STRONG_SOURCE:
232         case MBEDTLS_ERR_ENTROPY_SOURCE_FAILED:
233             return PSA_ERROR_INSUFFICIENT_ENTROPY;
234 
235 #if defined(MBEDTLS_GCM_C)
236         case MBEDTLS_ERR_GCM_AUTH_FAILED:
237             return PSA_ERROR_INVALID_SIGNATURE;
238         case MBEDTLS_ERR_GCM_BUFFER_TOO_SMALL:
239             return PSA_ERROR_BUFFER_TOO_SMALL;
240         case MBEDTLS_ERR_GCM_BAD_INPUT:
241             return PSA_ERROR_INVALID_ARGUMENT;
242 #endif
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 #if defined(MBEDTLS_MD_LIGHT)
258         case MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE:
259             return PSA_ERROR_NOT_SUPPORTED;
260         case MBEDTLS_ERR_MD_BAD_INPUT_DATA:
261             return PSA_ERROR_INVALID_ARGUMENT;
262         case MBEDTLS_ERR_MD_ALLOC_FAILED:
263             return PSA_ERROR_INSUFFICIENT_MEMORY;
264 #if defined(MBEDTLS_FS_IO)
265         case MBEDTLS_ERR_MD_FILE_IO_ERROR:
266             return PSA_ERROR_STORAGE_FAILURE;
267 #endif
268 #endif
269 
270 #if defined(MBEDTLS_BIGNUM_C)
271 #if defined(MBEDTLS_FS_IO)
272         case MBEDTLS_ERR_MPI_FILE_IO_ERROR:
273             return PSA_ERROR_STORAGE_FAILURE;
274 #endif
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 #endif
290 
291 #if defined(MBEDTLS_PK_C)
292         case MBEDTLS_ERR_PK_ALLOC_FAILED:
293             return PSA_ERROR_INSUFFICIENT_MEMORY;
294         case MBEDTLS_ERR_PK_TYPE_MISMATCH:
295         case MBEDTLS_ERR_PK_BAD_INPUT_DATA:
296             return PSA_ERROR_INVALID_ARGUMENT;
297 #if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) || defined(MBEDTLS_FS_IO) || \
298             defined(MBEDTLS_PSA_ITS_FILE_C)
299         case MBEDTLS_ERR_PK_FILE_IO_ERROR:
300             return PSA_ERROR_STORAGE_FAILURE;
301 #endif
302         case MBEDTLS_ERR_PK_KEY_INVALID_VERSION:
303         case MBEDTLS_ERR_PK_KEY_INVALID_FORMAT:
304             return PSA_ERROR_INVALID_ARGUMENT;
305         case MBEDTLS_ERR_PK_UNKNOWN_PK_ALG:
306             return PSA_ERROR_NOT_SUPPORTED;
307         case MBEDTLS_ERR_PK_PASSWORD_REQUIRED:
308         case MBEDTLS_ERR_PK_PASSWORD_MISMATCH:
309             return PSA_ERROR_NOT_PERMITTED;
310         case MBEDTLS_ERR_PK_INVALID_PUBKEY:
311             return PSA_ERROR_INVALID_ARGUMENT;
312         case MBEDTLS_ERR_PK_INVALID_ALG:
313         case MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE:
314         case MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE:
315             return PSA_ERROR_NOT_SUPPORTED;
316         case MBEDTLS_ERR_PK_SIG_LEN_MISMATCH:
317             return PSA_ERROR_INVALID_SIGNATURE;
318         case MBEDTLS_ERR_PK_BUFFER_TOO_SMALL:
319             return PSA_ERROR_BUFFER_TOO_SMALL;
320 #endif
321 
322         case MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED:
323             return PSA_ERROR_HARDWARE_FAILURE;
324         case MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED:
325             return PSA_ERROR_NOT_SUPPORTED;
326 
327 #if defined(MBEDTLS_RSA_C)
328         case MBEDTLS_ERR_RSA_BAD_INPUT_DATA:
329             return PSA_ERROR_INVALID_ARGUMENT;
330         case MBEDTLS_ERR_RSA_INVALID_PADDING:
331             return PSA_ERROR_INVALID_PADDING;
332         case MBEDTLS_ERR_RSA_KEY_GEN_FAILED:
333             return PSA_ERROR_HARDWARE_FAILURE;
334         case MBEDTLS_ERR_RSA_KEY_CHECK_FAILED:
335             return PSA_ERROR_INVALID_ARGUMENT;
336         case MBEDTLS_ERR_RSA_PUBLIC_FAILED:
337         case MBEDTLS_ERR_RSA_PRIVATE_FAILED:
338             return PSA_ERROR_CORRUPTION_DETECTED;
339         case MBEDTLS_ERR_RSA_VERIFY_FAILED:
340             return PSA_ERROR_INVALID_SIGNATURE;
341         case MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE:
342             return PSA_ERROR_BUFFER_TOO_SMALL;
343         case MBEDTLS_ERR_RSA_RNG_FAILED:
344             return PSA_ERROR_INSUFFICIENT_ENTROPY;
345 #endif
346 
347 #if defined(MBEDTLS_ECP_LIGHT)
348         case MBEDTLS_ERR_ECP_BAD_INPUT_DATA:
349         case MBEDTLS_ERR_ECP_INVALID_KEY:
350             return PSA_ERROR_INVALID_ARGUMENT;
351         case MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL:
352             return PSA_ERROR_BUFFER_TOO_SMALL;
353         case MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE:
354             return PSA_ERROR_NOT_SUPPORTED;
355         case MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH:
356         case MBEDTLS_ERR_ECP_VERIFY_FAILED:
357             return PSA_ERROR_INVALID_SIGNATURE;
358         case MBEDTLS_ERR_ECP_ALLOC_FAILED:
359             return PSA_ERROR_INSUFFICIENT_MEMORY;
360         case MBEDTLS_ERR_ECP_RANDOM_FAILED:
361             return PSA_ERROR_INSUFFICIENT_ENTROPY;
362 
363 #if defined(MBEDTLS_ECP_RESTARTABLE)
364         case MBEDTLS_ERR_ECP_IN_PROGRESS:
365             return PSA_OPERATION_INCOMPLETE;
366 #endif
367 #endif
368 
369         case MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED:
370             return PSA_ERROR_CORRUPTION_DETECTED;
371 
372         default:
373             return PSA_ERROR_GENERIC_ERROR;
374     }
375 }
376 
377 /**
378  * \brief                       For output buffers which contain "tags"
379  *                              (outputs that may be checked for validity like
380  *                              hashes, MACs and signatures), fill the unused
381  *                              part of the output buffer (the whole buffer on
382  *                              error, the trailing part on success) with
383  *                              something that isn't a valid tag (barring an
384  *                              attack on the tag and deliberately-crafted
385  *                              input), in case the caller doesn't check the
386  *                              return status properly.
387  *
388  * \param output_buffer         Pointer to buffer to wipe. May not be NULL
389  *                              unless \p output_buffer_size is zero.
390  * \param status                Status of function called to generate
391  *                              output_buffer originally
392  * \param output_buffer_size    Size of output buffer. If zero, \p output_buffer
393  *                              could be NULL.
394  * \param output_buffer_length  Length of data written to output_buffer, must be
395  *                              less than \p output_buffer_size
396  */
psa_wipe_tag_output_buffer(uint8_t * output_buffer,psa_status_t status,size_t output_buffer_size,size_t output_buffer_length)397 static void psa_wipe_tag_output_buffer(uint8_t *output_buffer, psa_status_t status,
398                                        size_t output_buffer_size, size_t output_buffer_length)
399 {
400     size_t offset = 0;
401 
402     if (output_buffer_size == 0) {
403         /* If output_buffer_size is 0 then we have nothing to do. We must not
404            call memset because output_buffer may be NULL in this case */
405         return;
406     }
407 
408     if (status == PSA_SUCCESS) {
409         offset = output_buffer_length;
410     }
411 
412     memset(output_buffer + offset, '!', output_buffer_size - offset);
413 }
414 
415 
psa_validate_unstructured_key_bit_size(psa_key_type_t type,size_t bits)416 psa_status_t psa_validate_unstructured_key_bit_size(psa_key_type_t type,
417                                                     size_t bits)
418 {
419     /* Check that the bit size is acceptable for the key type */
420     switch (type) {
421         case PSA_KEY_TYPE_RAW_DATA:
422         case PSA_KEY_TYPE_HMAC:
423         case PSA_KEY_TYPE_DERIVE:
424         case PSA_KEY_TYPE_PASSWORD:
425         case PSA_KEY_TYPE_PASSWORD_HASH:
426             break;
427 #if defined(PSA_WANT_KEY_TYPE_AES)
428         case PSA_KEY_TYPE_AES:
429             if (bits != 128 && bits != 192 && bits != 256) {
430                 return PSA_ERROR_INVALID_ARGUMENT;
431             }
432             break;
433 #endif
434 #if defined(PSA_WANT_KEY_TYPE_ARIA)
435         case PSA_KEY_TYPE_ARIA:
436             if (bits != 128 && bits != 192 && bits != 256) {
437                 return PSA_ERROR_INVALID_ARGUMENT;
438             }
439             break;
440 #endif
441 #if defined(PSA_WANT_KEY_TYPE_CAMELLIA)
442         case PSA_KEY_TYPE_CAMELLIA:
443             if (bits != 128 && bits != 192 && bits != 256) {
444                 return PSA_ERROR_INVALID_ARGUMENT;
445             }
446             break;
447 #endif
448 #if defined(PSA_WANT_KEY_TYPE_DES)
449         case PSA_KEY_TYPE_DES:
450             if (bits != 64 && bits != 128 && bits != 192) {
451                 return PSA_ERROR_INVALID_ARGUMENT;
452             }
453             break;
454 #endif
455 #if defined(PSA_WANT_KEY_TYPE_CHACHA20)
456         case PSA_KEY_TYPE_CHACHA20:
457             if (bits != 256) {
458                 return PSA_ERROR_INVALID_ARGUMENT;
459             }
460             break;
461 #endif
462         default:
463             return PSA_ERROR_NOT_SUPPORTED;
464     }
465     if (bits % 8 != 0) {
466         return PSA_ERROR_INVALID_ARGUMENT;
467     }
468 
469     return PSA_SUCCESS;
470 }
471 
472 /** Check whether a given key type is valid for use with a given MAC algorithm
473  *
474  * Upon successful return of this function, the behavior of #PSA_MAC_LENGTH
475  * when called with the validated \p algorithm and \p key_type is well-defined.
476  *
477  * \param[in] algorithm     The specific MAC algorithm (can be wildcard).
478  * \param[in] key_type      The key type of the key to be used with the
479  *                          \p algorithm.
480  *
481  * \retval #PSA_SUCCESS
482  *         The \p key_type is valid for use with the \p algorithm
483  * \retval #PSA_ERROR_INVALID_ARGUMENT
484  *         The \p key_type is not valid for use with the \p algorithm
485  */
psa_mac_key_can_do(psa_algorithm_t algorithm,psa_key_type_t key_type)486 MBEDTLS_STATIC_TESTABLE psa_status_t psa_mac_key_can_do(
487     psa_algorithm_t algorithm,
488     psa_key_type_t key_type)
489 {
490     if (PSA_ALG_IS_HMAC(algorithm)) {
491         if (key_type == PSA_KEY_TYPE_HMAC) {
492             return PSA_SUCCESS;
493         }
494     }
495 
496     if (PSA_ALG_IS_BLOCK_CIPHER_MAC(algorithm)) {
497         /* Check that we're calling PSA_BLOCK_CIPHER_BLOCK_LENGTH with a cipher
498          * key. */
499         if ((key_type & PSA_KEY_TYPE_CATEGORY_MASK) ==
500             PSA_KEY_TYPE_CATEGORY_SYMMETRIC) {
501             /* PSA_BLOCK_CIPHER_BLOCK_LENGTH returns 1 for stream ciphers and
502              * the block length (larger than 1) for block ciphers. */
503             if (PSA_BLOCK_CIPHER_BLOCK_LENGTH(key_type) > 1) {
504                 return PSA_SUCCESS;
505             }
506         }
507     }
508 
509     return PSA_ERROR_INVALID_ARGUMENT;
510 }
511 
psa_allocate_buffer_to_slot(psa_key_slot_t * slot,size_t buffer_length)512 psa_status_t psa_allocate_buffer_to_slot(psa_key_slot_t *slot,
513                                          size_t buffer_length)
514 {
515     if (slot->key.data != NULL) {
516         return PSA_ERROR_ALREADY_EXISTS;
517     }
518 
519     slot->key.data = mbedtls_calloc(1, buffer_length);
520     if (slot->key.data == NULL) {
521         return PSA_ERROR_INSUFFICIENT_MEMORY;
522     }
523 
524     slot->key.bytes = buffer_length;
525     return PSA_SUCCESS;
526 }
527 
psa_copy_key_material_into_slot(psa_key_slot_t * slot,const uint8_t * data,size_t data_length)528 psa_status_t psa_copy_key_material_into_slot(psa_key_slot_t *slot,
529                                              const uint8_t *data,
530                                              size_t data_length)
531 {
532     psa_status_t status = psa_allocate_buffer_to_slot(slot,
533                                                       data_length);
534     if (status != PSA_SUCCESS) {
535         return status;
536     }
537 
538     memcpy(slot->key.data, data, data_length);
539     return PSA_SUCCESS;
540 }
541 
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)542 psa_status_t psa_import_key_into_slot(
543     const psa_key_attributes_t *attributes,
544     const uint8_t *data, size_t data_length,
545     uint8_t *key_buffer, size_t key_buffer_size,
546     size_t *key_buffer_length, size_t *bits)
547 {
548     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
549     psa_key_type_t type = attributes->core.type;
550 
551     /* zero-length keys are never supported. */
552     if (data_length == 0) {
553         return PSA_ERROR_NOT_SUPPORTED;
554     }
555 
556     if (key_type_is_raw_bytes(type)) {
557         *bits = PSA_BYTES_TO_BITS(data_length);
558 
559         status = psa_validate_unstructured_key_bit_size(attributes->core.type,
560                                                         *bits);
561         if (status != PSA_SUCCESS) {
562             return status;
563         }
564 
565         /* Copy the key material. */
566         memcpy(key_buffer, data, data_length);
567         *key_buffer_length = data_length;
568         (void) key_buffer_size;
569 
570         return PSA_SUCCESS;
571     } else if (PSA_KEY_TYPE_IS_ASYMMETRIC(type)) {
572 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_KEY_PAIR_IMPORT) || \
573         defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_PUBLIC_KEY)
574         if (PSA_KEY_TYPE_IS_DH(type)) {
575             if (psa_is_dh_key_size_valid(PSA_BYTES_TO_BITS(data_length)) == 0) {
576                 return PSA_ERROR_INVALID_ARGUMENT;
577             }
578             return mbedtls_psa_ffdh_import_key(attributes,
579                                                data, data_length,
580                                                key_buffer, key_buffer_size,
581                                                key_buffer_length,
582                                                bits);
583         }
584 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_KEY_PAIR_IMPORT) ||
585         * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_PUBLIC_KEY) */
586 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_IMPORT) || \
587         defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY)
588         if (PSA_KEY_TYPE_IS_ECC(type)) {
589             return mbedtls_psa_ecp_import_key(attributes,
590                                               data, data_length,
591                                               key_buffer, key_buffer_size,
592                                               key_buffer_length,
593                                               bits);
594         }
595 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_IMPORT) ||
596         * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY) */
597 #if (defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_IMPORT) && \
598         defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_EXPORT)) || \
599         defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY)
600         if (PSA_KEY_TYPE_IS_RSA(type)) {
601             return mbedtls_psa_rsa_import_key(attributes,
602                                               data, data_length,
603                                               key_buffer, key_buffer_size,
604                                               key_buffer_length,
605                                               bits);
606         }
607 #endif /* (defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_IMPORT) &&
608            defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_EXPORT)) ||
609         * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY) */
610     }
611 
612     return PSA_ERROR_NOT_SUPPORTED;
613 }
614 
615 /** Calculate the intersection of two algorithm usage policies.
616  *
617  * Return 0 (which allows no operation) on incompatibility.
618  */
psa_key_policy_algorithm_intersection(psa_key_type_t key_type,psa_algorithm_t alg1,psa_algorithm_t alg2)619 static psa_algorithm_t psa_key_policy_algorithm_intersection(
620     psa_key_type_t key_type,
621     psa_algorithm_t alg1,
622     psa_algorithm_t alg2)
623 {
624     /* Common case: both sides actually specify the same policy. */
625     if (alg1 == alg2) {
626         return alg1;
627     }
628     /* If the policies are from the same hash-and-sign family, check
629      * if one is a wildcard. If so the other has the specific algorithm. */
630     if (PSA_ALG_IS_SIGN_HASH(alg1) &&
631         PSA_ALG_IS_SIGN_HASH(alg2) &&
632         (alg1 & ~PSA_ALG_HASH_MASK) == (alg2 & ~PSA_ALG_HASH_MASK)) {
633         if (PSA_ALG_SIGN_GET_HASH(alg1) == PSA_ALG_ANY_HASH) {
634             return alg2;
635         }
636         if (PSA_ALG_SIGN_GET_HASH(alg2) == PSA_ALG_ANY_HASH) {
637             return alg1;
638         }
639     }
640     /* If the policies are from the same AEAD family, check whether
641      * one of them is a minimum-tag-length wildcard. Calculate the most
642      * restrictive tag length. */
643     if (PSA_ALG_IS_AEAD(alg1) && PSA_ALG_IS_AEAD(alg2) &&
644         (PSA_ALG_AEAD_WITH_SHORTENED_TAG(alg1, 0) ==
645          PSA_ALG_AEAD_WITH_SHORTENED_TAG(alg2, 0))) {
646         size_t alg1_len = PSA_ALG_AEAD_GET_TAG_LENGTH(alg1);
647         size_t alg2_len = PSA_ALG_AEAD_GET_TAG_LENGTH(alg2);
648         size_t restricted_len = alg1_len > alg2_len ? alg1_len : alg2_len;
649 
650         /* If both are wildcards, return most restrictive wildcard */
651         if (((alg1 & PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG) != 0) &&
652             ((alg2 & PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG) != 0)) {
653             return PSA_ALG_AEAD_WITH_AT_LEAST_THIS_LENGTH_TAG(
654                 alg1, restricted_len);
655         }
656         /* If only one is a wildcard, return specific algorithm if compatible. */
657         if (((alg1 & PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG) != 0) &&
658             (alg1_len <= alg2_len)) {
659             return alg2;
660         }
661         if (((alg2 & PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG) != 0) &&
662             (alg2_len <= alg1_len)) {
663             return alg1;
664         }
665     }
666     /* If the policies are from the same MAC family, check whether one
667      * of them is a minimum-MAC-length policy. Calculate the most
668      * restrictive tag length. */
669     if (PSA_ALG_IS_MAC(alg1) && PSA_ALG_IS_MAC(alg2) &&
670         (PSA_ALG_FULL_LENGTH_MAC(alg1) ==
671          PSA_ALG_FULL_LENGTH_MAC(alg2))) {
672         /* Validate the combination of key type and algorithm. Since the base
673          * algorithm of alg1 and alg2 are the same, we only need this once. */
674         if (PSA_SUCCESS != psa_mac_key_can_do(alg1, key_type)) {
675             return 0;
676         }
677 
678         /* Get the (exact or at-least) output lengths for both sides of the
679          * requested intersection. None of the currently supported algorithms
680          * have an output length dependent on the actual key size, so setting it
681          * to a bogus value of 0 is currently OK.
682          *
683          * Note that for at-least-this-length wildcard algorithms, the output
684          * length is set to the shortest allowed length, which allows us to
685          * calculate the most restrictive tag length for the intersection. */
686         size_t alg1_len = PSA_MAC_LENGTH(key_type, 0, alg1);
687         size_t alg2_len = PSA_MAC_LENGTH(key_type, 0, alg2);
688         size_t restricted_len = alg1_len > alg2_len ? alg1_len : alg2_len;
689 
690         /* If both are wildcards, return most restrictive wildcard */
691         if (((alg1 & PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG) != 0) &&
692             ((alg2 & PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG) != 0)) {
693             return PSA_ALG_AT_LEAST_THIS_LENGTH_MAC(alg1, restricted_len);
694         }
695 
696         /* If only one is an at-least-this-length policy, the intersection would
697          * be the other (fixed-length) policy as long as said fixed length is
698          * equal to or larger than the shortest allowed length. */
699         if ((alg1 & PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG) != 0) {
700             return (alg1_len <= alg2_len) ? alg2 : 0;
701         }
702         if ((alg2 & PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG) != 0) {
703             return (alg2_len <= alg1_len) ? alg1 : 0;
704         }
705 
706         /* If none of them are wildcards, check whether they define the same tag
707          * length. This is still possible here when one is default-length and
708          * the other specific-length. Ensure to always return the
709          * specific-length version for the intersection. */
710         if (alg1_len == alg2_len) {
711             return PSA_ALG_TRUNCATED_MAC(alg1, alg1_len);
712         }
713     }
714     /* If the policies are incompatible, allow nothing. */
715     return 0;
716 }
717 
psa_key_algorithm_permits(psa_key_type_t key_type,psa_algorithm_t policy_alg,psa_algorithm_t requested_alg)718 static int psa_key_algorithm_permits(psa_key_type_t key_type,
719                                      psa_algorithm_t policy_alg,
720                                      psa_algorithm_t requested_alg)
721 {
722     /* Common case: the policy only allows requested_alg. */
723     if (requested_alg == policy_alg) {
724         return 1;
725     }
726     /* If policy_alg is a hash-and-sign with a wildcard for the hash,
727      * and requested_alg is the same hash-and-sign family with any hash,
728      * then requested_alg is compliant with policy_alg. */
729     if (PSA_ALG_IS_SIGN_HASH(requested_alg) &&
730         PSA_ALG_SIGN_GET_HASH(policy_alg) == PSA_ALG_ANY_HASH) {
731         return (policy_alg & ~PSA_ALG_HASH_MASK) ==
732                (requested_alg & ~PSA_ALG_HASH_MASK);
733     }
734     /* If policy_alg is a wildcard AEAD algorithm of the same base as
735      * the requested algorithm, check the requested tag length to be
736      * equal-length or longer than the wildcard-specified length. */
737     if (PSA_ALG_IS_AEAD(policy_alg) &&
738         PSA_ALG_IS_AEAD(requested_alg) &&
739         (PSA_ALG_AEAD_WITH_SHORTENED_TAG(policy_alg, 0) ==
740          PSA_ALG_AEAD_WITH_SHORTENED_TAG(requested_alg, 0)) &&
741         ((policy_alg & PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG) != 0)) {
742         return PSA_ALG_AEAD_GET_TAG_LENGTH(policy_alg) <=
743                PSA_ALG_AEAD_GET_TAG_LENGTH(requested_alg);
744     }
745     /* If policy_alg is a MAC algorithm of the same base as the requested
746      * algorithm, check whether their MAC lengths are compatible. */
747     if (PSA_ALG_IS_MAC(policy_alg) &&
748         PSA_ALG_IS_MAC(requested_alg) &&
749         (PSA_ALG_FULL_LENGTH_MAC(policy_alg) ==
750          PSA_ALG_FULL_LENGTH_MAC(requested_alg))) {
751         /* Validate the combination of key type and algorithm. Since the policy
752          * and requested algorithms are the same, we only need this once. */
753         if (PSA_SUCCESS != psa_mac_key_can_do(policy_alg, key_type)) {
754             return 0;
755         }
756 
757         /* Get both the requested output length for the algorithm which is to be
758          * verified, and the default output length for the base algorithm.
759          * Note that none of the currently supported algorithms have an output
760          * length dependent on actual key size, so setting it to a bogus value
761          * of 0 is currently OK. */
762         size_t requested_output_length = PSA_MAC_LENGTH(
763             key_type, 0, requested_alg);
764         size_t default_output_length = PSA_MAC_LENGTH(
765             key_type, 0,
766             PSA_ALG_FULL_LENGTH_MAC(requested_alg));
767 
768         /* If the policy is default-length, only allow an algorithm with
769          * a declared exact-length matching the default. */
770         if (PSA_MAC_TRUNCATED_LENGTH(policy_alg) == 0) {
771             return requested_output_length == default_output_length;
772         }
773 
774         /* If the requested algorithm is default-length, allow it if the policy
775          * length exactly matches the default length. */
776         if (PSA_MAC_TRUNCATED_LENGTH(requested_alg) == 0 &&
777             PSA_MAC_TRUNCATED_LENGTH(policy_alg) == default_output_length) {
778             return 1;
779         }
780 
781         /* If policy_alg is an at-least-this-length wildcard MAC algorithm,
782          * check for the requested MAC length to be equal to or longer than the
783          * minimum allowed length. */
784         if ((policy_alg & PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG) != 0) {
785             return PSA_MAC_TRUNCATED_LENGTH(policy_alg) <=
786                    requested_output_length;
787         }
788     }
789     /* If policy_alg is a generic key agreement operation, then using it for
790      * a key derivation with that key agreement should also be allowed. This
791      * behaviour is expected to be defined in a future specification version. */
792     if (PSA_ALG_IS_RAW_KEY_AGREEMENT(policy_alg) &&
793         PSA_ALG_IS_KEY_AGREEMENT(requested_alg)) {
794         return PSA_ALG_KEY_AGREEMENT_GET_BASE(requested_alg) ==
795                policy_alg;
796     }
797     /* If it isn't explicitly permitted, it's forbidden. */
798     return 0;
799 }
800 
801 /** Test whether a policy permits an algorithm.
802  *
803  * The caller must test usage flags separately.
804  *
805  * \note This function requires providing the key type for which the policy is
806  *       being validated, since some algorithm policy definitions (e.g. MAC)
807  *       have different properties depending on what kind of cipher it is
808  *       combined with.
809  *
810  * \retval PSA_SUCCESS                  When \p alg is a specific algorithm
811  *                                      allowed by the \p policy.
812  * \retval PSA_ERROR_INVALID_ARGUMENT   When \p alg is not a specific algorithm
813  * \retval PSA_ERROR_NOT_PERMITTED      When \p alg is a specific algorithm, but
814  *                                      the \p policy does not allow it.
815  */
psa_key_policy_permits(const psa_key_policy_t * policy,psa_key_type_t key_type,psa_algorithm_t alg)816 static psa_status_t psa_key_policy_permits(const psa_key_policy_t *policy,
817                                            psa_key_type_t key_type,
818                                            psa_algorithm_t alg)
819 {
820     /* '0' is not a valid algorithm */
821     if (alg == 0) {
822         return PSA_ERROR_INVALID_ARGUMENT;
823     }
824 
825     /* A requested algorithm cannot be a wildcard. */
826     if (PSA_ALG_IS_WILDCARD(alg)) {
827         return PSA_ERROR_INVALID_ARGUMENT;
828     }
829 
830     if (psa_key_algorithm_permits(key_type, policy->alg, alg) ||
831         psa_key_algorithm_permits(key_type, policy->alg2, alg)) {
832         return PSA_SUCCESS;
833     } else {
834         return PSA_ERROR_NOT_PERMITTED;
835     }
836 }
837 
838 /** Restrict a key policy based on a constraint.
839  *
840  * \note This function requires providing the key type for which the policy is
841  *       being restricted, since some algorithm policy definitions (e.g. MAC)
842  *       have different properties depending on what kind of cipher it is
843  *       combined with.
844  *
845  * \param[in] key_type      The key type for which to restrict the policy
846  * \param[in,out] policy    The policy to restrict.
847  * \param[in] constraint    The policy constraint to apply.
848  *
849  * \retval #PSA_SUCCESS
850  *         \c *policy contains the intersection of the original value of
851  *         \c *policy and \c *constraint.
852  * \retval #PSA_ERROR_INVALID_ARGUMENT
853  *         \c key_type, \c *policy and \c *constraint are incompatible.
854  *         \c *policy is unchanged.
855  */
psa_restrict_key_policy(psa_key_type_t key_type,psa_key_policy_t * policy,const psa_key_policy_t * constraint)856 static psa_status_t psa_restrict_key_policy(
857     psa_key_type_t key_type,
858     psa_key_policy_t *policy,
859     const psa_key_policy_t *constraint)
860 {
861     psa_algorithm_t intersection_alg =
862         psa_key_policy_algorithm_intersection(key_type, policy->alg,
863                                               constraint->alg);
864     psa_algorithm_t intersection_alg2 =
865         psa_key_policy_algorithm_intersection(key_type, policy->alg2,
866                                               constraint->alg2);
867     if (intersection_alg == 0 && policy->alg != 0 && constraint->alg != 0) {
868         return PSA_ERROR_INVALID_ARGUMENT;
869     }
870     if (intersection_alg2 == 0 && policy->alg2 != 0 && constraint->alg2 != 0) {
871         return PSA_ERROR_INVALID_ARGUMENT;
872     }
873     policy->usage &= constraint->usage;
874     policy->alg = intersection_alg;
875     policy->alg2 = intersection_alg2;
876     return PSA_SUCCESS;
877 }
878 
879 /** Get the description of a key given its identifier and policy constraints
880  *  and lock it.
881  *
882  * The key must have allow all the usage flags set in \p usage. If \p alg is
883  * nonzero, the key must allow operations with this algorithm. If \p alg is
884  * zero, the algorithm is not checked.
885  *
886  * In case of a persistent key, the function loads the description of the key
887  * into a key slot if not already done.
888  *
889  * On success, the returned key slot is locked. It is the responsibility of
890  * the caller to unlock the key slot when it does not access it anymore.
891  */
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)892 static psa_status_t psa_get_and_lock_key_slot_with_policy(
893     mbedtls_svc_key_id_t key,
894     psa_key_slot_t **p_slot,
895     psa_key_usage_t usage,
896     psa_algorithm_t alg)
897 {
898     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
899     psa_key_slot_t *slot = NULL;
900 
901     status = psa_get_and_lock_key_slot(key, p_slot);
902     if (status != PSA_SUCCESS) {
903         return status;
904     }
905     slot = *p_slot;
906 
907     /* Enforce that usage policy for the key slot contains all the flags
908      * required by the usage parameter. There is one exception: public
909      * keys can always be exported, so we treat public key objects as
910      * if they had the export flag. */
911     if (PSA_KEY_TYPE_IS_PUBLIC_KEY(slot->attr.type)) {
912         usage &= ~PSA_KEY_USAGE_EXPORT;
913     }
914 
915     if ((slot->attr.policy.usage & usage) != usage) {
916         status = PSA_ERROR_NOT_PERMITTED;
917         goto error;
918     }
919 
920     /* Enforce that the usage policy permits the requested algorithm. */
921     if (alg != 0) {
922         status = psa_key_policy_permits(&slot->attr.policy,
923                                         slot->attr.type,
924                                         alg);
925         if (status != PSA_SUCCESS) {
926             goto error;
927         }
928     }
929 
930     return PSA_SUCCESS;
931 
932 error:
933     *p_slot = NULL;
934     psa_unlock_key_slot(slot);
935 
936     return status;
937 }
938 
939 /** Get a key slot containing a transparent key and lock it.
940  *
941  * A transparent key is a key for which the key material is directly
942  * available, as opposed to a key in a secure element and/or to be used
943  * by a secure element.
944  *
945  * This is a temporary function that may be used instead of
946  * psa_get_and_lock_key_slot_with_policy() when there is no opaque key support
947  * for a cryptographic operation.
948  *
949  * On success, the returned key slot is locked. It is the responsibility of the
950  * caller to unlock the key slot when it does not access it anymore.
951  */
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)952 static psa_status_t psa_get_and_lock_transparent_key_slot_with_policy(
953     mbedtls_svc_key_id_t key,
954     psa_key_slot_t **p_slot,
955     psa_key_usage_t usage,
956     psa_algorithm_t alg)
957 {
958     psa_status_t status = psa_get_and_lock_key_slot_with_policy(key, p_slot,
959                                                                 usage, alg);
960     if (status != PSA_SUCCESS) {
961         return status;
962     }
963 
964     if (psa_key_lifetime_is_external((*p_slot)->attr.lifetime)
965 #if defined(PSA_CRYPTO_DRIVER_TFM_BUILTIN_KEY_LOADER)
966         && PSA_KEY_LIFETIME_GET_LOCATION((*p_slot)->attr.lifetime) != TFM_BUILTIN_KEY_LOADER_KEY_LOCATION
967 #endif /* PSA_CRYPTO_DRIVER_TFM_BUILTIN_KEY_LOADER */
968         ) {
969         psa_unlock_key_slot(*p_slot);
970         *p_slot = NULL;
971         return PSA_ERROR_NOT_SUPPORTED;
972     }
973 
974     return PSA_SUCCESS;
975 }
976 
psa_remove_key_data_from_memory(psa_key_slot_t * slot)977 psa_status_t psa_remove_key_data_from_memory(psa_key_slot_t *slot)
978 {
979     if (slot->key.data != NULL) {
980         mbedtls_zeroize_and_free(slot->key.data, slot->key.bytes);
981     }
982 
983     slot->key.data = NULL;
984     slot->key.bytes = 0;
985 
986     return PSA_SUCCESS;
987 }
988 
989 /** Completely wipe a slot in memory, including its policy.
990  * Persistent storage is not affected. */
psa_wipe_key_slot(psa_key_slot_t * slot)991 psa_status_t psa_wipe_key_slot(psa_key_slot_t *slot)
992 {
993     psa_status_t status = psa_remove_key_data_from_memory(slot);
994 
995     /*
996      * As the return error code may not be handled in case of multiple errors,
997      * do our best to report an unexpected lock counter. Assert with
998      * MBEDTLS_TEST_HOOK_TEST_ASSERT that the lock counter is equal to one:
999      * if the MBEDTLS_TEST_HOOKS configuration option is enabled and the
1000      * function is called as part of the execution of a test suite, the
1001      * execution of the test suite is stopped in error if the assertion fails.
1002      */
1003     if (slot->lock_count != 1) {
1004         MBEDTLS_TEST_HOOK_TEST_ASSERT(slot->lock_count == 1);
1005         status = PSA_ERROR_CORRUPTION_DETECTED;
1006     }
1007 
1008     /* Multipart operations may still be using the key. This is safe
1009      * because all multipart operation objects are independent from
1010      * the key slot: if they need to access the key after the setup
1011      * phase, they have a copy of the key. Note that this means that
1012      * key material can linger until all operations are completed. */
1013     /* At this point, key material and other type-specific content has
1014      * been wiped. Clear remaining metadata. We can call memset and not
1015      * zeroize because the metadata is not particularly sensitive. */
1016     memset(slot, 0, sizeof(*slot));
1017     return status;
1018 }
1019 
psa_destroy_key(mbedtls_svc_key_id_t key)1020 psa_status_t psa_destroy_key(mbedtls_svc_key_id_t key)
1021 {
1022     psa_key_slot_t *slot;
1023     psa_status_t status; /* status of the last operation */
1024     psa_status_t overall_status = PSA_SUCCESS;
1025 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1026     psa_se_drv_table_entry_t *driver;
1027 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1028 
1029     if (mbedtls_svc_key_id_is_null(key)) {
1030         return PSA_SUCCESS;
1031     }
1032 
1033     /*
1034      * Get the description of the key in a key slot. In case of a persistent
1035      * key, this will load the key description from persistent memory if not
1036      * done yet. We cannot avoid this loading as without it we don't know if
1037      * the key is operated by an SE or not and this information is needed by
1038      * the current implementation.
1039      */
1040     status = psa_get_and_lock_key_slot(key, &slot);
1041     if (status != PSA_SUCCESS) {
1042         return status;
1043     }
1044 
1045     /*
1046      * If the key slot containing the key description is under access by the
1047      * library (apart from the present access), the key cannot be destroyed
1048      * yet. For the time being, just return in error. Eventually (to be
1049      * implemented), the key should be destroyed when all accesses have
1050      * stopped.
1051      */
1052     if (slot->lock_count > 1) {
1053         psa_unlock_key_slot(slot);
1054         return PSA_ERROR_GENERIC_ERROR;
1055     }
1056 
1057     if (PSA_KEY_LIFETIME_IS_READ_ONLY(slot->attr.lifetime)) {
1058         /* Refuse the destruction of a read-only key (which may or may not work
1059          * if we attempt it, depending on whether the key is merely read-only
1060          * by policy or actually physically read-only).
1061          * Just do the best we can, which is to wipe the copy in memory
1062          * (done in this function's cleanup code). */
1063         overall_status = PSA_ERROR_NOT_PERMITTED;
1064         goto exit;
1065     }
1066 
1067 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1068     driver = psa_get_se_driver_entry(slot->attr.lifetime);
1069     if (driver != NULL) {
1070         /* For a key in a secure element, we need to do three things:
1071          * remove the key file in internal storage, destroy the
1072          * key inside the secure element, and update the driver's
1073          * persistent data. Start a transaction that will encompass these
1074          * three actions. */
1075         psa_crypto_prepare_transaction(PSA_CRYPTO_TRANSACTION_DESTROY_KEY);
1076         psa_crypto_transaction.key.lifetime = slot->attr.lifetime;
1077         psa_crypto_transaction.key.slot = psa_key_slot_get_slot_number(slot);
1078         psa_crypto_transaction.key.id = slot->attr.id;
1079         status = psa_crypto_save_transaction();
1080         if (status != PSA_SUCCESS) {
1081             (void) psa_crypto_stop_transaction();
1082             /* We should still try to destroy the key in the secure
1083              * element and the key metadata in storage. This is especially
1084              * important if the error is that the storage is full.
1085              * But how to do it exactly without risking an inconsistent
1086              * state after a reset?
1087              * https://github.com/ARMmbed/mbed-crypto/issues/215
1088              */
1089             overall_status = status;
1090             goto exit;
1091         }
1092 
1093         status = psa_destroy_se_key(driver,
1094                                     psa_key_slot_get_slot_number(slot));
1095         if (overall_status == PSA_SUCCESS) {
1096             overall_status = status;
1097         }
1098     }
1099 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1100 
1101 #if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C)
1102     if (!PSA_KEY_LIFETIME_IS_VOLATILE(slot->attr.lifetime)) {
1103         status = psa_destroy_persistent_key(slot->attr.id);
1104         if (overall_status == PSA_SUCCESS) {
1105             overall_status = status;
1106         }
1107 
1108         /* TODO: other slots may have a copy of the same key. We should
1109          * invalidate them.
1110          * https://github.com/ARMmbed/mbed-crypto/issues/214
1111          */
1112     }
1113 #endif /* defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) */
1114 
1115 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1116     if (driver != NULL) {
1117         status = psa_save_se_persistent_data(driver);
1118         if (overall_status == PSA_SUCCESS) {
1119             overall_status = status;
1120         }
1121         status = psa_crypto_stop_transaction();
1122         if (overall_status == PSA_SUCCESS) {
1123             overall_status = status;
1124         }
1125     }
1126 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1127 
1128 exit:
1129     status = psa_wipe_key_slot(slot);
1130     /* Prioritize CORRUPTION_DETECTED from wiping over a storage error */
1131     if (status != PSA_SUCCESS) {
1132         overall_status = status;
1133     }
1134     return overall_status;
1135 }
1136 
1137 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_EXPORT) || \
1138     defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY)
psa_get_rsa_public_exponent(const mbedtls_rsa_context * rsa,psa_key_attributes_t * attributes)1139 static psa_status_t psa_get_rsa_public_exponent(
1140     const mbedtls_rsa_context *rsa,
1141     psa_key_attributes_t *attributes)
1142 {
1143     mbedtls_mpi mpi;
1144     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1145     uint8_t *buffer = NULL;
1146     size_t buflen;
1147     mbedtls_mpi_init(&mpi);
1148 
1149     ret = mbedtls_rsa_export(rsa, NULL, NULL, NULL, NULL, &mpi);
1150     if (ret != 0) {
1151         goto exit;
1152     }
1153     if (mbedtls_mpi_cmp_int(&mpi, 65537) == 0) {
1154         /* It's the default value, which is reported as an empty string,
1155          * so there's nothing to do. */
1156         goto exit;
1157     }
1158 
1159     buflen = mbedtls_mpi_size(&mpi);
1160     buffer = mbedtls_calloc(1, buflen);
1161     if (buffer == NULL) {
1162         ret = MBEDTLS_ERR_MPI_ALLOC_FAILED;
1163         goto exit;
1164     }
1165     ret = mbedtls_mpi_write_binary(&mpi, buffer, buflen);
1166     if (ret != 0) {
1167         goto exit;
1168     }
1169     attributes->domain_parameters = buffer;
1170     attributes->domain_parameters_size = buflen;
1171 
1172 exit:
1173     mbedtls_mpi_free(&mpi);
1174     if (ret != 0) {
1175         mbedtls_free(buffer);
1176     }
1177     return mbedtls_to_psa_error(ret);
1178 }
1179 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_EXPORT) ||
1180         * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY) */
1181 
1182 /** Retrieve all the publicly-accessible attributes of a key.
1183  */
psa_get_key_attributes(mbedtls_svc_key_id_t key,psa_key_attributes_t * attributes)1184 psa_status_t psa_get_key_attributes(mbedtls_svc_key_id_t key,
1185                                     psa_key_attributes_t *attributes)
1186 {
1187     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
1188     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
1189     psa_key_slot_t *slot;
1190 
1191     psa_reset_key_attributes(attributes);
1192 
1193     status = psa_get_and_lock_key_slot_with_policy(key, &slot, 0, 0);
1194     if (status != PSA_SUCCESS) {
1195         return status;
1196     }
1197 
1198     attributes->core = slot->attr;
1199     attributes->core.flags &= (MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY |
1200                                MBEDTLS_PSA_KA_MASK_DUAL_USE);
1201 
1202 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1203     if (psa_get_se_driver_entry(slot->attr.lifetime) != NULL) {
1204         psa_set_key_slot_number(attributes,
1205                                 psa_key_slot_get_slot_number(slot));
1206     }
1207 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1208 
1209     switch (slot->attr.type) {
1210 #if (defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_IMPORT) && \
1211     defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_EXPORT)) || \
1212     defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY)
1213         case PSA_KEY_TYPE_RSA_KEY_PAIR:
1214         case PSA_KEY_TYPE_RSA_PUBLIC_KEY:
1215             /* TODO: reporting the public exponent for opaque keys
1216              * is not yet implemented.
1217              * https://github.com/ARMmbed/mbed-crypto/issues/216
1218              */
1219             if (!psa_key_lifetime_is_external(slot->attr.lifetime)) {
1220                 mbedtls_rsa_context *rsa = NULL;
1221 
1222                 status = mbedtls_psa_rsa_load_representation(
1223                     slot->attr.type,
1224                     slot->key.data,
1225                     slot->key.bytes,
1226                     &rsa);
1227                 if (status != PSA_SUCCESS) {
1228                     break;
1229                 }
1230 
1231                 status = psa_get_rsa_public_exponent(rsa,
1232                                                      attributes);
1233                 mbedtls_rsa_free(rsa);
1234                 mbedtls_free(rsa);
1235             }
1236             break;
1237 #endif /* (defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_IMPORT) && \
1238         * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_EXPORT)) ||
1239         * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY) */
1240         default:
1241             /* Nothing else to do. */
1242             break;
1243     }
1244 
1245     if (status != PSA_SUCCESS) {
1246         psa_reset_key_attributes(attributes);
1247     }
1248 
1249     unlock_status = psa_unlock_key_slot(slot);
1250 
1251     return (status == PSA_SUCCESS) ? unlock_status : status;
1252 }
1253 
1254 #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)1255 psa_status_t psa_get_key_slot_number(
1256     const psa_key_attributes_t *attributes,
1257     psa_key_slot_number_t *slot_number)
1258 {
1259     if (attributes->core.flags & MBEDTLS_PSA_KA_FLAG_HAS_SLOT_NUMBER) {
1260         *slot_number = attributes->slot_number;
1261         return PSA_SUCCESS;
1262     } else {
1263         return PSA_ERROR_INVALID_ARGUMENT;
1264     }
1265 }
1266 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1267 
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)1268 static psa_status_t psa_export_key_buffer_internal(const uint8_t *key_buffer,
1269                                                    size_t key_buffer_size,
1270                                                    uint8_t *data,
1271                                                    size_t data_size,
1272                                                    size_t *data_length)
1273 {
1274     if (key_buffer_size > data_size) {
1275         return PSA_ERROR_BUFFER_TOO_SMALL;
1276     }
1277     memcpy(data, key_buffer, key_buffer_size);
1278     memset(data + key_buffer_size, 0,
1279            data_size - key_buffer_size);
1280     *data_length = key_buffer_size;
1281     return PSA_SUCCESS;
1282 }
1283 
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)1284 psa_status_t psa_export_key_internal(
1285     const psa_key_attributes_t *attributes,
1286     const uint8_t *key_buffer, size_t key_buffer_size,
1287     uint8_t *data, size_t data_size, size_t *data_length)
1288 {
1289     psa_key_type_t type = attributes->core.type;
1290 
1291     if (key_type_is_raw_bytes(type) ||
1292         PSA_KEY_TYPE_IS_RSA(type)   ||
1293         PSA_KEY_TYPE_IS_ECC(type)   ||
1294         PSA_KEY_TYPE_IS_DH(type)) {
1295         return psa_export_key_buffer_internal(
1296             key_buffer, key_buffer_size,
1297             data, data_size, data_length);
1298     } else {
1299         /* This shouldn't happen in the reference implementation, but
1300            it is valid for a special-purpose implementation to omit
1301            support for exporting certain key types. */
1302         return PSA_ERROR_NOT_SUPPORTED;
1303     }
1304 }
1305 
psa_export_key(mbedtls_svc_key_id_t key,uint8_t * data,size_t data_size,size_t * data_length)1306 psa_status_t psa_export_key(mbedtls_svc_key_id_t key,
1307                             uint8_t *data,
1308                             size_t data_size,
1309                             size_t *data_length)
1310 {
1311     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
1312     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
1313     psa_key_slot_t *slot;
1314 
1315     /* Reject a zero-length output buffer now, since this can never be a
1316      * valid key representation. This way we know that data must be a valid
1317      * pointer and we can do things like memset(data, ..., data_size). */
1318     if (data_size == 0) {
1319         return PSA_ERROR_BUFFER_TOO_SMALL;
1320     }
1321 
1322     /* Set the key to empty now, so that even when there are errors, we always
1323      * set data_length to a value between 0 and data_size. On error, setting
1324      * the key to empty is a good choice because an empty key representation is
1325      * unlikely to be accepted anywhere. */
1326     *data_length = 0;
1327 
1328     /* Export requires the EXPORT flag. There is an exception for public keys,
1329      * which don't require any flag, but
1330      * psa_get_and_lock_key_slot_with_policy() takes care of this.
1331      */
1332     status = psa_get_and_lock_key_slot_with_policy(key, &slot,
1333                                                    PSA_KEY_USAGE_EXPORT, 0);
1334     if (status != PSA_SUCCESS) {
1335         return status;
1336     }
1337 
1338     psa_key_attributes_t attributes = {
1339         .core = slot->attr
1340     };
1341     status = psa_driver_wrapper_export_key(&attributes,
1342                                            slot->key.data, slot->key.bytes,
1343                                            data, data_size, data_length);
1344 
1345     unlock_status = psa_unlock_key_slot(slot);
1346 
1347     return (status == PSA_SUCCESS) ? unlock_status : status;
1348 }
1349 
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)1350 psa_status_t psa_export_public_key_internal(
1351     const psa_key_attributes_t *attributes,
1352     const uint8_t *key_buffer,
1353     size_t key_buffer_size,
1354     uint8_t *data,
1355     size_t data_size,
1356     size_t *data_length)
1357 {
1358     psa_key_type_t type = attributes->core.type;
1359 
1360     if (PSA_KEY_TYPE_IS_PUBLIC_KEY(type) &&
1361         (PSA_KEY_TYPE_IS_RSA(type) || PSA_KEY_TYPE_IS_ECC(type) ||
1362          PSA_KEY_TYPE_IS_DH(type))) {
1363         /* Exporting public -> public */
1364         return psa_export_key_buffer_internal(
1365             key_buffer, key_buffer_size,
1366             data, data_size, data_length);
1367     } else if (PSA_KEY_TYPE_IS_RSA(type)) {
1368 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_EXPORT) || \
1369         defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY)
1370         return mbedtls_psa_rsa_export_public_key(attributes,
1371                                                  key_buffer,
1372                                                  key_buffer_size,
1373                                                  data,
1374                                                  data_size,
1375                                                  data_length);
1376 #else
1377         /* We don't know how to convert a private RSA key to public. */
1378         return PSA_ERROR_NOT_SUPPORTED;
1379 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_EXPORT) ||
1380         * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY) */
1381     } else if (PSA_KEY_TYPE_IS_ECC(type)) {
1382 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_EXPORT) || \
1383         defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY)
1384         return mbedtls_psa_ecp_export_public_key(attributes,
1385                                                  key_buffer,
1386                                                  key_buffer_size,
1387                                                  data,
1388                                                  data_size,
1389                                                  data_length);
1390 #else
1391         /* We don't know how to convert a private ECC key to public */
1392         return PSA_ERROR_NOT_SUPPORTED;
1393 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_EXPORT) ||
1394         * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY) */
1395     } else if (PSA_KEY_TYPE_IS_DH(type)) {
1396 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_KEY_PAIR_EXPORT) || \
1397         defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_PUBLIC_KEY)
1398         return mbedtls_psa_ffdh_export_public_key(attributes,
1399                                                   key_buffer,
1400                                                   key_buffer_size,
1401                                                   data, data_size,
1402                                                   data_length);
1403 #else
1404         return PSA_ERROR_NOT_SUPPORTED;
1405 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_KEY_PAIR_EXPORT) ||
1406         * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_PUBLIC_KEY) */
1407     } else {
1408         (void) key_buffer;
1409         (void) key_buffer_size;
1410         (void) data;
1411         (void) data_size;
1412         (void) data_length;
1413         return PSA_ERROR_NOT_SUPPORTED;
1414     }
1415 }
1416 
psa_export_public_key(mbedtls_svc_key_id_t key,uint8_t * data,size_t data_size,size_t * data_length)1417 psa_status_t psa_export_public_key(mbedtls_svc_key_id_t key,
1418                                    uint8_t *data,
1419                                    size_t data_size,
1420                                    size_t *data_length)
1421 {
1422     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
1423     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
1424     psa_key_slot_t *slot;
1425     psa_key_attributes_t attributes;
1426 
1427     /* Reject a zero-length output buffer now, since this can never be a
1428      * valid key representation. This way we know that data must be a valid
1429      * pointer and we can do things like memset(data, ..., data_size). */
1430     if (data_size == 0) {
1431         return PSA_ERROR_BUFFER_TOO_SMALL;
1432     }
1433 
1434     /* Set the key to empty now, so that even when there are errors, we always
1435      * set data_length to a value between 0 and data_size. On error, setting
1436      * the key to empty is a good choice because an empty key representation is
1437      * unlikely to be accepted anywhere. */
1438     *data_length = 0;
1439 
1440     /* Exporting a public key doesn't require a usage flag. */
1441     status = psa_get_and_lock_key_slot_with_policy(key, &slot, 0, 0);
1442     if (status != PSA_SUCCESS) {
1443         return status;
1444     }
1445 
1446     if (!PSA_KEY_TYPE_IS_ASYMMETRIC(slot->attr.type)) {
1447         status = PSA_ERROR_INVALID_ARGUMENT;
1448         goto exit;
1449     }
1450 
1451     attributes = (psa_key_attributes_t) {
1452         .core = slot->attr
1453     };
1454     status = psa_driver_wrapper_export_public_key(
1455         &attributes, slot->key.data, slot->key.bytes,
1456         data, data_size, data_length);
1457 
1458 exit:
1459     unlock_status = psa_unlock_key_slot(slot);
1460 
1461     return (status == PSA_SUCCESS) ? unlock_status : status;
1462 }
1463 
1464 MBEDTLS_STATIC_ASSERT(
1465     (MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY & MBEDTLS_PSA_KA_MASK_DUAL_USE) == 0,
1466     "One or more key attribute flag is listed as both external-only and dual-use")
1467 MBEDTLS_STATIC_ASSERT(
1468     (PSA_KA_MASK_INTERNAL_ONLY & MBEDTLS_PSA_KA_MASK_DUAL_USE) == 0,
1469     "One or more key attribute flag is listed as both internal-only and dual-use")
1470 MBEDTLS_STATIC_ASSERT(
1471     (PSA_KA_MASK_INTERNAL_ONLY & MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY) == 0,
1472     "One or more key attribute flag is listed as both internal-only and external-only")
1473 
1474 /** Validate that a key policy is internally well-formed.
1475  *
1476  * This function only rejects invalid policies. It does not validate the
1477  * consistency of the policy with respect to other attributes of the key
1478  * such as the key type.
1479  */
psa_validate_key_policy(const psa_key_policy_t * policy)1480 static psa_status_t psa_validate_key_policy(const psa_key_policy_t *policy)
1481 {
1482     if ((policy->usage & ~(PSA_KEY_USAGE_EXPORT |
1483                            PSA_KEY_USAGE_COPY |
1484                            PSA_KEY_USAGE_ENCRYPT |
1485                            PSA_KEY_USAGE_DECRYPT |
1486                            PSA_KEY_USAGE_SIGN_MESSAGE |
1487                            PSA_KEY_USAGE_VERIFY_MESSAGE |
1488                            PSA_KEY_USAGE_SIGN_HASH |
1489                            PSA_KEY_USAGE_VERIFY_HASH |
1490                            PSA_KEY_USAGE_VERIFY_DERIVATION |
1491                            PSA_KEY_USAGE_DERIVE)) != 0) {
1492         return PSA_ERROR_INVALID_ARGUMENT;
1493     }
1494 
1495     return PSA_SUCCESS;
1496 }
1497 
1498 /** Validate the internal consistency of key attributes.
1499  *
1500  * This function only rejects invalid attribute values. If does not
1501  * validate the consistency of the attributes with any key data that may
1502  * be involved in the creation of the key.
1503  *
1504  * Call this function early in the key creation process.
1505  *
1506  * \param[in] attributes    Key attributes for the new key.
1507  * \param[out] p_drv        On any return, the driver for the key, if any.
1508  *                          NULL for a transparent key.
1509  *
1510  */
psa_validate_key_attributes(const psa_key_attributes_t * attributes,psa_se_drv_table_entry_t ** p_drv)1511 static psa_status_t psa_validate_key_attributes(
1512     const psa_key_attributes_t *attributes,
1513     psa_se_drv_table_entry_t **p_drv)
1514 {
1515     psa_status_t status = PSA_ERROR_INVALID_ARGUMENT;
1516     psa_key_lifetime_t lifetime = psa_get_key_lifetime(attributes);
1517     mbedtls_svc_key_id_t key = psa_get_key_id(attributes);
1518 
1519     status = psa_validate_key_location(lifetime, p_drv);
1520     if (status != PSA_SUCCESS) {
1521         return status;
1522     }
1523 
1524     status = psa_validate_key_persistence(lifetime);
1525     if (status != PSA_SUCCESS) {
1526         return status;
1527     }
1528 
1529     if (PSA_KEY_LIFETIME_IS_VOLATILE(lifetime)) {
1530         if (MBEDTLS_SVC_KEY_ID_GET_KEY_ID(key) != 0) {
1531             return PSA_ERROR_INVALID_ARGUMENT;
1532         }
1533     } else {
1534 #ifdef MBEDTLS_PSA_CRYPTO_SE_C
1535         if (!psa_is_valid_key_id(psa_get_key_id(attributes), 1)) {
1536 #else
1537         if (!psa_is_valid_key_id(psa_get_key_id(attributes), 0)) {
1538 #endif
1539             return PSA_ERROR_INVALID_ARGUMENT;
1540         }
1541     }
1542 
1543     status = psa_validate_key_policy(&attributes->core.policy);
1544     if (status != PSA_SUCCESS) {
1545         return status;
1546     }
1547 
1548     /* Refuse to create overly large keys.
1549      * Note that this doesn't trigger on import if the attributes don't
1550      * explicitly specify a size (so psa_get_key_bits returns 0), so
1551      * psa_import_key() needs its own checks. */
1552     if (psa_get_key_bits(attributes) > PSA_MAX_KEY_BITS) {
1553         return PSA_ERROR_NOT_SUPPORTED;
1554     }
1555 
1556     /* Reject invalid flags. These should not be reachable through the API. */
1557     if (attributes->core.flags & ~(MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY |
1558                                    MBEDTLS_PSA_KA_MASK_DUAL_USE)) {
1559         return PSA_ERROR_INVALID_ARGUMENT;
1560     }
1561 
1562     return PSA_SUCCESS;
1563 }
1564 
1565 /** Prepare a key slot to receive key material.
1566  *
1567  * This function allocates a key slot and sets its metadata.
1568  *
1569  * If this function fails, call psa_fail_key_creation().
1570  *
1571  * This function is intended to be used as follows:
1572  * -# Call psa_start_key_creation() to allocate a key slot, prepare
1573  *    it with the specified attributes, and in case of a volatile key assign it
1574  *    a volatile key identifier.
1575  * -# Populate the slot with the key material.
1576  * -# Call psa_finish_key_creation() to finalize the creation of the slot.
1577  * In case of failure at any step, stop the sequence and call
1578  * psa_fail_key_creation().
1579  *
1580  * On success, the key slot is locked. It is the responsibility of the caller
1581  * to unlock the key slot when it does not access it anymore.
1582  *
1583  * \param method            An identification of the calling function.
1584  * \param[in] attributes    Key attributes for the new key.
1585  * \param[out] p_slot       On success, a pointer to the prepared slot.
1586  * \param[out] p_drv        On any return, the driver for the key, if any.
1587  *                          NULL for a transparent key.
1588  *
1589  * \retval #PSA_SUCCESS
1590  *         The key slot is ready to receive key material.
1591  * \return If this function fails, the key slot is an invalid state.
1592  *         You must call psa_fail_key_creation() to wipe and free the slot.
1593  */
1594 static psa_status_t psa_start_key_creation(
1595     psa_key_creation_method_t method,
1596     const psa_key_attributes_t *attributes,
1597     psa_key_slot_t **p_slot,
1598     psa_se_drv_table_entry_t **p_drv)
1599 {
1600     psa_status_t status;
1601     psa_key_id_t volatile_key_id;
1602     psa_key_slot_t *slot;
1603 
1604     (void) method;
1605     *p_drv = NULL;
1606 
1607     status = psa_validate_key_attributes(attributes, p_drv);
1608     if (status != PSA_SUCCESS) {
1609         return status;
1610     }
1611 
1612     status = psa_get_empty_key_slot(&volatile_key_id, p_slot);
1613     if (status != PSA_SUCCESS) {
1614         return status;
1615     }
1616     slot = *p_slot;
1617 
1618     /* We're storing the declared bit-size of the key. It's up to each
1619      * creation mechanism to verify that this information is correct.
1620      * It's automatically correct for mechanisms that use the bit-size as
1621      * an input (generate, device) but not for those where the bit-size
1622      * is optional (import, copy). In case of a volatile key, assign it the
1623      * volatile key identifier associated to the slot returned to contain its
1624      * definition. */
1625 
1626     slot->attr = attributes->core;
1627     if (PSA_KEY_LIFETIME_IS_VOLATILE(slot->attr.lifetime)) {
1628 #if !defined(MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER)
1629         slot->attr.id = volatile_key_id;
1630 #else
1631         slot->attr.id.key_id = volatile_key_id;
1632 #endif
1633     }
1634 
1635     /* Erase external-only flags from the internal copy. To access
1636      * external-only flags, query `attributes`. Thanks to the check
1637      * in psa_validate_key_attributes(), this leaves the dual-use
1638      * flags and any internal flag that psa_get_empty_key_slot()
1639      * may have set. */
1640     slot->attr.flags &= ~MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY;
1641 
1642 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1643     /* For a key in a secure element, we need to do three things
1644      * when creating or registering a persistent key:
1645      * create the key file in internal storage, create the
1646      * key inside the secure element, and update the driver's
1647      * persistent data. This is done by starting a transaction that will
1648      * encompass these three actions.
1649      * For registering a volatile key, we just need to find an appropriate
1650      * slot number inside the SE. Since the key is designated volatile, creating
1651      * a transaction is not required. */
1652     /* The first thing to do is to find a slot number for the new key.
1653      * We save the slot number in persistent storage as part of the
1654      * transaction data. It will be needed to recover if the power
1655      * fails during the key creation process, to clean up on the secure
1656      * element side after restarting. Obtaining a slot number from the
1657      * secure element driver updates its persistent state, but we do not yet
1658      * save the driver's persistent state, so that if the power fails,
1659      * we can roll back to a state where the key doesn't exist. */
1660     if (*p_drv != NULL) {
1661         psa_key_slot_number_t slot_number;
1662         status = psa_find_se_slot_for_key(attributes, method, *p_drv,
1663                                           &slot_number);
1664         if (status != PSA_SUCCESS) {
1665             return status;
1666         }
1667 
1668         if (!PSA_KEY_LIFETIME_IS_VOLATILE(attributes->core.lifetime)) {
1669             psa_crypto_prepare_transaction(PSA_CRYPTO_TRANSACTION_CREATE_KEY);
1670             psa_crypto_transaction.key.lifetime = slot->attr.lifetime;
1671             psa_crypto_transaction.key.slot = slot_number;
1672             psa_crypto_transaction.key.id = slot->attr.id;
1673             status = psa_crypto_save_transaction();
1674             if (status != PSA_SUCCESS) {
1675                 (void) psa_crypto_stop_transaction();
1676                 return status;
1677             }
1678         }
1679 
1680         status = psa_copy_key_material_into_slot(
1681             slot, (uint8_t *) (&slot_number), sizeof(slot_number));
1682     }
1683 
1684     if (*p_drv == NULL && method == PSA_KEY_CREATION_REGISTER) {
1685         /* Key registration only makes sense with a secure element. */
1686         return PSA_ERROR_INVALID_ARGUMENT;
1687     }
1688 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1689 
1690     return PSA_SUCCESS;
1691 }
1692 
1693 /** Finalize the creation of a key once its key material has been set.
1694  *
1695  * This entails writing the key to persistent storage.
1696  *
1697  * If this function fails, call psa_fail_key_creation().
1698  * See the documentation of psa_start_key_creation() for the intended use
1699  * of this function.
1700  *
1701  * If the finalization succeeds, the function unlocks the key slot (it was
1702  * locked by psa_start_key_creation()) and the key slot cannot be accessed
1703  * anymore as part of the key creation process.
1704  *
1705  * \param[in,out] slot  Pointer to the slot with key material.
1706  * \param[in] driver    The secure element driver for the key,
1707  *                      or NULL for a transparent key.
1708  * \param[out] key      On success, identifier of the key. Note that the
1709  *                      key identifier is also stored in the key slot.
1710  *
1711  * \retval #PSA_SUCCESS
1712  *         The key was successfully created.
1713  * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
1714  * \retval #PSA_ERROR_INSUFFICIENT_STORAGE \emptydescription
1715  * \retval #PSA_ERROR_ALREADY_EXISTS \emptydescription
1716  * \retval #PSA_ERROR_DATA_INVALID \emptydescription
1717  * \retval #PSA_ERROR_DATA_CORRUPT \emptydescription
1718  * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
1719  *
1720  * \return If this function fails, the key slot is an invalid state.
1721  *         You must call psa_fail_key_creation() to wipe and free the slot.
1722  */
1723 static psa_status_t psa_finish_key_creation(
1724     psa_key_slot_t *slot,
1725     psa_se_drv_table_entry_t *driver,
1726     mbedtls_svc_key_id_t *key)
1727 {
1728     psa_status_t status = PSA_SUCCESS;
1729     (void) slot;
1730     (void) driver;
1731 
1732 #if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C)
1733     if (!PSA_KEY_LIFETIME_IS_VOLATILE(slot->attr.lifetime)) {
1734 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1735         if (driver != NULL) {
1736             psa_se_key_data_storage_t data;
1737             psa_key_slot_number_t slot_number =
1738                 psa_key_slot_get_slot_number(slot);
1739 
1740             MBEDTLS_STATIC_ASSERT(sizeof(slot_number) ==
1741                                   sizeof(data.slot_number),
1742                                   "Slot number size does not match psa_se_key_data_storage_t");
1743 
1744             memcpy(&data.slot_number, &slot_number, sizeof(slot_number));
1745             status = psa_save_persistent_key(&slot->attr,
1746                                              (uint8_t *) &data,
1747                                              sizeof(data));
1748         } else
1749 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1750         {
1751             /* Key material is saved in export representation in the slot, so
1752              * just pass the slot buffer for storage. */
1753             status = psa_save_persistent_key(&slot->attr,
1754                                              slot->key.data,
1755                                              slot->key.bytes);
1756         }
1757     }
1758 #endif /* defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) */
1759 
1760 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1761     /* Finish the transaction for a key creation. This does not
1762      * happen when registering an existing key. Detect this case
1763      * by checking whether a transaction is in progress (actual
1764      * creation of a persistent key in a secure element requires a transaction,
1765      * but registration or volatile key creation doesn't use one). */
1766     if (driver != NULL &&
1767         psa_crypto_transaction.unknown.type == PSA_CRYPTO_TRANSACTION_CREATE_KEY) {
1768         status = psa_save_se_persistent_data(driver);
1769         if (status != PSA_SUCCESS) {
1770             psa_destroy_persistent_key(slot->attr.id);
1771             return status;
1772         }
1773         status = psa_crypto_stop_transaction();
1774     }
1775 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1776 
1777     if (status == PSA_SUCCESS) {
1778         *key = slot->attr.id;
1779         status = psa_unlock_key_slot(slot);
1780         if (status != PSA_SUCCESS) {
1781             *key = MBEDTLS_SVC_KEY_ID_INIT;
1782         }
1783     }
1784 
1785     return status;
1786 }
1787 
1788 /** Abort the creation of a key.
1789  *
1790  * You may call this function after calling psa_start_key_creation(),
1791  * or after psa_finish_key_creation() fails. In other circumstances, this
1792  * function may not clean up persistent storage.
1793  * See the documentation of psa_start_key_creation() for the intended use
1794  * of this function.
1795  *
1796  * \param[in,out] slot  Pointer to the slot with key material.
1797  * \param[in] driver    The secure element driver for the key,
1798  *                      or NULL for a transparent key.
1799  */
1800 static void psa_fail_key_creation(psa_key_slot_t *slot,
1801                                   psa_se_drv_table_entry_t *driver)
1802 {
1803     (void) driver;
1804 
1805     if (slot == NULL) {
1806         return;
1807     }
1808 
1809 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1810     /* TODO: If the key has already been created in the secure
1811      * element, and the failure happened later (when saving metadata
1812      * to internal storage), we need to destroy the key in the secure
1813      * element.
1814      * https://github.com/ARMmbed/mbed-crypto/issues/217
1815      */
1816 
1817     /* Abort the ongoing transaction if any (there may not be one if
1818      * the creation process failed before starting one, or if the
1819      * key creation is a registration of a key in a secure element).
1820      * Earlier functions must already have done what it takes to undo any
1821      * partial creation. All that's left is to update the transaction data
1822      * itself. */
1823     (void) psa_crypto_stop_transaction();
1824 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1825 
1826     psa_wipe_key_slot(slot);
1827 }
1828 
1829 /** Validate optional attributes during key creation.
1830  *
1831  * Some key attributes are optional during key creation. If they are
1832  * specified in the attributes structure, check that they are consistent
1833  * with the data in the slot.
1834  *
1835  * This function should be called near the end of key creation, after
1836  * the slot in memory is fully populated but before saving persistent data.
1837  */
1838 static psa_status_t psa_validate_optional_attributes(
1839     const psa_key_slot_t *slot,
1840     const psa_key_attributes_t *attributes)
1841 {
1842     if (attributes->core.type != 0) {
1843         if (attributes->core.type != slot->attr.type) {
1844             return PSA_ERROR_INVALID_ARGUMENT;
1845         }
1846     }
1847 
1848     if (attributes->domain_parameters_size != 0) {
1849 #if (defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_IMPORT) && \
1850         defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_EXPORT)) || \
1851         defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY)
1852         if (PSA_KEY_TYPE_IS_RSA(slot->attr.type)) {
1853             mbedtls_rsa_context *rsa = NULL;
1854             mbedtls_mpi actual, required;
1855             int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1856 
1857             psa_status_t status = mbedtls_psa_rsa_load_representation(
1858                 slot->attr.type,
1859                 slot->key.data,
1860                 slot->key.bytes,
1861                 &rsa);
1862             if (status != PSA_SUCCESS) {
1863                 return status;
1864             }
1865 
1866             mbedtls_mpi_init(&actual);
1867             mbedtls_mpi_init(&required);
1868             ret = mbedtls_rsa_export(rsa,
1869                                      NULL, NULL, NULL, NULL, &actual);
1870             mbedtls_rsa_free(rsa);
1871             mbedtls_free(rsa);
1872             if (ret != 0) {
1873                 goto rsa_exit;
1874             }
1875             ret = mbedtls_mpi_read_binary(&required,
1876                                           attributes->domain_parameters,
1877                                           attributes->domain_parameters_size);
1878             if (ret != 0) {
1879                 goto rsa_exit;
1880             }
1881             if (mbedtls_mpi_cmp_mpi(&actual, &required) != 0) {
1882                 ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1883             }
1884 rsa_exit:
1885             mbedtls_mpi_free(&actual);
1886             mbedtls_mpi_free(&required);
1887             if (ret != 0) {
1888                 return mbedtls_to_psa_error(ret);
1889             }
1890         } else
1891 #endif /* (defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_IMPORT) &&
1892         *  defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_EXPORT)) ||
1893         * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY) */
1894         {
1895             return PSA_ERROR_INVALID_ARGUMENT;
1896         }
1897     }
1898 
1899     if (attributes->core.bits != 0) {
1900         if (attributes->core.bits != slot->attr.bits) {
1901             return PSA_ERROR_INVALID_ARGUMENT;
1902         }
1903     }
1904 
1905     return PSA_SUCCESS;
1906 }
1907 
1908 psa_status_t psa_import_key(const psa_key_attributes_t *attributes,
1909                             const uint8_t *data,
1910                             size_t data_length,
1911                             mbedtls_svc_key_id_t *key)
1912 {
1913     psa_status_t status;
1914     psa_key_slot_t *slot = NULL;
1915     psa_se_drv_table_entry_t *driver = NULL;
1916     size_t bits;
1917     size_t storage_size = data_length;
1918 
1919     *key = MBEDTLS_SVC_KEY_ID_INIT;
1920 
1921     /* Reject zero-length symmetric keys (including raw data key objects).
1922      * This also rejects any key which might be encoded as an empty string,
1923      * which is never valid. */
1924     if (data_length == 0) {
1925         return PSA_ERROR_INVALID_ARGUMENT;
1926     }
1927 
1928     /* Ensure that the bytes-to-bits conversion cannot overflow. */
1929     if (data_length > SIZE_MAX / 8) {
1930         return PSA_ERROR_NOT_SUPPORTED;
1931     }
1932 
1933     status = psa_start_key_creation(PSA_KEY_CREATION_IMPORT, attributes,
1934                                     &slot, &driver);
1935     if (status != PSA_SUCCESS) {
1936         goto exit;
1937     }
1938 
1939     /* In the case of a transparent key or an opaque key stored in local
1940      * storage ( thus not in the case of importing a key in a secure element
1941      * with storage ( MBEDTLS_PSA_CRYPTO_SE_C ) ),we have to allocate a
1942      * buffer to hold the imported key material. */
1943     if (slot->key.data == NULL) {
1944         if (psa_key_lifetime_is_external(attributes->core.lifetime)) {
1945             status = psa_driver_wrapper_get_key_buffer_size_from_key_data(
1946                 attributes, data, data_length, &storage_size);
1947             if (status != PSA_SUCCESS) {
1948                 goto exit;
1949             }
1950         }
1951         status = psa_allocate_buffer_to_slot(slot, storage_size);
1952         if (status != PSA_SUCCESS) {
1953             goto exit;
1954         }
1955     }
1956 
1957     bits = slot->attr.bits;
1958     status = psa_driver_wrapper_import_key(attributes,
1959                                            data, data_length,
1960                                            slot->key.data,
1961                                            slot->key.bytes,
1962                                            &slot->key.bytes, &bits);
1963     if (status != PSA_SUCCESS) {
1964         goto exit;
1965     }
1966 
1967     if (slot->attr.bits == 0) {
1968         slot->attr.bits = (psa_key_bits_t) bits;
1969     } else if (bits != slot->attr.bits) {
1970         status = PSA_ERROR_INVALID_ARGUMENT;
1971         goto exit;
1972     }
1973 
1974     /* Enforce a size limit, and in particular ensure that the bit
1975      * size fits in its representation type.*/
1976     if (bits > PSA_MAX_KEY_BITS) {
1977         status = PSA_ERROR_NOT_SUPPORTED;
1978         goto exit;
1979     }
1980     status = psa_validate_optional_attributes(slot, attributes);
1981     if (status != PSA_SUCCESS) {
1982         goto exit;
1983     }
1984 
1985     status = psa_finish_key_creation(slot, driver, key);
1986 exit:
1987     if (status != PSA_SUCCESS) {
1988         psa_fail_key_creation(slot, driver);
1989     }
1990 
1991     return status;
1992 }
1993 
1994 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1995 psa_status_t mbedtls_psa_register_se_key(
1996     const psa_key_attributes_t *attributes)
1997 {
1998     psa_status_t status;
1999     psa_key_slot_t *slot = NULL;
2000     psa_se_drv_table_entry_t *driver = NULL;
2001     mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
2002 
2003     /* Leaving attributes unspecified is not currently supported.
2004      * It could make sense to query the key type and size from the
2005      * secure element, but not all secure elements support this
2006      * and the driver HAL doesn't currently support it. */
2007     if (psa_get_key_type(attributes) == PSA_KEY_TYPE_NONE) {
2008         return PSA_ERROR_NOT_SUPPORTED;
2009     }
2010     if (psa_get_key_bits(attributes) == 0) {
2011         return PSA_ERROR_NOT_SUPPORTED;
2012     }
2013 
2014     status = psa_start_key_creation(PSA_KEY_CREATION_REGISTER, attributes,
2015                                     &slot, &driver);
2016     if (status != PSA_SUCCESS) {
2017         goto exit;
2018     }
2019 
2020     status = psa_finish_key_creation(slot, driver, &key);
2021 
2022 exit:
2023     if (status != PSA_SUCCESS) {
2024         psa_fail_key_creation(slot, driver);
2025     }
2026 
2027     /* Registration doesn't keep the key in RAM. */
2028     psa_close_key(key);
2029     return status;
2030 }
2031 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
2032 
2033 psa_status_t psa_copy_key(mbedtls_svc_key_id_t source_key,
2034                           const psa_key_attributes_t *specified_attributes,
2035                           mbedtls_svc_key_id_t *target_key)
2036 {
2037     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2038     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
2039     psa_key_slot_t *source_slot = NULL;
2040     psa_key_slot_t *target_slot = NULL;
2041     psa_key_attributes_t actual_attributes = *specified_attributes;
2042     psa_se_drv_table_entry_t *driver = NULL;
2043     size_t storage_size = 0;
2044 
2045     *target_key = MBEDTLS_SVC_KEY_ID_INIT;
2046 
2047     status = psa_get_and_lock_key_slot_with_policy(
2048         source_key, &source_slot, PSA_KEY_USAGE_COPY, 0);
2049     if (status != PSA_SUCCESS) {
2050         goto exit;
2051     }
2052 
2053     status = psa_validate_optional_attributes(source_slot,
2054                                               specified_attributes);
2055     if (status != PSA_SUCCESS) {
2056         goto exit;
2057     }
2058 
2059     /* The target key type and number of bits have been validated by
2060      * psa_validate_optional_attributes() to be either equal to zero or
2061      * equal to the ones of the source key. So it is safe to inherit
2062      * them from the source key now."
2063      * */
2064     actual_attributes.core.bits = source_slot->attr.bits;
2065     actual_attributes.core.type = source_slot->attr.type;
2066 
2067 
2068     status = psa_restrict_key_policy(source_slot->attr.type,
2069                                      &actual_attributes.core.policy,
2070                                      &source_slot->attr.policy);
2071     if (status != PSA_SUCCESS) {
2072         goto exit;
2073     }
2074 
2075     status = psa_start_key_creation(PSA_KEY_CREATION_COPY, &actual_attributes,
2076                                     &target_slot, &driver);
2077     if (status != PSA_SUCCESS) {
2078         goto exit;
2079     }
2080     if (PSA_KEY_LIFETIME_GET_LOCATION(target_slot->attr.lifetime) !=
2081         PSA_KEY_LIFETIME_GET_LOCATION(source_slot->attr.lifetime)) {
2082         /*
2083          * If the source and target keys are stored in different locations,
2084          * the source key would need to be exported as plaintext and re-imported
2085          * in the other location. This has security implications which have not
2086          * been fully mapped. For now, this can be achieved through
2087          * appropriate API invocations from the application, if needed.
2088          * */
2089         status = PSA_ERROR_NOT_SUPPORTED;
2090         goto exit;
2091     }
2092     /*
2093      * When the source and target keys are within the same location,
2094      * - For transparent keys it is a blind copy without any driver invocation,
2095      * - For opaque keys this translates to an invocation of the drivers'
2096      *   copy_key entry point through the dispatch layer.
2097      * */
2098     if (psa_key_lifetime_is_external(actual_attributes.core.lifetime)) {
2099         status = psa_driver_wrapper_get_key_buffer_size(&actual_attributes,
2100                                                         &storage_size);
2101         if (status != PSA_SUCCESS) {
2102             goto exit;
2103         }
2104 
2105         status = psa_allocate_buffer_to_slot(target_slot, storage_size);
2106         if (status != PSA_SUCCESS) {
2107             goto exit;
2108         }
2109 
2110         status = psa_driver_wrapper_copy_key(&actual_attributes,
2111                                              source_slot->key.data,
2112                                              source_slot->key.bytes,
2113                                              target_slot->key.data,
2114                                              target_slot->key.bytes,
2115                                              &target_slot->key.bytes);
2116         if (status != PSA_SUCCESS) {
2117             goto exit;
2118         }
2119     } else {
2120         status = psa_copy_key_material_into_slot(target_slot,
2121                                                  source_slot->key.data,
2122                                                  source_slot->key.bytes);
2123         if (status != PSA_SUCCESS) {
2124             goto exit;
2125         }
2126     }
2127     status = psa_finish_key_creation(target_slot, driver, target_key);
2128 exit:
2129     if (status != PSA_SUCCESS) {
2130         psa_fail_key_creation(target_slot, driver);
2131     }
2132 
2133     unlock_status = psa_unlock_key_slot(source_slot);
2134 
2135     return (status == PSA_SUCCESS) ? unlock_status : status;
2136 }
2137 
2138 
2139 
2140 /****************************************************************/
2141 /* Message digests */
2142 /****************************************************************/
2143 
2144 psa_status_t psa_hash_abort(psa_hash_operation_t *operation)
2145 {
2146     /* Aborting a non-active operation is allowed */
2147     if (operation->id == 0) {
2148         return PSA_SUCCESS;
2149     }
2150 
2151     psa_status_t status = psa_driver_wrapper_hash_abort(operation);
2152     operation->id = 0;
2153 
2154     return status;
2155 }
2156 
2157 psa_status_t psa_hash_setup(psa_hash_operation_t *operation,
2158                             psa_algorithm_t alg)
2159 {
2160     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2161 
2162     /* A context must be freshly initialized before it can be set up. */
2163     if (operation->id != 0) {
2164         status = PSA_ERROR_BAD_STATE;
2165         goto exit;
2166     }
2167 
2168     if (!PSA_ALG_IS_HASH(alg)) {
2169         status = PSA_ERROR_INVALID_ARGUMENT;
2170         goto exit;
2171     }
2172 
2173     /* Ensure all of the context is zeroized, since PSA_HASH_OPERATION_INIT only
2174      * directly zeroes the int-sized dummy member of the context union. */
2175     memset(&operation->ctx, 0, sizeof(operation->ctx));
2176 
2177     status = psa_driver_wrapper_hash_setup(operation, alg);
2178 
2179 exit:
2180     if (status != PSA_SUCCESS) {
2181         psa_hash_abort(operation);
2182     }
2183 
2184     return status;
2185 }
2186 
2187 psa_status_t psa_hash_update(psa_hash_operation_t *operation,
2188                              const uint8_t *input,
2189                              size_t input_length)
2190 {
2191     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2192 
2193     if (operation->id == 0) {
2194         status = PSA_ERROR_BAD_STATE;
2195         goto exit;
2196     }
2197 
2198     /* Don't require hash implementations to behave correctly on a
2199      * zero-length input, which may have an invalid pointer. */
2200     if (input_length == 0) {
2201         return PSA_SUCCESS;
2202     }
2203 
2204     status = psa_driver_wrapper_hash_update(operation, input, input_length);
2205 
2206 exit:
2207     if (status != PSA_SUCCESS) {
2208         psa_hash_abort(operation);
2209     }
2210 
2211     return status;
2212 }
2213 
2214 psa_status_t psa_hash_finish(psa_hash_operation_t *operation,
2215                              uint8_t *hash,
2216                              size_t hash_size,
2217                              size_t *hash_length)
2218 {
2219     *hash_length = 0;
2220     if (operation->id == 0) {
2221         return PSA_ERROR_BAD_STATE;
2222     }
2223 
2224     psa_status_t status = psa_driver_wrapper_hash_finish(
2225         operation, hash, hash_size, hash_length);
2226     psa_hash_abort(operation);
2227     return status;
2228 }
2229 
2230 psa_status_t psa_hash_verify(psa_hash_operation_t *operation,
2231                              const uint8_t *hash,
2232                              size_t hash_length)
2233 {
2234     uint8_t actual_hash[PSA_HASH_MAX_SIZE];
2235     size_t actual_hash_length;
2236     psa_status_t status = psa_hash_finish(
2237         operation,
2238         actual_hash, sizeof(actual_hash),
2239         &actual_hash_length);
2240 
2241     if (status != PSA_SUCCESS) {
2242         goto exit;
2243     }
2244 
2245     if (actual_hash_length != hash_length) {
2246         status = PSA_ERROR_INVALID_SIGNATURE;
2247         goto exit;
2248     }
2249 
2250     if (mbedtls_ct_memcmp(hash, actual_hash, actual_hash_length) != 0) {
2251         status = PSA_ERROR_INVALID_SIGNATURE;
2252     }
2253 
2254 exit:
2255     mbedtls_platform_zeroize(actual_hash, sizeof(actual_hash));
2256     if (status != PSA_SUCCESS) {
2257         psa_hash_abort(operation);
2258     }
2259 
2260     return status;
2261 }
2262 
2263 psa_status_t psa_hash_compute(psa_algorithm_t alg,
2264                               const uint8_t *input, size_t input_length,
2265                               uint8_t *hash, size_t hash_size,
2266                               size_t *hash_length)
2267 {
2268     *hash_length = 0;
2269     if (!PSA_ALG_IS_HASH(alg)) {
2270         return PSA_ERROR_INVALID_ARGUMENT;
2271     }
2272 
2273     return psa_driver_wrapper_hash_compute(alg, input, input_length,
2274                                            hash, hash_size, hash_length);
2275 }
2276 
2277 psa_status_t psa_hash_compare(psa_algorithm_t alg,
2278                               const uint8_t *input, size_t input_length,
2279                               const uint8_t *hash, size_t hash_length)
2280 {
2281     uint8_t actual_hash[PSA_HASH_MAX_SIZE];
2282     size_t actual_hash_length;
2283 
2284     if (!PSA_ALG_IS_HASH(alg)) {
2285         return PSA_ERROR_INVALID_ARGUMENT;
2286     }
2287 
2288     psa_status_t status = psa_driver_wrapper_hash_compute(
2289         alg, input, input_length,
2290         actual_hash, sizeof(actual_hash),
2291         &actual_hash_length);
2292     if (status != PSA_SUCCESS) {
2293         goto exit;
2294     }
2295     if (actual_hash_length != hash_length) {
2296         status = PSA_ERROR_INVALID_SIGNATURE;
2297         goto exit;
2298     }
2299     if (mbedtls_ct_memcmp(hash, actual_hash, actual_hash_length) != 0) {
2300         status = PSA_ERROR_INVALID_SIGNATURE;
2301     }
2302 
2303 exit:
2304     mbedtls_platform_zeroize(actual_hash, sizeof(actual_hash));
2305     return status;
2306 }
2307 
2308 psa_status_t psa_hash_clone(const psa_hash_operation_t *source_operation,
2309                             psa_hash_operation_t *target_operation)
2310 {
2311     if (source_operation->id == 0 ||
2312         target_operation->id != 0) {
2313         return PSA_ERROR_BAD_STATE;
2314     }
2315 
2316     psa_status_t status = psa_driver_wrapper_hash_clone(source_operation,
2317                                                         target_operation);
2318     if (status != PSA_SUCCESS) {
2319         psa_hash_abort(target_operation);
2320     }
2321 
2322     return status;
2323 }
2324 
2325 
2326 /****************************************************************/
2327 /* MAC */
2328 /****************************************************************/
2329 
2330 psa_status_t psa_mac_abort(psa_mac_operation_t *operation)
2331 {
2332     /* Aborting a non-active operation is allowed */
2333     if (operation->id == 0) {
2334         return PSA_SUCCESS;
2335     }
2336 
2337     psa_status_t status = psa_driver_wrapper_mac_abort(operation);
2338     operation->mac_size = 0;
2339     operation->is_sign = 0;
2340     operation->id = 0;
2341 
2342     return status;
2343 }
2344 
2345 static psa_status_t psa_mac_finalize_alg_and_key_validation(
2346     psa_algorithm_t alg,
2347     const psa_key_attributes_t *attributes,
2348     uint8_t *mac_size)
2349 {
2350     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2351     psa_key_type_t key_type = psa_get_key_type(attributes);
2352     size_t key_bits = psa_get_key_bits(attributes);
2353 
2354     if (!PSA_ALG_IS_MAC(alg)) {
2355         return PSA_ERROR_INVALID_ARGUMENT;
2356     }
2357 
2358     /* Validate the combination of key type and algorithm */
2359     status = psa_mac_key_can_do(alg, key_type);
2360     if (status != PSA_SUCCESS) {
2361         return status;
2362     }
2363 
2364     /* Get the output length for the algorithm and key combination */
2365     *mac_size = PSA_MAC_LENGTH(key_type, key_bits, alg);
2366 
2367     if (*mac_size < 4) {
2368         /* A very short MAC is too short for security since it can be
2369          * brute-forced. Ancient protocols with 32-bit MACs do exist,
2370          * so we make this our minimum, even though 32 bits is still
2371          * too small for security. */
2372         return PSA_ERROR_NOT_SUPPORTED;
2373     }
2374 
2375     if (*mac_size > PSA_MAC_LENGTH(key_type, key_bits,
2376                                    PSA_ALG_FULL_LENGTH_MAC(alg))) {
2377         /* It's impossible to "truncate" to a larger length than the full length
2378          * of the algorithm. */
2379         return PSA_ERROR_INVALID_ARGUMENT;
2380     }
2381 
2382     if (*mac_size > PSA_MAC_MAX_SIZE) {
2383         /* PSA_MAC_LENGTH returns the correct length even for a MAC algorithm
2384          * that is disabled in the compile-time configuration. The result can
2385          * therefore be larger than PSA_MAC_MAX_SIZE, which does take the
2386          * configuration into account. In this case, force a return of
2387          * PSA_ERROR_NOT_SUPPORTED here. Otherwise psa_mac_verify(), or
2388          * psa_mac_compute(mac_size=PSA_MAC_MAX_SIZE), would return
2389          * PSA_ERROR_BUFFER_TOO_SMALL for an unsupported algorithm whose MAC size
2390          * is larger than PSA_MAC_MAX_SIZE, which is misleading and which breaks
2391          * systematically generated tests. */
2392         return PSA_ERROR_NOT_SUPPORTED;
2393     }
2394 
2395     return PSA_SUCCESS;
2396 }
2397 
2398 static psa_status_t psa_mac_setup(psa_mac_operation_t *operation,
2399                                   mbedtls_svc_key_id_t key,
2400                                   psa_algorithm_t alg,
2401                                   int is_sign)
2402 {
2403     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2404     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
2405     psa_key_slot_t *slot = NULL;
2406     psa_key_attributes_t attributes;
2407 
2408     /* A context must be freshly initialized before it can be set up. */
2409     if (operation->id != 0) {
2410         status = PSA_ERROR_BAD_STATE;
2411         goto exit;
2412     }
2413 
2414     status = psa_get_and_lock_key_slot_with_policy(
2415         key,
2416         &slot,
2417         is_sign ? PSA_KEY_USAGE_SIGN_MESSAGE : PSA_KEY_USAGE_VERIFY_MESSAGE,
2418         alg);
2419     if (status != PSA_SUCCESS) {
2420         goto exit;
2421     }
2422 
2423     attributes = (psa_key_attributes_t) {
2424         .core = slot->attr
2425     };
2426 
2427     status = psa_mac_finalize_alg_and_key_validation(alg, &attributes,
2428                                                      &operation->mac_size);
2429     if (status != PSA_SUCCESS) {
2430         goto exit;
2431     }
2432 
2433     operation->is_sign = is_sign;
2434     /* Dispatch the MAC setup call with validated input */
2435     if (is_sign) {
2436         status = psa_driver_wrapper_mac_sign_setup(operation,
2437                                                    &attributes,
2438                                                    slot->key.data,
2439                                                    slot->key.bytes,
2440                                                    alg);
2441     } else {
2442         status = psa_driver_wrapper_mac_verify_setup(operation,
2443                                                      &attributes,
2444                                                      slot->key.data,
2445                                                      slot->key.bytes,
2446                                                      alg);
2447     }
2448 
2449 exit:
2450     if (status != PSA_SUCCESS) {
2451         psa_mac_abort(operation);
2452     }
2453 
2454     unlock_status = psa_unlock_key_slot(slot);
2455 
2456     return (status == PSA_SUCCESS) ? unlock_status : status;
2457 }
2458 
2459 psa_status_t psa_mac_sign_setup(psa_mac_operation_t *operation,
2460                                 mbedtls_svc_key_id_t key,
2461                                 psa_algorithm_t alg)
2462 {
2463     return psa_mac_setup(operation, key, alg, 1);
2464 }
2465 
2466 psa_status_t psa_mac_verify_setup(psa_mac_operation_t *operation,
2467                                   mbedtls_svc_key_id_t key,
2468                                   psa_algorithm_t alg)
2469 {
2470     return psa_mac_setup(operation, key, alg, 0);
2471 }
2472 
2473 psa_status_t psa_mac_update(psa_mac_operation_t *operation,
2474                             const uint8_t *input,
2475                             size_t input_length)
2476 {
2477     if (operation->id == 0) {
2478         return PSA_ERROR_BAD_STATE;
2479     }
2480 
2481     /* Don't require hash implementations to behave correctly on a
2482      * zero-length input, which may have an invalid pointer. */
2483     if (input_length == 0) {
2484         return PSA_SUCCESS;
2485     }
2486 
2487     psa_status_t status = psa_driver_wrapper_mac_update(operation,
2488                                                         input, input_length);
2489     if (status != PSA_SUCCESS) {
2490         psa_mac_abort(operation);
2491     }
2492 
2493     return status;
2494 }
2495 
2496 psa_status_t psa_mac_sign_finish(psa_mac_operation_t *operation,
2497                                  uint8_t *mac,
2498                                  size_t mac_size,
2499                                  size_t *mac_length)
2500 {
2501     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2502     psa_status_t abort_status = PSA_ERROR_CORRUPTION_DETECTED;
2503 
2504     if (operation->id == 0) {
2505         status = PSA_ERROR_BAD_STATE;
2506         goto exit;
2507     }
2508 
2509     if (!operation->is_sign) {
2510         status = PSA_ERROR_BAD_STATE;
2511         goto exit;
2512     }
2513 
2514     /* Sanity check. This will guarantee that mac_size != 0 (and so mac != NULL)
2515      * once all the error checks are done. */
2516     if (operation->mac_size == 0) {
2517         status = PSA_ERROR_BAD_STATE;
2518         goto exit;
2519     }
2520 
2521     if (mac_size < operation->mac_size) {
2522         status = PSA_ERROR_BUFFER_TOO_SMALL;
2523         goto exit;
2524     }
2525 
2526     status = psa_driver_wrapper_mac_sign_finish(operation,
2527                                                 mac, operation->mac_size,
2528                                                 mac_length);
2529 
2530 exit:
2531     /* In case of success, set the potential excess room in the output buffer
2532      * to an invalid value, to avoid potentially leaking a longer MAC.
2533      * In case of error, set the output length and content to a safe default,
2534      * such that in case the caller misses an error check, the output would be
2535      * an unachievable MAC.
2536      */
2537     if (status != PSA_SUCCESS) {
2538         *mac_length = mac_size;
2539         operation->mac_size = 0;
2540     }
2541 
2542     psa_wipe_tag_output_buffer(mac, status, mac_size, *mac_length);
2543 
2544     abort_status = psa_mac_abort(operation);
2545 
2546     return status == PSA_SUCCESS ? abort_status : status;
2547 }
2548 
2549 psa_status_t psa_mac_verify_finish(psa_mac_operation_t *operation,
2550                                    const uint8_t *mac,
2551                                    size_t mac_length)
2552 {
2553     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2554     psa_status_t abort_status = PSA_ERROR_CORRUPTION_DETECTED;
2555 
2556     if (operation->id == 0) {
2557         status = PSA_ERROR_BAD_STATE;
2558         goto exit;
2559     }
2560 
2561     if (operation->is_sign) {
2562         status = PSA_ERROR_BAD_STATE;
2563         goto exit;
2564     }
2565 
2566     if (operation->mac_size != mac_length) {
2567         status = PSA_ERROR_INVALID_SIGNATURE;
2568         goto exit;
2569     }
2570 
2571     status = psa_driver_wrapper_mac_verify_finish(operation,
2572                                                   mac, mac_length);
2573 
2574 exit:
2575     abort_status = psa_mac_abort(operation);
2576 
2577     return status == PSA_SUCCESS ? abort_status : status;
2578 }
2579 
2580 static psa_status_t psa_mac_compute_internal(mbedtls_svc_key_id_t key,
2581                                              psa_algorithm_t alg,
2582                                              const uint8_t *input,
2583                                              size_t input_length,
2584                                              uint8_t *mac,
2585                                              size_t mac_size,
2586                                              size_t *mac_length,
2587                                              int is_sign)
2588 {
2589     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2590     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
2591     psa_key_slot_t *slot;
2592     uint8_t operation_mac_size = 0;
2593     psa_key_attributes_t attributes;
2594 
2595     status = psa_get_and_lock_key_slot_with_policy(
2596         key,
2597         &slot,
2598         is_sign ? PSA_KEY_USAGE_SIGN_MESSAGE : PSA_KEY_USAGE_VERIFY_MESSAGE,
2599         alg);
2600     if (status != PSA_SUCCESS) {
2601         goto exit;
2602     }
2603 
2604     attributes = (psa_key_attributes_t) {
2605         .core = slot->attr
2606     };
2607 
2608     status = psa_mac_finalize_alg_and_key_validation(alg, &attributes,
2609                                                      &operation_mac_size);
2610     if (status != PSA_SUCCESS) {
2611         goto exit;
2612     }
2613 
2614     if (mac_size < operation_mac_size) {
2615         status = PSA_ERROR_BUFFER_TOO_SMALL;
2616         goto exit;
2617     }
2618 
2619     status = psa_driver_wrapper_mac_compute(
2620         &attributes,
2621         slot->key.data, slot->key.bytes,
2622         alg,
2623         input, input_length,
2624         mac, operation_mac_size, mac_length);
2625 
2626 exit:
2627     /* In case of success, set the potential excess room in the output buffer
2628      * to an invalid value, to avoid potentially leaking a longer MAC.
2629      * In case of error, set the output length and content to a safe default,
2630      * such that in case the caller misses an error check, the output would be
2631      * an unachievable MAC.
2632      */
2633     if (status != PSA_SUCCESS) {
2634         *mac_length = mac_size;
2635         operation_mac_size = 0;
2636     }
2637 
2638     psa_wipe_tag_output_buffer(mac, status, mac_size, *mac_length);
2639 
2640     unlock_status = psa_unlock_key_slot(slot);
2641 
2642     return (status == PSA_SUCCESS) ? unlock_status : status;
2643 }
2644 
2645 psa_status_t psa_mac_compute(mbedtls_svc_key_id_t key,
2646                              psa_algorithm_t alg,
2647                              const uint8_t *input,
2648                              size_t input_length,
2649                              uint8_t *mac,
2650                              size_t mac_size,
2651                              size_t *mac_length)
2652 {
2653     return psa_mac_compute_internal(key, alg,
2654                                     input, input_length,
2655                                     mac, mac_size, mac_length, 1);
2656 }
2657 
2658 psa_status_t psa_mac_verify(mbedtls_svc_key_id_t key,
2659                             psa_algorithm_t alg,
2660                             const uint8_t *input,
2661                             size_t input_length,
2662                             const uint8_t *mac,
2663                             size_t mac_length)
2664 {
2665     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2666     uint8_t actual_mac[PSA_MAC_MAX_SIZE];
2667     size_t actual_mac_length;
2668 
2669     status = psa_mac_compute_internal(key, alg,
2670                                       input, input_length,
2671                                       actual_mac, sizeof(actual_mac),
2672                                       &actual_mac_length, 0);
2673     if (status != PSA_SUCCESS) {
2674         goto exit;
2675     }
2676 
2677     if (mac_length != actual_mac_length) {
2678         status = PSA_ERROR_INVALID_SIGNATURE;
2679         goto exit;
2680     }
2681     if (mbedtls_ct_memcmp(mac, actual_mac, actual_mac_length) != 0) {
2682         status = PSA_ERROR_INVALID_SIGNATURE;
2683         goto exit;
2684     }
2685 
2686 exit:
2687     mbedtls_platform_zeroize(actual_mac, sizeof(actual_mac));
2688 
2689     return status;
2690 }
2691 
2692 /****************************************************************/
2693 /* Asymmetric cryptography */
2694 /****************************************************************/
2695 
2696 static psa_status_t psa_sign_verify_check_alg(int input_is_message,
2697                                               psa_algorithm_t alg)
2698 {
2699     if (input_is_message) {
2700         if (!PSA_ALG_IS_SIGN_MESSAGE(alg)) {
2701             return PSA_ERROR_INVALID_ARGUMENT;
2702         }
2703 
2704         if (PSA_ALG_IS_SIGN_HASH(alg)) {
2705             if (!PSA_ALG_IS_HASH(PSA_ALG_SIGN_GET_HASH(alg))) {
2706                 return PSA_ERROR_INVALID_ARGUMENT;
2707             }
2708         }
2709     } else {
2710         if (!PSA_ALG_IS_SIGN_HASH(alg)) {
2711             return PSA_ERROR_INVALID_ARGUMENT;
2712         }
2713     }
2714 
2715     return PSA_SUCCESS;
2716 }
2717 
2718 static psa_status_t psa_sign_internal(mbedtls_svc_key_id_t key,
2719                                       int input_is_message,
2720                                       psa_algorithm_t alg,
2721                                       const uint8_t *input,
2722                                       size_t input_length,
2723                                       uint8_t *signature,
2724                                       size_t signature_size,
2725                                       size_t *signature_length)
2726 {
2727     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2728     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
2729     psa_key_slot_t *slot;
2730     psa_key_attributes_t attributes;
2731 
2732     *signature_length = 0;
2733 
2734     status = psa_sign_verify_check_alg(input_is_message, alg);
2735     if (status != PSA_SUCCESS) {
2736         return status;
2737     }
2738 
2739     /* Immediately reject a zero-length signature buffer. This guarantees
2740      * that signature must be a valid pointer. (On the other hand, the input
2741      * buffer can in principle be empty since it doesn't actually have
2742      * to be a hash.) */
2743     if (signature_size == 0) {
2744         return PSA_ERROR_BUFFER_TOO_SMALL;
2745     }
2746 
2747     status = psa_get_and_lock_key_slot_with_policy(
2748         key, &slot,
2749         input_is_message ? PSA_KEY_USAGE_SIGN_MESSAGE :
2750         PSA_KEY_USAGE_SIGN_HASH,
2751         alg);
2752 
2753     if (status != PSA_SUCCESS) {
2754         goto exit;
2755     }
2756 
2757     if (!PSA_KEY_TYPE_IS_KEY_PAIR(slot->attr.type)) {
2758         status = PSA_ERROR_INVALID_ARGUMENT;
2759         goto exit;
2760     }
2761 
2762     attributes = (psa_key_attributes_t) {
2763         .core = slot->attr
2764     };
2765 
2766     if (input_is_message) {
2767         status = psa_driver_wrapper_sign_message(
2768             &attributes, slot->key.data, slot->key.bytes,
2769             alg, input, input_length,
2770             signature, signature_size, signature_length);
2771     } else {
2772 
2773         status = psa_driver_wrapper_sign_hash(
2774             &attributes, slot->key.data, slot->key.bytes,
2775             alg, input, input_length,
2776             signature, signature_size, signature_length);
2777     }
2778 
2779 
2780 exit:
2781     psa_wipe_tag_output_buffer(signature, status, signature_size,
2782                                *signature_length);
2783 
2784     unlock_status = psa_unlock_key_slot(slot);
2785 
2786     return (status == PSA_SUCCESS) ? unlock_status : status;
2787 }
2788 
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 
2806     status = psa_get_and_lock_key_slot_with_policy(
2807         key, &slot,
2808         input_is_message ? PSA_KEY_USAGE_VERIFY_MESSAGE :
2809         PSA_KEY_USAGE_VERIFY_HASH,
2810         alg);
2811 
2812     if (status != PSA_SUCCESS) {
2813         return status;
2814     }
2815 
2816     psa_key_attributes_t attributes = {
2817         .core = slot->attr
2818     };
2819 
2820     if (input_is_message) {
2821         status = psa_driver_wrapper_verify_message(
2822             &attributes, slot->key.data, slot->key.bytes,
2823             alg, input, input_length,
2824             signature, signature_length);
2825     } else {
2826         status = psa_driver_wrapper_verify_hash(
2827             &attributes, slot->key.data, slot->key.bytes,
2828             alg, input, input_length,
2829             signature, signature_length);
2830     }
2831 
2832     unlock_status = psa_unlock_key_slot(slot);
2833 
2834     return (status == PSA_SUCCESS) ? unlock_status : status;
2835 
2836 }
2837 
2838 psa_status_t psa_sign_message_builtin(
2839     const psa_key_attributes_t *attributes,
2840     const uint8_t *key_buffer,
2841     size_t key_buffer_size,
2842     psa_algorithm_t alg,
2843     const uint8_t *input,
2844     size_t input_length,
2845     uint8_t *signature,
2846     size_t signature_size,
2847     size_t *signature_length)
2848 {
2849     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2850 
2851     if (PSA_ALG_IS_SIGN_HASH(alg)) {
2852         size_t hash_length;
2853         uint8_t hash[PSA_HASH_MAX_SIZE];
2854 
2855         status = psa_driver_wrapper_hash_compute(
2856             PSA_ALG_SIGN_GET_HASH(alg),
2857             input, input_length,
2858             hash, sizeof(hash), &hash_length);
2859 
2860         if (status != PSA_SUCCESS) {
2861             return status;
2862         }
2863 
2864         return psa_driver_wrapper_sign_hash(
2865             attributes, key_buffer, key_buffer_size,
2866             alg, hash, hash_length,
2867             signature, signature_size, signature_length);
2868     }
2869 
2870     return PSA_ERROR_NOT_SUPPORTED;
2871 }
2872 
2873 psa_status_t psa_sign_message(mbedtls_svc_key_id_t key,
2874                               psa_algorithm_t alg,
2875                               const uint8_t *input,
2876                               size_t input_length,
2877                               uint8_t *signature,
2878                               size_t signature_size,
2879                               size_t *signature_length)
2880 {
2881     return psa_sign_internal(
2882         key, 1, alg, input, input_length,
2883         signature, signature_size, signature_length);
2884 }
2885 
2886 psa_status_t psa_verify_message_builtin(
2887     const psa_key_attributes_t *attributes,
2888     const uint8_t *key_buffer,
2889     size_t key_buffer_size,
2890     psa_algorithm_t alg,
2891     const uint8_t *input,
2892     size_t input_length,
2893     const uint8_t *signature,
2894     size_t signature_length)
2895 {
2896     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2897 
2898     if (PSA_ALG_IS_SIGN_HASH(alg)) {
2899         size_t hash_length;
2900         uint8_t hash[PSA_HASH_MAX_SIZE];
2901 
2902         status = psa_driver_wrapper_hash_compute(
2903             PSA_ALG_SIGN_GET_HASH(alg),
2904             input, input_length,
2905             hash, sizeof(hash), &hash_length);
2906 
2907         if (status != PSA_SUCCESS) {
2908             return status;
2909         }
2910 
2911         return psa_driver_wrapper_verify_hash(
2912             attributes, key_buffer, key_buffer_size,
2913             alg, hash, hash_length,
2914             signature, signature_length);
2915     }
2916 
2917     return PSA_ERROR_NOT_SUPPORTED;
2918 }
2919 
2920 psa_status_t psa_verify_message(mbedtls_svc_key_id_t key,
2921                                 psa_algorithm_t alg,
2922                                 const uint8_t *input,
2923                                 size_t input_length,
2924                                 const uint8_t *signature,
2925                                 size_t signature_length)
2926 {
2927     return psa_verify_internal(
2928         key, 1, alg, input, input_length,
2929         signature, signature_length);
2930 }
2931 
2932 psa_status_t psa_sign_hash_builtin(
2933     const psa_key_attributes_t *attributes,
2934     const uint8_t *key_buffer, size_t key_buffer_size,
2935     psa_algorithm_t alg, const uint8_t *hash, size_t hash_length,
2936     uint8_t *signature, size_t signature_size, size_t *signature_length)
2937 {
2938     if (attributes->core.type == PSA_KEY_TYPE_RSA_KEY_PAIR) {
2939         if (PSA_ALG_IS_RSA_PKCS1V15_SIGN(alg) ||
2940             PSA_ALG_IS_RSA_PSS(alg)) {
2941 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) || \
2942             defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS)
2943             return mbedtls_psa_rsa_sign_hash(
2944                 attributes,
2945                 key_buffer, key_buffer_size,
2946                 alg, hash, hash_length,
2947                 signature, signature_size, signature_length);
2948 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) ||
2949         * defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS) */
2950         } else {
2951             return PSA_ERROR_INVALID_ARGUMENT;
2952         }
2953     } else if (PSA_KEY_TYPE_IS_ECC(attributes->core.type)) {
2954         if (PSA_ALG_IS_ECDSA(alg)) {
2955 #if defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
2956             defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)
2957             return mbedtls_psa_ecdsa_sign_hash(
2958                 attributes,
2959                 key_buffer, key_buffer_size,
2960                 alg, hash, hash_length,
2961                 signature, signature_size, signature_length);
2962 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
2963         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) */
2964         } else {
2965             return PSA_ERROR_INVALID_ARGUMENT;
2966         }
2967     }
2968 
2969     (void) key_buffer;
2970     (void) key_buffer_size;
2971     (void) hash;
2972     (void) hash_length;
2973     (void) signature;
2974     (void) signature_size;
2975     (void) signature_length;
2976 
2977     return PSA_ERROR_NOT_SUPPORTED;
2978 }
2979 
2980 psa_status_t psa_sign_hash(mbedtls_svc_key_id_t key,
2981                            psa_algorithm_t alg,
2982                            const uint8_t *hash,
2983                            size_t hash_length,
2984                            uint8_t *signature,
2985                            size_t signature_size,
2986                            size_t *signature_length)
2987 {
2988     return psa_sign_internal(
2989         key, 0, alg, hash, hash_length,
2990         signature, signature_size, signature_length);
2991 }
2992 
2993 psa_status_t psa_verify_hash_builtin(
2994     const psa_key_attributes_t *attributes,
2995     const uint8_t *key_buffer, size_t key_buffer_size,
2996     psa_algorithm_t alg, const uint8_t *hash, size_t hash_length,
2997     const uint8_t *signature, size_t signature_length)
2998 {
2999     if (PSA_KEY_TYPE_IS_RSA(attributes->core.type)) {
3000         if (PSA_ALG_IS_RSA_PKCS1V15_SIGN(alg) ||
3001             PSA_ALG_IS_RSA_PSS(alg)) {
3002 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) || \
3003             defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS)
3004             return mbedtls_psa_rsa_verify_hash(
3005                 attributes,
3006                 key_buffer, key_buffer_size,
3007                 alg, hash, hash_length,
3008                 signature, signature_length);
3009 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) ||
3010         * defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS) */
3011         } else {
3012             return PSA_ERROR_INVALID_ARGUMENT;
3013         }
3014     } else if (PSA_KEY_TYPE_IS_ECC(attributes->core.type)) {
3015         if (PSA_ALG_IS_ECDSA(alg)) {
3016 #if defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
3017             defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)
3018             return mbedtls_psa_ecdsa_verify_hash(
3019                 attributes,
3020                 key_buffer, key_buffer_size,
3021                 alg, hash, hash_length,
3022                 signature, signature_length);
3023 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
3024         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) */
3025         } else {
3026             return PSA_ERROR_INVALID_ARGUMENT;
3027         }
3028     }
3029 
3030     (void) key_buffer;
3031     (void) key_buffer_size;
3032     (void) hash;
3033     (void) hash_length;
3034     (void) signature;
3035     (void) signature_length;
3036 
3037     return PSA_ERROR_NOT_SUPPORTED;
3038 }
3039 
3040 psa_status_t psa_verify_hash(mbedtls_svc_key_id_t key,
3041                              psa_algorithm_t alg,
3042                              const uint8_t *hash,
3043                              size_t hash_length,
3044                              const uint8_t *signature,
3045                              size_t signature_length)
3046 {
3047     return psa_verify_internal(
3048         key, 0, alg, hash, hash_length,
3049         signature, signature_length);
3050 }
3051 
3052 psa_status_t psa_asymmetric_encrypt(mbedtls_svc_key_id_t key,
3053                                     psa_algorithm_t alg,
3054                                     const uint8_t *input,
3055                                     size_t input_length,
3056                                     const uint8_t *salt,
3057                                     size_t salt_length,
3058                                     uint8_t *output,
3059                                     size_t output_size,
3060                                     size_t *output_length)
3061 {
3062     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3063     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
3064     psa_key_slot_t *slot;
3065     psa_key_attributes_t attributes;
3066 
3067     (void) input;
3068     (void) input_length;
3069     (void) salt;
3070     (void) output;
3071     (void) output_size;
3072 
3073     *output_length = 0;
3074 
3075     if (!PSA_ALG_IS_RSA_OAEP(alg) && salt_length != 0) {
3076         return PSA_ERROR_INVALID_ARGUMENT;
3077     }
3078 
3079     status = psa_get_and_lock_transparent_key_slot_with_policy(
3080         key, &slot, PSA_KEY_USAGE_ENCRYPT, alg);
3081     if (status != PSA_SUCCESS) {
3082         return status;
3083     }
3084     if (!(PSA_KEY_TYPE_IS_PUBLIC_KEY(slot->attr.type) ||
3085           PSA_KEY_TYPE_IS_KEY_PAIR(slot->attr.type))) {
3086         status = PSA_ERROR_INVALID_ARGUMENT;
3087         goto exit;
3088     }
3089 
3090     attributes = (psa_key_attributes_t) {
3091         .core = slot->attr
3092     };
3093 
3094     status = psa_driver_wrapper_asymmetric_encrypt(
3095         &attributes, slot->key.data, slot->key.bytes,
3096         alg, input, input_length, salt, salt_length,
3097         output, output_size, output_length);
3098 exit:
3099     unlock_status = psa_unlock_key_slot(slot);
3100 
3101     return (status == PSA_SUCCESS) ? unlock_status : status;
3102 }
3103 
3104 psa_status_t psa_asymmetric_decrypt(mbedtls_svc_key_id_t key,
3105                                     psa_algorithm_t alg,
3106                                     const uint8_t *input,
3107                                     size_t input_length,
3108                                     const uint8_t *salt,
3109                                     size_t salt_length,
3110                                     uint8_t *output,
3111                                     size_t output_size,
3112                                     size_t *output_length)
3113 {
3114     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3115     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
3116     psa_key_slot_t *slot;
3117     psa_key_attributes_t attributes;
3118 
3119     (void) input;
3120     (void) input_length;
3121     (void) salt;
3122     (void) output;
3123     (void) output_size;
3124 
3125     *output_length = 0;
3126 
3127     if (!PSA_ALG_IS_RSA_OAEP(alg) && salt_length != 0) {
3128         return PSA_ERROR_INVALID_ARGUMENT;
3129     }
3130 
3131     status = psa_get_and_lock_transparent_key_slot_with_policy(
3132         key, &slot, PSA_KEY_USAGE_DECRYPT, alg);
3133     if (status != PSA_SUCCESS) {
3134         return status;
3135     }
3136     if (!PSA_KEY_TYPE_IS_KEY_PAIR(slot->attr.type)) {
3137         status = PSA_ERROR_INVALID_ARGUMENT;
3138         goto exit;
3139     }
3140 
3141     attributes = (psa_key_attributes_t) {
3142         .core = slot->attr
3143     };
3144 
3145     status = psa_driver_wrapper_asymmetric_decrypt(
3146         &attributes, slot->key.data, slot->key.bytes,
3147         alg, input, input_length, salt, salt_length,
3148         output, output_size, output_length);
3149 
3150 exit:
3151     unlock_status = psa_unlock_key_slot(slot);
3152 
3153     return (status == PSA_SUCCESS) ? unlock_status : status;
3154 }
3155 
3156 /****************************************************************/
3157 /* Asymmetric interruptible cryptography                        */
3158 /****************************************************************/
3159 
3160 static uint32_t psa_interruptible_max_ops = PSA_INTERRUPTIBLE_MAX_OPS_UNLIMITED;
3161 
3162 void psa_interruptible_set_max_ops(uint32_t max_ops)
3163 {
3164     psa_interruptible_max_ops = max_ops;
3165 }
3166 
3167 uint32_t psa_interruptible_get_max_ops(void)
3168 {
3169     return psa_interruptible_max_ops;
3170 }
3171 
3172 uint32_t psa_sign_hash_get_num_ops(
3173     const psa_sign_hash_interruptible_operation_t *operation)
3174 {
3175     return operation->num_ops;
3176 }
3177 
3178 uint32_t psa_verify_hash_get_num_ops(
3179     const psa_verify_hash_interruptible_operation_t *operation)
3180 {
3181     return operation->num_ops;
3182 }
3183 
3184 static psa_status_t psa_sign_hash_abort_internal(
3185     psa_sign_hash_interruptible_operation_t *operation)
3186 {
3187     if (operation->id == 0) {
3188         /* The object has (apparently) been initialized but it is not (yet)
3189          * in use. It's ok to call abort on such an object, and there's
3190          * nothing to do. */
3191         return PSA_SUCCESS;
3192     }
3193 
3194     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3195 
3196     status = psa_driver_wrapper_sign_hash_abort(operation);
3197 
3198     operation->id = 0;
3199 
3200     /* Do not clear either the error_occurred or num_ops elements here as they
3201      * only want to be cleared by the application calling abort, not by abort
3202      * being called at completion of an operation. */
3203 
3204     return status;
3205 }
3206 
3207 psa_status_t psa_sign_hash_start(
3208     psa_sign_hash_interruptible_operation_t *operation,
3209     mbedtls_svc_key_id_t key, psa_algorithm_t alg,
3210     const uint8_t *hash, size_t hash_length)
3211 {
3212     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3213     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
3214     psa_key_slot_t *slot;
3215     psa_key_attributes_t attributes;
3216 
3217     /* Check that start has not been previously called, or operation has not
3218      * previously errored. */
3219     if (operation->id != 0 || operation->error_occurred) {
3220         return PSA_ERROR_BAD_STATE;
3221     }
3222 
3223     status = psa_sign_verify_check_alg(0, alg);
3224     if (status != PSA_SUCCESS) {
3225         operation->error_occurred = 1;
3226         return status;
3227     }
3228 
3229     status = psa_get_and_lock_key_slot_with_policy(key, &slot,
3230                                                    PSA_KEY_USAGE_SIGN_HASH,
3231                                                    alg);
3232 
3233     if (status != PSA_SUCCESS) {
3234         goto exit;
3235     }
3236 
3237     if (!PSA_KEY_TYPE_IS_KEY_PAIR(slot->attr.type)) {
3238         status = PSA_ERROR_INVALID_ARGUMENT;
3239         goto exit;
3240     }
3241 
3242     attributes = (psa_key_attributes_t) {
3243         .core = slot->attr
3244     };
3245 
3246     /* Ensure ops count gets reset, in case of operation re-use. */
3247     operation->num_ops = 0;
3248 
3249     status = psa_driver_wrapper_sign_hash_start(operation, &attributes,
3250                                                 slot->key.data,
3251                                                 slot->key.bytes, alg,
3252                                                 hash, hash_length);
3253 exit:
3254 
3255     if (status != PSA_SUCCESS) {
3256         operation->error_occurred = 1;
3257         psa_sign_hash_abort_internal(operation);
3258     }
3259 
3260     unlock_status = psa_unlock_key_slot(slot);
3261 
3262     if (unlock_status != PSA_SUCCESS) {
3263         operation->error_occurred = 1;
3264     }
3265 
3266     return (status == PSA_SUCCESS) ? unlock_status : status;
3267 }
3268 
3269 
3270 psa_status_t psa_sign_hash_complete(
3271     psa_sign_hash_interruptible_operation_t *operation,
3272     uint8_t *signature, size_t signature_size,
3273     size_t *signature_length)
3274 {
3275     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3276 
3277     *signature_length = 0;
3278 
3279     /* Check that start has been called first, and that operation has not
3280      * previously errored. */
3281     if (operation->id == 0 || operation->error_occurred) {
3282         status = PSA_ERROR_BAD_STATE;
3283         goto exit;
3284     }
3285 
3286     /* Immediately reject a zero-length signature buffer. This guarantees that
3287      * signature must be a valid pointer. */
3288     if (signature_size == 0) {
3289         status = PSA_ERROR_BUFFER_TOO_SMALL;
3290         goto exit;
3291     }
3292 
3293     status = psa_driver_wrapper_sign_hash_complete(operation, signature,
3294                                                    signature_size,
3295                                                    signature_length);
3296 
3297     /* Update ops count with work done. */
3298     operation->num_ops = psa_driver_wrapper_sign_hash_get_num_ops(operation);
3299 
3300 exit:
3301 
3302     psa_wipe_tag_output_buffer(signature, status, signature_size,
3303                                *signature_length);
3304 
3305     if (status != PSA_OPERATION_INCOMPLETE) {
3306         if (status != PSA_SUCCESS) {
3307             operation->error_occurred = 1;
3308         }
3309 
3310         psa_sign_hash_abort_internal(operation);
3311     }
3312 
3313     return status;
3314 }
3315 
3316 psa_status_t psa_sign_hash_abort(
3317     psa_sign_hash_interruptible_operation_t *operation)
3318 {
3319     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3320 
3321     status = psa_sign_hash_abort_internal(operation);
3322 
3323     /* We clear the number of ops done here, so that it is not cleared when
3324      * the operation fails or succeeds, only on manual abort. */
3325     operation->num_ops = 0;
3326 
3327     /* Likewise, failure state. */
3328     operation->error_occurred = 0;
3329 
3330     return status;
3331 }
3332 
3333 static psa_status_t psa_verify_hash_abort_internal(
3334     psa_verify_hash_interruptible_operation_t *operation)
3335 {
3336     if (operation->id == 0) {
3337         /* The object has (apparently) been initialized but it is not (yet)
3338          * in use. It's ok to call abort on such an object, and there's
3339          * nothing to do. */
3340         return PSA_SUCCESS;
3341     }
3342 
3343     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3344 
3345     status = psa_driver_wrapper_verify_hash_abort(operation);
3346 
3347     operation->id = 0;
3348 
3349     /* Do not clear either the error_occurred or num_ops elements here as they
3350      * only want to be cleared by the application calling abort, not by abort
3351      * being called at completion of an operation. */
3352 
3353     return status;
3354 }
3355 
3356 psa_status_t psa_verify_hash_start(
3357     psa_verify_hash_interruptible_operation_t *operation,
3358     mbedtls_svc_key_id_t key, psa_algorithm_t alg,
3359     const uint8_t *hash, size_t hash_length,
3360     const uint8_t *signature, size_t signature_length)
3361 {
3362     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3363     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
3364     psa_key_slot_t *slot;
3365 
3366     /* Check that start has not been previously called, or operation has not
3367      * previously errored. */
3368     if (operation->id != 0 || operation->error_occurred) {
3369         return PSA_ERROR_BAD_STATE;
3370     }
3371 
3372     status = psa_sign_verify_check_alg(0, alg);
3373     if (status != PSA_SUCCESS) {
3374         operation->error_occurred = 1;
3375         return status;
3376     }
3377 
3378     status = psa_get_and_lock_key_slot_with_policy(key, &slot,
3379                                                    PSA_KEY_USAGE_VERIFY_HASH,
3380                                                    alg);
3381 
3382     if (status != PSA_SUCCESS) {
3383         operation->error_occurred = 1;
3384         return status;
3385     }
3386 
3387     psa_key_attributes_t attributes = {
3388         .core = slot->attr
3389     };
3390 
3391     /* Ensure ops count gets reset, in case of operation re-use. */
3392     operation->num_ops = 0;
3393 
3394     status = psa_driver_wrapper_verify_hash_start(operation, &attributes,
3395                                                   slot->key.data,
3396                                                   slot->key.bytes,
3397                                                   alg, hash, hash_length,
3398                                                   signature, signature_length);
3399 
3400     if (status != PSA_SUCCESS) {
3401         operation->error_occurred = 1;
3402         psa_verify_hash_abort_internal(operation);
3403     }
3404 
3405     unlock_status = psa_unlock_key_slot(slot);
3406 
3407     if (unlock_status != PSA_SUCCESS) {
3408         operation->error_occurred = 1;
3409     }
3410 
3411     return (status == PSA_SUCCESS) ? unlock_status : status;
3412 }
3413 
3414 psa_status_t psa_verify_hash_complete(
3415     psa_verify_hash_interruptible_operation_t *operation)
3416 {
3417     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3418 
3419     /* Check that start has been called first, and that operation has not
3420      * previously errored. */
3421     if (operation->id == 0 || operation->error_occurred) {
3422         status = PSA_ERROR_BAD_STATE;
3423         goto exit;
3424     }
3425 
3426     status = psa_driver_wrapper_verify_hash_complete(operation);
3427 
3428     /* Update ops count with work done. */
3429     operation->num_ops = psa_driver_wrapper_verify_hash_get_num_ops(
3430         operation);
3431 
3432 exit:
3433 
3434     if (status != PSA_OPERATION_INCOMPLETE) {
3435         if (status != PSA_SUCCESS) {
3436             operation->error_occurred = 1;
3437         }
3438 
3439         psa_verify_hash_abort_internal(operation);
3440     }
3441 
3442     return status;
3443 }
3444 
3445 psa_status_t psa_verify_hash_abort(
3446     psa_verify_hash_interruptible_operation_t *operation)
3447 {
3448     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3449 
3450     status = psa_verify_hash_abort_internal(operation);
3451 
3452     /* We clear the number of ops done here, so that it is not cleared when
3453      * the operation fails or succeeds, only on manual abort. */
3454     operation->num_ops = 0;
3455 
3456     /* Likewise, failure state. */
3457     operation->error_occurred = 0;
3458 
3459     return status;
3460 }
3461 
3462 /****************************************************************/
3463 /* Asymmetric interruptible cryptography internal               */
3464 /* implementations                                              */
3465 /****************************************************************/
3466 
3467 void mbedtls_psa_interruptible_set_max_ops(uint32_t max_ops)
3468 {
3469 
3470 #if (defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
3471     defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)) && \
3472     defined(MBEDTLS_ECP_RESTARTABLE)
3473 
3474     /* Internal implementation uses zero to indicate infinite number max ops,
3475      * therefore avoid this value, and set to minimum possible. */
3476     if (max_ops == 0) {
3477         max_ops = 1;
3478     }
3479 
3480     mbedtls_ecp_set_max_ops(max_ops);
3481 #else
3482     (void) max_ops;
3483 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
3484         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) &&
3485         * defined( MBEDTLS_ECP_RESTARTABLE ) */
3486 }
3487 
3488 uint32_t mbedtls_psa_sign_hash_get_num_ops(
3489     const mbedtls_psa_sign_hash_interruptible_operation_t *operation)
3490 {
3491 #if (defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
3492     defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)) && \
3493     defined(MBEDTLS_ECP_RESTARTABLE)
3494 
3495     return operation->num_ops;
3496 #else
3497     (void) operation;
3498     return 0;
3499 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
3500         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) &&
3501         * defined( MBEDTLS_ECP_RESTARTABLE ) */
3502 }
3503 
3504 uint32_t mbedtls_psa_verify_hash_get_num_ops(
3505     const mbedtls_psa_verify_hash_interruptible_operation_t *operation)
3506 {
3507     #if (defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
3508     defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)) && \
3509     defined(MBEDTLS_ECP_RESTARTABLE)
3510 
3511     return operation->num_ops;
3512 #else
3513     (void) operation;
3514     return 0;
3515 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
3516         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) &&
3517         * defined( MBEDTLS_ECP_RESTARTABLE ) */
3518 }
3519 
3520 psa_status_t mbedtls_psa_sign_hash_start(
3521     mbedtls_psa_sign_hash_interruptible_operation_t *operation,
3522     const psa_key_attributes_t *attributes, const uint8_t *key_buffer,
3523     size_t key_buffer_size, psa_algorithm_t alg,
3524     const uint8_t *hash, size_t hash_length)
3525 {
3526     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3527     size_t required_hash_length;
3528 
3529     if (!PSA_KEY_TYPE_IS_ECC(attributes->core.type)) {
3530         return PSA_ERROR_NOT_SUPPORTED;
3531     }
3532 
3533     if (!PSA_ALG_IS_ECDSA(alg)) {
3534         return PSA_ERROR_NOT_SUPPORTED;
3535     }
3536 
3537 #if (defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
3538     defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)) && \
3539     defined(MBEDTLS_ECP_RESTARTABLE)
3540 
3541     mbedtls_ecdsa_restart_init(&operation->restart_ctx);
3542 
3543     /* Ensure num_ops is zero'ed in case of context re-use. */
3544     operation->num_ops = 0;
3545 
3546     status = mbedtls_psa_ecp_load_representation(attributes->core.type,
3547                                                  attributes->core.bits,
3548                                                  key_buffer,
3549                                                  key_buffer_size,
3550                                                  &operation->ctx);
3551 
3552     if (status != PSA_SUCCESS) {
3553         return status;
3554     }
3555 
3556     operation->coordinate_bytes = PSA_BITS_TO_BYTES(
3557         operation->ctx->grp.nbits);
3558 
3559     psa_algorithm_t hash_alg = PSA_ALG_SIGN_GET_HASH(alg);
3560     operation->md_alg = mbedtls_md_type_from_psa_alg(hash_alg);
3561     operation->alg = alg;
3562 
3563     /* We only need to store the same length of hash as the private key size
3564      * here, it would be truncated by the internal implementation anyway. */
3565     required_hash_length = (hash_length < operation->coordinate_bytes ?
3566                             hash_length : operation->coordinate_bytes);
3567 
3568     if (required_hash_length > sizeof(operation->hash)) {
3569         /* Shouldn't happen, but better safe than sorry. */
3570         return PSA_ERROR_CORRUPTION_DETECTED;
3571     }
3572 
3573     memcpy(operation->hash, hash, required_hash_length);
3574     operation->hash_length = required_hash_length;
3575 
3576     return PSA_SUCCESS;
3577 
3578 #else
3579     (void) operation;
3580     (void) key_buffer;
3581     (void) key_buffer_size;
3582     (void) alg;
3583     (void) hash;
3584     (void) hash_length;
3585     (void) status;
3586     (void) required_hash_length;
3587 
3588     return PSA_ERROR_NOT_SUPPORTED;
3589 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
3590         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) &&
3591         * defined( MBEDTLS_ECP_RESTARTABLE ) */
3592 }
3593 
3594 psa_status_t mbedtls_psa_sign_hash_complete(
3595     mbedtls_psa_sign_hash_interruptible_operation_t *operation,
3596     uint8_t *signature, size_t signature_size,
3597     size_t *signature_length)
3598 {
3599 #if (defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
3600     defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)) && \
3601     defined(MBEDTLS_ECP_RESTARTABLE)
3602 
3603     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3604     mbedtls_mpi r;
3605     mbedtls_mpi s;
3606 
3607     mbedtls_mpi_init(&r);
3608     mbedtls_mpi_init(&s);
3609 
3610     /* Ensure max_ops is set to the current value (or default). */
3611     mbedtls_psa_interruptible_set_max_ops(psa_interruptible_get_max_ops());
3612 
3613     if (signature_size < 2 * operation->coordinate_bytes) {
3614         status = PSA_ERROR_BUFFER_TOO_SMALL;
3615         goto exit;
3616     }
3617 
3618     if (PSA_ALG_ECDSA_IS_DETERMINISTIC(operation->alg)) {
3619 
3620 #if defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)
3621         status = mbedtls_to_psa_error(
3622             mbedtls_ecdsa_sign_det_restartable(&operation->ctx->grp,
3623                                                &r,
3624                                                &s,
3625                                                &operation->ctx->d,
3626                                                operation->hash,
3627                                                operation->hash_length,
3628                                                operation->md_alg,
3629                                                mbedtls_psa_get_random,
3630                                                MBEDTLS_PSA_RANDOM_STATE,
3631                                                &operation->restart_ctx));
3632 #else /* defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) */
3633         status = PSA_ERROR_NOT_SUPPORTED;
3634         goto exit;
3635 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) */
3636     } else {
3637         status = mbedtls_to_psa_error(
3638             mbedtls_ecdsa_sign_restartable(&operation->ctx->grp,
3639                                            &r,
3640                                            &s,
3641                                            &operation->ctx->d,
3642                                            operation->hash,
3643                                            operation->hash_length,
3644                                            mbedtls_psa_get_random,
3645                                            MBEDTLS_PSA_RANDOM_STATE,
3646                                            mbedtls_psa_get_random,
3647                                            MBEDTLS_PSA_RANDOM_STATE,
3648                                            &operation->restart_ctx));
3649     }
3650 
3651     /* Hide the fact that the restart context only holds a delta of number of
3652      * ops done during the last operation, not an absolute value. */
3653     operation->num_ops += operation->restart_ctx.ecp.ops_done;
3654 
3655     if (status == PSA_SUCCESS) {
3656         status =  mbedtls_to_psa_error(
3657             mbedtls_mpi_write_binary(&r,
3658                                      signature,
3659                                      operation->coordinate_bytes)
3660             );
3661 
3662         if (status != PSA_SUCCESS) {
3663             goto exit;
3664         }
3665 
3666         status =  mbedtls_to_psa_error(
3667             mbedtls_mpi_write_binary(&s,
3668                                      signature +
3669                                      operation->coordinate_bytes,
3670                                      operation->coordinate_bytes)
3671             );
3672 
3673         if (status != PSA_SUCCESS) {
3674             goto exit;
3675         }
3676 
3677         *signature_length = operation->coordinate_bytes * 2;
3678 
3679         status = PSA_SUCCESS;
3680     }
3681 
3682 exit:
3683 
3684     mbedtls_mpi_free(&r);
3685     mbedtls_mpi_free(&s);
3686     return status;
3687 
3688  #else
3689 
3690     (void) operation;
3691     (void) signature;
3692     (void) signature_size;
3693     (void) signature_length;
3694 
3695     return PSA_ERROR_NOT_SUPPORTED;
3696 
3697 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
3698         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) &&
3699         * defined( MBEDTLS_ECP_RESTARTABLE ) */
3700 }
3701 
3702 psa_status_t mbedtls_psa_sign_hash_abort(
3703     mbedtls_psa_sign_hash_interruptible_operation_t *operation)
3704 {
3705 
3706 #if (defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
3707     defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)) && \
3708     defined(MBEDTLS_ECP_RESTARTABLE)
3709 
3710     if (operation->ctx) {
3711         mbedtls_ecdsa_free(operation->ctx);
3712         mbedtls_free(operation->ctx);
3713         operation->ctx = NULL;
3714     }
3715 
3716     mbedtls_ecdsa_restart_free(&operation->restart_ctx);
3717 
3718     operation->num_ops = 0;
3719 
3720     return PSA_SUCCESS;
3721 
3722 #else
3723 
3724     (void) operation;
3725 
3726     return PSA_ERROR_NOT_SUPPORTED;
3727 
3728 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
3729         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) &&
3730         * defined( MBEDTLS_ECP_RESTARTABLE ) */
3731 }
3732 
3733 psa_status_t mbedtls_psa_verify_hash_start(
3734     mbedtls_psa_verify_hash_interruptible_operation_t *operation,
3735     const psa_key_attributes_t *attributes,
3736     const uint8_t *key_buffer, size_t key_buffer_size,
3737     psa_algorithm_t alg,
3738     const uint8_t *hash, size_t hash_length,
3739     const uint8_t *signature, size_t signature_length)
3740 {
3741     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3742     size_t coordinate_bytes = 0;
3743     size_t required_hash_length = 0;
3744 
3745     if (!PSA_KEY_TYPE_IS_ECC(attributes->core.type)) {
3746         return PSA_ERROR_NOT_SUPPORTED;
3747     }
3748 
3749     if (!PSA_ALG_IS_ECDSA(alg)) {
3750         return PSA_ERROR_NOT_SUPPORTED;
3751     }
3752 
3753 #if (defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
3754     defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)) && \
3755     defined(MBEDTLS_ECP_RESTARTABLE)
3756 
3757     mbedtls_ecdsa_restart_init(&operation->restart_ctx);
3758     mbedtls_mpi_init(&operation->r);
3759     mbedtls_mpi_init(&operation->s);
3760 
3761     /* Ensure num_ops is zero'ed in case of context re-use. */
3762     operation->num_ops = 0;
3763 
3764     status = mbedtls_psa_ecp_load_representation(attributes->core.type,
3765                                                  attributes->core.bits,
3766                                                  key_buffer,
3767                                                  key_buffer_size,
3768                                                  &operation->ctx);
3769 
3770     if (status != PSA_SUCCESS) {
3771         return status;
3772     }
3773 
3774     coordinate_bytes = PSA_BITS_TO_BYTES(operation->ctx->grp.nbits);
3775 
3776     if (signature_length != 2 * coordinate_bytes) {
3777         return PSA_ERROR_INVALID_SIGNATURE;
3778     }
3779 
3780     status = mbedtls_to_psa_error(
3781         mbedtls_mpi_read_binary(&operation->r,
3782                                 signature,
3783                                 coordinate_bytes));
3784 
3785     if (status != PSA_SUCCESS) {
3786         return status;
3787     }
3788 
3789     status = mbedtls_to_psa_error(
3790         mbedtls_mpi_read_binary(&operation->s,
3791                                 signature +
3792                                 coordinate_bytes,
3793                                 coordinate_bytes));
3794 
3795     if (status != PSA_SUCCESS) {
3796         return status;
3797     }
3798 
3799     status = mbedtls_psa_ecp_load_public_part(operation->ctx);
3800 
3801     if (status != PSA_SUCCESS) {
3802         return status;
3803     }
3804 
3805     /* We only need to store the same length of hash as the private key size
3806      * here, it would be truncated by the internal implementation anyway. */
3807     required_hash_length = (hash_length < coordinate_bytes ? hash_length :
3808                             coordinate_bytes);
3809 
3810     if (required_hash_length > sizeof(operation->hash)) {
3811         /* Shouldn't happen, but better safe than sorry. */
3812         return PSA_ERROR_CORRUPTION_DETECTED;
3813     }
3814 
3815     memcpy(operation->hash, hash, required_hash_length);
3816     operation->hash_length = required_hash_length;
3817 
3818     return PSA_SUCCESS;
3819 #else
3820     (void) operation;
3821     (void) key_buffer;
3822     (void) key_buffer_size;
3823     (void) alg;
3824     (void) hash;
3825     (void) hash_length;
3826     (void) signature;
3827     (void) signature_length;
3828     (void) status;
3829     (void) coordinate_bytes;
3830     (void) required_hash_length;
3831 
3832     return PSA_ERROR_NOT_SUPPORTED;
3833 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
3834         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) &&
3835         * defined( MBEDTLS_ECP_RESTARTABLE ) */
3836 }
3837 
3838 psa_status_t mbedtls_psa_verify_hash_complete(
3839     mbedtls_psa_verify_hash_interruptible_operation_t *operation)
3840 {
3841 
3842 #if (defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
3843     defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)) && \
3844     defined(MBEDTLS_ECP_RESTARTABLE)
3845 
3846     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3847 
3848     /* Ensure max_ops is set to the current value (or default). */
3849     mbedtls_psa_interruptible_set_max_ops(psa_interruptible_get_max_ops());
3850 
3851     status = mbedtls_to_psa_error(
3852         mbedtls_ecdsa_verify_restartable(&operation->ctx->grp,
3853                                          operation->hash,
3854                                          operation->hash_length,
3855                                          &operation->ctx->Q,
3856                                          &operation->r,
3857                                          &operation->s,
3858                                          &operation->restart_ctx));
3859 
3860     /* Hide the fact that the restart context only holds a delta of number of
3861      * ops done during the last operation, not an absolute value. */
3862     operation->num_ops += operation->restart_ctx.ecp.ops_done;
3863 
3864     return status;
3865 #else
3866     (void) operation;
3867 
3868     return PSA_ERROR_NOT_SUPPORTED;
3869 
3870 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
3871         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) &&
3872         * defined( MBEDTLS_ECP_RESTARTABLE ) */
3873 }
3874 
3875 psa_status_t mbedtls_psa_verify_hash_abort(
3876     mbedtls_psa_verify_hash_interruptible_operation_t *operation)
3877 {
3878 
3879 #if (defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
3880     defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)) && \
3881     defined(MBEDTLS_ECP_RESTARTABLE)
3882 
3883     if (operation->ctx) {
3884         mbedtls_ecdsa_free(operation->ctx);
3885         mbedtls_free(operation->ctx);
3886         operation->ctx = NULL;
3887     }
3888 
3889     mbedtls_ecdsa_restart_free(&operation->restart_ctx);
3890 
3891     operation->num_ops = 0;
3892 
3893     mbedtls_mpi_free(&operation->r);
3894     mbedtls_mpi_free(&operation->s);
3895 
3896     return PSA_SUCCESS;
3897 
3898 #else
3899     (void) operation;
3900 
3901     return PSA_ERROR_NOT_SUPPORTED;
3902 
3903 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
3904         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) &&
3905         * defined( MBEDTLS_ECP_RESTARTABLE ) */
3906 }
3907 
3908 /****************************************************************/
3909 /* Symmetric cryptography */
3910 /****************************************************************/
3911 
3912 static psa_status_t psa_cipher_setup(psa_cipher_operation_t *operation,
3913                                      mbedtls_svc_key_id_t key,
3914                                      psa_algorithm_t alg,
3915                                      mbedtls_operation_t cipher_operation)
3916 {
3917     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3918     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
3919     psa_key_slot_t *slot = NULL;
3920     psa_key_usage_t usage = (cipher_operation == MBEDTLS_ENCRYPT ?
3921                              PSA_KEY_USAGE_ENCRYPT :
3922                              PSA_KEY_USAGE_DECRYPT);
3923     psa_key_attributes_t attributes;
3924 
3925     /* A context must be freshly initialized before it can be set up. */
3926     if (operation->id != 0) {
3927         status = PSA_ERROR_BAD_STATE;
3928         goto exit;
3929     }
3930 
3931     if (!PSA_ALG_IS_CIPHER(alg)) {
3932         status = PSA_ERROR_INVALID_ARGUMENT;
3933         goto exit;
3934     }
3935 
3936     status = psa_get_and_lock_key_slot_with_policy(key, &slot, usage, alg);
3937     if (status != PSA_SUCCESS) {
3938         goto exit;
3939     }
3940 
3941     /* Initialize the operation struct members, except for id. The id member
3942      * is used to indicate to psa_cipher_abort that there are resources to free,
3943      * so we only set it (in the driver wrapper) after resources have been
3944      * allocated/initialized. */
3945     operation->iv_set = 0;
3946     if (alg == PSA_ALG_ECB_NO_PADDING) {
3947         operation->iv_required = 0;
3948     } else {
3949         operation->iv_required = 1;
3950     }
3951     operation->default_iv_length = PSA_CIPHER_IV_LENGTH(slot->attr.type, alg);
3952 
3953     attributes = (psa_key_attributes_t) {
3954         .core = slot->attr
3955     };
3956 
3957     /* Try doing the operation through a driver before using software fallback. */
3958     if (cipher_operation == MBEDTLS_ENCRYPT) {
3959         status = psa_driver_wrapper_cipher_encrypt_setup(operation,
3960                                                          &attributes,
3961                                                          slot->key.data,
3962                                                          slot->key.bytes,
3963                                                          alg);
3964     } else {
3965         status = psa_driver_wrapper_cipher_decrypt_setup(operation,
3966                                                          &attributes,
3967                                                          slot->key.data,
3968                                                          slot->key.bytes,
3969                                                          alg);
3970     }
3971 
3972 exit:
3973     if (status != PSA_SUCCESS) {
3974         psa_cipher_abort(operation);
3975     }
3976 
3977     unlock_status = psa_unlock_key_slot(slot);
3978 
3979     return (status == PSA_SUCCESS) ? unlock_status : status;
3980 }
3981 
3982 psa_status_t psa_cipher_encrypt_setup(psa_cipher_operation_t *operation,
3983                                       mbedtls_svc_key_id_t key,
3984                                       psa_algorithm_t alg)
3985 {
3986     return psa_cipher_setup(operation, key, alg, MBEDTLS_ENCRYPT);
3987 }
3988 
3989 psa_status_t psa_cipher_decrypt_setup(psa_cipher_operation_t *operation,
3990                                       mbedtls_svc_key_id_t key,
3991                                       psa_algorithm_t alg)
3992 {
3993     return psa_cipher_setup(operation, key, alg, MBEDTLS_DECRYPT);
3994 }
3995 
3996 psa_status_t psa_cipher_generate_iv(psa_cipher_operation_t *operation,
3997                                     uint8_t *iv,
3998                                     size_t iv_size,
3999                                     size_t *iv_length)
4000 {
4001     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4002     uint8_t local_iv[PSA_CIPHER_IV_MAX_SIZE];
4003     size_t default_iv_length = 0;
4004 
4005     if (operation->id == 0) {
4006         status = PSA_ERROR_BAD_STATE;
4007         goto exit;
4008     }
4009 
4010     if (operation->iv_set || !operation->iv_required) {
4011         status = PSA_ERROR_BAD_STATE;
4012         goto exit;
4013     }
4014 
4015     default_iv_length = operation->default_iv_length;
4016     if (iv_size < default_iv_length) {
4017         status = PSA_ERROR_BUFFER_TOO_SMALL;
4018         goto exit;
4019     }
4020 
4021     if (default_iv_length > PSA_CIPHER_IV_MAX_SIZE) {
4022         status = PSA_ERROR_GENERIC_ERROR;
4023         goto exit;
4024     }
4025 
4026     status = psa_generate_random(local_iv, default_iv_length);
4027     if (status != PSA_SUCCESS) {
4028         goto exit;
4029     }
4030 
4031     status = psa_driver_wrapper_cipher_set_iv(operation,
4032                                               local_iv, default_iv_length);
4033 
4034 exit:
4035     if (status == PSA_SUCCESS) {
4036         memcpy(iv, local_iv, default_iv_length);
4037         *iv_length = default_iv_length;
4038         operation->iv_set = 1;
4039     } else {
4040         *iv_length = 0;
4041         psa_cipher_abort(operation);
4042     }
4043 
4044     return status;
4045 }
4046 
4047 psa_status_t psa_cipher_set_iv(psa_cipher_operation_t *operation,
4048                                const uint8_t *iv,
4049                                size_t iv_length)
4050 {
4051     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4052 
4053     if (operation->id == 0) {
4054         status = PSA_ERROR_BAD_STATE;
4055         goto exit;
4056     }
4057 
4058     if (operation->iv_set || !operation->iv_required) {
4059         status = PSA_ERROR_BAD_STATE;
4060         goto exit;
4061     }
4062 
4063     if (iv_length > PSA_CIPHER_IV_MAX_SIZE) {
4064         status = PSA_ERROR_INVALID_ARGUMENT;
4065         goto exit;
4066     }
4067 
4068     status = psa_driver_wrapper_cipher_set_iv(operation,
4069                                               iv,
4070                                               iv_length);
4071 
4072 exit:
4073     if (status == PSA_SUCCESS) {
4074         operation->iv_set = 1;
4075     } else {
4076         psa_cipher_abort(operation);
4077     }
4078     return status;
4079 }
4080 
4081 psa_status_t psa_cipher_update(psa_cipher_operation_t *operation,
4082                                const uint8_t *input,
4083                                size_t input_length,
4084                                uint8_t *output,
4085                                size_t output_size,
4086                                size_t *output_length)
4087 {
4088     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4089 
4090     if (operation->id == 0) {
4091         status = PSA_ERROR_BAD_STATE;
4092         goto exit;
4093     }
4094 
4095     if (operation->iv_required && !operation->iv_set) {
4096         status = PSA_ERROR_BAD_STATE;
4097         goto exit;
4098     }
4099 
4100     status = psa_driver_wrapper_cipher_update(operation,
4101                                               input,
4102                                               input_length,
4103                                               output,
4104                                               output_size,
4105                                               output_length);
4106 
4107 exit:
4108     if (status != PSA_SUCCESS) {
4109         psa_cipher_abort(operation);
4110     }
4111 
4112     return status;
4113 }
4114 
4115 psa_status_t psa_cipher_finish(psa_cipher_operation_t *operation,
4116                                uint8_t *output,
4117                                size_t output_size,
4118                                size_t *output_length)
4119 {
4120     psa_status_t status = PSA_ERROR_GENERIC_ERROR;
4121 
4122     if (operation->id == 0) {
4123         status = PSA_ERROR_BAD_STATE;
4124         goto exit;
4125     }
4126 
4127     if (operation->iv_required && !operation->iv_set) {
4128         status = PSA_ERROR_BAD_STATE;
4129         goto exit;
4130     }
4131 
4132     status = psa_driver_wrapper_cipher_finish(operation,
4133                                               output,
4134                                               output_size,
4135                                               output_length);
4136 
4137 exit:
4138     if (status == PSA_SUCCESS) {
4139         return psa_cipher_abort(operation);
4140     } else {
4141         *output_length = 0;
4142         (void) psa_cipher_abort(operation);
4143 
4144         return status;
4145     }
4146 }
4147 
4148 psa_status_t psa_cipher_abort(psa_cipher_operation_t *operation)
4149 {
4150     if (operation->id == 0) {
4151         /* The object has (apparently) been initialized but it is not (yet)
4152          * in use. It's ok to call abort on such an object, and there's
4153          * nothing to do. */
4154         return PSA_SUCCESS;
4155     }
4156 
4157     psa_driver_wrapper_cipher_abort(operation);
4158 
4159     operation->id = 0;
4160     operation->iv_set = 0;
4161     operation->iv_required = 0;
4162 
4163     return PSA_SUCCESS;
4164 }
4165 
4166 psa_status_t psa_cipher_encrypt(mbedtls_svc_key_id_t key,
4167                                 psa_algorithm_t alg,
4168                                 const uint8_t *input,
4169                                 size_t input_length,
4170                                 uint8_t *output,
4171                                 size_t output_size,
4172                                 size_t *output_length)
4173 {
4174     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4175     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
4176     psa_key_slot_t *slot = NULL;
4177     uint8_t local_iv[PSA_CIPHER_IV_MAX_SIZE];
4178     size_t default_iv_length = 0;
4179     psa_key_attributes_t attributes;
4180 
4181     if (!PSA_ALG_IS_CIPHER(alg)) {
4182         status = PSA_ERROR_INVALID_ARGUMENT;
4183         goto exit;
4184     }
4185 
4186     status = psa_get_and_lock_key_slot_with_policy(key, &slot,
4187                                                    PSA_KEY_USAGE_ENCRYPT,
4188                                                    alg);
4189     if (status != PSA_SUCCESS) {
4190         goto exit;
4191     }
4192 
4193     attributes = (psa_key_attributes_t) {
4194         .core = slot->attr
4195     };
4196 
4197     default_iv_length = PSA_CIPHER_IV_LENGTH(slot->attr.type, alg);
4198     if (default_iv_length > PSA_CIPHER_IV_MAX_SIZE) {
4199         status = PSA_ERROR_GENERIC_ERROR;
4200         goto exit;
4201     }
4202 
4203     if (default_iv_length > 0) {
4204         if (output_size < default_iv_length) {
4205             status = PSA_ERROR_BUFFER_TOO_SMALL;
4206             goto exit;
4207         }
4208 
4209         status = psa_generate_random(local_iv, default_iv_length);
4210         if (status != PSA_SUCCESS) {
4211             goto exit;
4212         }
4213     }
4214 
4215     status = psa_driver_wrapper_cipher_encrypt(
4216         &attributes, slot->key.data, slot->key.bytes,
4217         alg, local_iv, default_iv_length, input, input_length,
4218         psa_crypto_buffer_offset(output, default_iv_length),
4219         output_size - default_iv_length, output_length);
4220 
4221 exit:
4222     unlock_status = psa_unlock_key_slot(slot);
4223     if (status == PSA_SUCCESS) {
4224         status = unlock_status;
4225     }
4226 
4227     if (status == PSA_SUCCESS) {
4228         if (default_iv_length > 0) {
4229             memcpy(output, local_iv, default_iv_length);
4230         }
4231         *output_length += default_iv_length;
4232     } else {
4233         *output_length = 0;
4234     }
4235 
4236     return status;
4237 }
4238 
4239 psa_status_t psa_cipher_decrypt(mbedtls_svc_key_id_t key,
4240                                 psa_algorithm_t alg,
4241                                 const uint8_t *input,
4242                                 size_t input_length,
4243                                 uint8_t *output,
4244                                 size_t output_size,
4245                                 size_t *output_length)
4246 {
4247     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4248     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
4249     psa_key_slot_t *slot = NULL;
4250     psa_key_attributes_t attributes;
4251 
4252     if (!PSA_ALG_IS_CIPHER(alg)) {
4253         status = PSA_ERROR_INVALID_ARGUMENT;
4254         goto exit;
4255     }
4256 
4257     status = psa_get_and_lock_key_slot_with_policy(key, &slot,
4258                                                    PSA_KEY_USAGE_DECRYPT,
4259                                                    alg);
4260     if (status != PSA_SUCCESS) {
4261         goto exit;
4262     }
4263 
4264     attributes = (psa_key_attributes_t) {
4265         .core = slot->attr
4266     };
4267 
4268     if (alg == PSA_ALG_CCM_STAR_NO_TAG &&
4269         input_length < PSA_BLOCK_CIPHER_BLOCK_LENGTH(slot->attr.type)) {
4270         status = PSA_ERROR_INVALID_ARGUMENT;
4271         goto exit;
4272     } else if (input_length < PSA_CIPHER_IV_LENGTH(slot->attr.type, alg)) {
4273         status = PSA_ERROR_INVALID_ARGUMENT;
4274         goto exit;
4275     }
4276 
4277     status = psa_driver_wrapper_cipher_decrypt(
4278         &attributes, slot->key.data, slot->key.bytes,
4279         alg, input, input_length,
4280         output, output_size, output_length);
4281 
4282 exit:
4283     unlock_status = psa_unlock_key_slot(slot);
4284     if (status == PSA_SUCCESS) {
4285         status = unlock_status;
4286     }
4287 
4288     if (status != PSA_SUCCESS) {
4289         *output_length = 0;
4290     }
4291 
4292     return status;
4293 }
4294 
4295 
4296 /****************************************************************/
4297 /* AEAD */
4298 /****************************************************************/
4299 
4300 /* Helper function to get the base algorithm from its variants. */
4301 static psa_algorithm_t psa_aead_get_base_algorithm(psa_algorithm_t alg)
4302 {
4303     return PSA_ALG_AEAD_WITH_DEFAULT_LENGTH_TAG(alg);
4304 }
4305 
4306 /* Helper function to perform common nonce length checks. */
4307 static psa_status_t psa_aead_check_nonce_length(psa_algorithm_t alg,
4308                                                 size_t nonce_length)
4309 {
4310     psa_algorithm_t base_alg = psa_aead_get_base_algorithm(alg);
4311 
4312     switch (base_alg) {
4313 #if defined(PSA_WANT_ALG_GCM)
4314         case PSA_ALG_GCM:
4315             /* Not checking max nonce size here as GCM spec allows almost
4316              * arbitrarily large nonces. Please note that we do not generally
4317              * recommend the usage of nonces of greater length than
4318              * PSA_AEAD_NONCE_MAX_SIZE, as large nonces are hashed to a shorter
4319              * size, which can then lead to collisions if you encrypt a very
4320              * large number of messages.*/
4321             if (nonce_length != 0) {
4322                 return PSA_SUCCESS;
4323             }
4324             break;
4325 #endif /* PSA_WANT_ALG_GCM */
4326 #if defined(PSA_WANT_ALG_CCM)
4327         case PSA_ALG_CCM:
4328             if (nonce_length >= 7 && nonce_length <= 13) {
4329                 return PSA_SUCCESS;
4330             }
4331             break;
4332 #endif /* PSA_WANT_ALG_CCM */
4333 #if defined(PSA_WANT_ALG_CHACHA20_POLY1305)
4334         case PSA_ALG_CHACHA20_POLY1305:
4335             if (nonce_length == 12) {
4336                 return PSA_SUCCESS;
4337             } else if (nonce_length == 8) {
4338                 return PSA_ERROR_NOT_SUPPORTED;
4339             }
4340             break;
4341 #endif /* PSA_WANT_ALG_CHACHA20_POLY1305 */
4342         default:
4343             (void) nonce_length;
4344             return PSA_ERROR_NOT_SUPPORTED;
4345     }
4346 
4347     return PSA_ERROR_INVALID_ARGUMENT;
4348 }
4349 
4350 static psa_status_t psa_aead_check_algorithm(psa_algorithm_t alg)
4351 {
4352     if (!PSA_ALG_IS_AEAD(alg) || PSA_ALG_IS_WILDCARD(alg)) {
4353         return PSA_ERROR_INVALID_ARGUMENT;
4354     }
4355 
4356     return PSA_SUCCESS;
4357 }
4358 
4359 psa_status_t psa_aead_encrypt(mbedtls_svc_key_id_t key,
4360                               psa_algorithm_t alg,
4361                               const uint8_t *nonce,
4362                               size_t nonce_length,
4363                               const uint8_t *additional_data,
4364                               size_t additional_data_length,
4365                               const uint8_t *plaintext,
4366                               size_t plaintext_length,
4367                               uint8_t *ciphertext,
4368                               size_t ciphertext_size,
4369                               size_t *ciphertext_length)
4370 {
4371     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4372     psa_key_slot_t *slot;
4373 
4374     *ciphertext_length = 0;
4375 
4376     status = psa_aead_check_algorithm(alg);
4377     if (status != PSA_SUCCESS) {
4378         return status;
4379     }
4380 
4381     status = psa_get_and_lock_key_slot_with_policy(
4382         key, &slot, PSA_KEY_USAGE_ENCRYPT, alg);
4383     if (status != PSA_SUCCESS) {
4384         return status;
4385     }
4386 
4387     psa_key_attributes_t attributes = {
4388         .core = slot->attr
4389     };
4390 
4391     status = psa_aead_check_nonce_length(alg, nonce_length);
4392     if (status != PSA_SUCCESS) {
4393         goto exit;
4394     }
4395 
4396     status = psa_driver_wrapper_aead_encrypt(
4397         &attributes, slot->key.data, slot->key.bytes,
4398         alg,
4399         nonce, nonce_length,
4400         additional_data, additional_data_length,
4401         plaintext, plaintext_length,
4402         ciphertext, ciphertext_size, ciphertext_length);
4403 
4404     if (status != PSA_SUCCESS && ciphertext_size != 0) {
4405         memset(ciphertext, 0, ciphertext_size);
4406     }
4407 
4408 exit:
4409     psa_unlock_key_slot(slot);
4410 
4411     return status;
4412 }
4413 
4414 psa_status_t psa_aead_decrypt(mbedtls_svc_key_id_t key,
4415                               psa_algorithm_t alg,
4416                               const uint8_t *nonce,
4417                               size_t nonce_length,
4418                               const uint8_t *additional_data,
4419                               size_t additional_data_length,
4420                               const uint8_t *ciphertext,
4421                               size_t ciphertext_length,
4422                               uint8_t *plaintext,
4423                               size_t plaintext_size,
4424                               size_t *plaintext_length)
4425 {
4426     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4427     psa_key_slot_t *slot;
4428 
4429     *plaintext_length = 0;
4430 
4431     status = psa_aead_check_algorithm(alg);
4432     if (status != PSA_SUCCESS) {
4433         return status;
4434     }
4435 
4436     status = psa_get_and_lock_key_slot_with_policy(
4437         key, &slot, PSA_KEY_USAGE_DECRYPT, alg);
4438     if (status != PSA_SUCCESS) {
4439         return status;
4440     }
4441 
4442     psa_key_attributes_t attributes = {
4443         .core = slot->attr
4444     };
4445 
4446     status = psa_aead_check_nonce_length(alg, nonce_length);
4447     if (status != PSA_SUCCESS) {
4448         goto exit;
4449     }
4450 
4451     status = psa_driver_wrapper_aead_decrypt(
4452         &attributes, slot->key.data, slot->key.bytes,
4453         alg,
4454         nonce, nonce_length,
4455         additional_data, additional_data_length,
4456         ciphertext, ciphertext_length,
4457         plaintext, plaintext_size, plaintext_length);
4458 
4459     if (status != PSA_SUCCESS && plaintext_size != 0) {
4460         memset(plaintext, 0, plaintext_size);
4461     }
4462 
4463 exit:
4464     psa_unlock_key_slot(slot);
4465 
4466     return status;
4467 }
4468 
4469 static psa_status_t psa_validate_tag_length(psa_algorithm_t alg)
4470 {
4471     const uint8_t tag_len = PSA_ALG_AEAD_GET_TAG_LENGTH(alg);
4472 
4473     switch (PSA_ALG_AEAD_WITH_SHORTENED_TAG(alg, 0)) {
4474 #if defined(PSA_WANT_ALG_CCM)
4475         case PSA_ALG_AEAD_WITH_SHORTENED_TAG(PSA_ALG_CCM, 0):
4476             /* CCM allows the following tag lengths: 4, 6, 8, 10, 12, 14, 16.*/
4477             if (tag_len < 4 || tag_len > 16 || tag_len % 2) {
4478                 return PSA_ERROR_INVALID_ARGUMENT;
4479             }
4480             break;
4481 #endif /* PSA_WANT_ALG_CCM */
4482 
4483 #if defined(PSA_WANT_ALG_GCM)
4484         case PSA_ALG_AEAD_WITH_SHORTENED_TAG(PSA_ALG_GCM, 0):
4485             /* GCM allows the following tag lengths: 4, 8, 12, 13, 14, 15, 16. */
4486             if (tag_len != 4 && tag_len != 8 && (tag_len < 12 || tag_len > 16)) {
4487                 return PSA_ERROR_INVALID_ARGUMENT;
4488             }
4489             break;
4490 #endif /* PSA_WANT_ALG_GCM */
4491 
4492 #if defined(PSA_WANT_ALG_CHACHA20_POLY1305)
4493         case PSA_ALG_AEAD_WITH_SHORTENED_TAG(PSA_ALG_CHACHA20_POLY1305, 0):
4494             /* We only support the default tag length. */
4495             if (tag_len != 16) {
4496                 return PSA_ERROR_INVALID_ARGUMENT;
4497             }
4498             break;
4499 #endif /* PSA_WANT_ALG_CHACHA20_POLY1305 */
4500 
4501         default:
4502             (void) tag_len;
4503             return PSA_ERROR_NOT_SUPPORTED;
4504     }
4505     return PSA_SUCCESS;
4506 }
4507 
4508 /* Set the key for a multipart authenticated operation. */
4509 static psa_status_t psa_aead_setup(psa_aead_operation_t *operation,
4510                                    int is_encrypt,
4511                                    mbedtls_svc_key_id_t key,
4512                                    psa_algorithm_t alg)
4513 {
4514     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4515     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
4516     psa_key_slot_t *slot = NULL;
4517     psa_key_usage_t key_usage = 0;
4518     psa_key_attributes_t attributes;
4519 
4520     status = psa_aead_check_algorithm(alg);
4521     if (status != PSA_SUCCESS) {
4522         goto exit;
4523     }
4524 
4525     if (operation->id != 0) {
4526         status = PSA_ERROR_BAD_STATE;
4527         goto exit;
4528     }
4529 
4530     if (operation->nonce_set || operation->lengths_set ||
4531         operation->ad_started || operation->body_started) {
4532         status = PSA_ERROR_BAD_STATE;
4533         goto exit;
4534     }
4535 
4536     if (is_encrypt) {
4537         key_usage = PSA_KEY_USAGE_ENCRYPT;
4538     } else {
4539         key_usage = PSA_KEY_USAGE_DECRYPT;
4540     }
4541 
4542     status = psa_get_and_lock_key_slot_with_policy(key, &slot, key_usage,
4543                                                    alg);
4544     if (status != PSA_SUCCESS) {
4545         goto exit;
4546     }
4547 
4548     attributes = (psa_key_attributes_t) {
4549         .core = slot->attr
4550     };
4551 
4552     if ((status = psa_validate_tag_length(alg)) != PSA_SUCCESS) {
4553         goto exit;
4554     }
4555 
4556     if (is_encrypt) {
4557         status = psa_driver_wrapper_aead_encrypt_setup(operation,
4558                                                        &attributes,
4559                                                        slot->key.data,
4560                                                        slot->key.bytes,
4561                                                        alg);
4562     } else {
4563         status = psa_driver_wrapper_aead_decrypt_setup(operation,
4564                                                        &attributes,
4565                                                        slot->key.data,
4566                                                        slot->key.bytes,
4567                                                        alg);
4568     }
4569     if (status != PSA_SUCCESS) {
4570         goto exit;
4571     }
4572 
4573     operation->key_type = psa_get_key_type(&attributes);
4574 
4575 exit:
4576     unlock_status = psa_unlock_key_slot(slot);
4577 
4578     if (status == PSA_SUCCESS) {
4579         status = unlock_status;
4580         operation->alg = psa_aead_get_base_algorithm(alg);
4581         operation->is_encrypt = is_encrypt;
4582     } else {
4583         psa_aead_abort(operation);
4584     }
4585 
4586     return status;
4587 }
4588 
4589 /* Set the key for a multipart authenticated encryption operation. */
4590 psa_status_t psa_aead_encrypt_setup(psa_aead_operation_t *operation,
4591                                     mbedtls_svc_key_id_t key,
4592                                     psa_algorithm_t alg)
4593 {
4594     return psa_aead_setup(operation, 1, key, alg);
4595 }
4596 
4597 /* Set the key for a multipart authenticated decryption operation. */
4598 psa_status_t psa_aead_decrypt_setup(psa_aead_operation_t *operation,
4599                                     mbedtls_svc_key_id_t key,
4600                                     psa_algorithm_t alg)
4601 {
4602     return psa_aead_setup(operation, 0, key, alg);
4603 }
4604 
4605 /* Generate a random nonce / IV for multipart AEAD operation */
4606 psa_status_t psa_aead_generate_nonce(psa_aead_operation_t *operation,
4607                                      uint8_t *nonce,
4608                                      size_t nonce_size,
4609                                      size_t *nonce_length)
4610 {
4611     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4612     uint8_t local_nonce[PSA_AEAD_NONCE_MAX_SIZE];
4613     size_t required_nonce_size = 0;
4614 
4615     *nonce_length = 0;
4616 
4617     if (operation->id == 0) {
4618         status = PSA_ERROR_BAD_STATE;
4619         goto exit;
4620     }
4621 
4622     if (operation->nonce_set || !operation->is_encrypt) {
4623         status = PSA_ERROR_BAD_STATE;
4624         goto exit;
4625     }
4626 
4627     /* For CCM, this size may not be correct according to the PSA
4628      * specification. The PSA Crypto 1.0.1 specification states:
4629      *
4630      * CCM encodes the plaintext length pLen in L octets, with L the smallest
4631      * integer >= 2 where pLen < 2^(8L). The nonce length is then 15 - L bytes.
4632      *
4633      * However this restriction that L has to be the smallest integer is not
4634      * applied in practice, and it is not implementable here since the
4635      * plaintext length may or may not be known at this time. */
4636     required_nonce_size = PSA_AEAD_NONCE_LENGTH(operation->key_type,
4637                                                 operation->alg);
4638     if (nonce_size < required_nonce_size) {
4639         status = PSA_ERROR_BUFFER_TOO_SMALL;
4640         goto exit;
4641     }
4642 
4643     status = psa_generate_random(local_nonce, required_nonce_size);
4644     if (status != PSA_SUCCESS) {
4645         goto exit;
4646     }
4647 
4648     status = psa_aead_set_nonce(operation, local_nonce, required_nonce_size);
4649 
4650 exit:
4651     if (status == PSA_SUCCESS) {
4652         memcpy(nonce, local_nonce, required_nonce_size);
4653         *nonce_length = required_nonce_size;
4654     } else {
4655         psa_aead_abort(operation);
4656     }
4657 
4658     return status;
4659 }
4660 
4661 /* Set the nonce for a multipart authenticated encryption or decryption
4662    operation.*/
4663 psa_status_t psa_aead_set_nonce(psa_aead_operation_t *operation,
4664                                 const uint8_t *nonce,
4665                                 size_t nonce_length)
4666 {
4667     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4668 
4669     if (operation->id == 0) {
4670         status = PSA_ERROR_BAD_STATE;
4671         goto exit;
4672     }
4673 
4674     if (operation->nonce_set) {
4675         status = PSA_ERROR_BAD_STATE;
4676         goto exit;
4677     }
4678 
4679     status = psa_aead_check_nonce_length(operation->alg, nonce_length);
4680     if (status != PSA_SUCCESS) {
4681         status = PSA_ERROR_INVALID_ARGUMENT;
4682         goto exit;
4683     }
4684 
4685     status = psa_driver_wrapper_aead_set_nonce(operation, nonce,
4686                                                nonce_length);
4687 
4688 exit:
4689     if (status == PSA_SUCCESS) {
4690         operation->nonce_set = 1;
4691     } else {
4692         psa_aead_abort(operation);
4693     }
4694 
4695     return status;
4696 }
4697 
4698 /* Declare the lengths of the message and additional data for multipart AEAD. */
4699 psa_status_t psa_aead_set_lengths(psa_aead_operation_t *operation,
4700                                   size_t ad_length,
4701                                   size_t plaintext_length)
4702 {
4703     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4704 
4705     if (operation->id == 0) {
4706         status = PSA_ERROR_BAD_STATE;
4707         goto exit;
4708     }
4709 
4710     if (operation->lengths_set || operation->ad_started ||
4711         operation->body_started) {
4712         status = PSA_ERROR_BAD_STATE;
4713         goto exit;
4714     }
4715 
4716     switch (operation->alg) {
4717 #if defined(PSA_WANT_ALG_GCM)
4718         case PSA_ALG_GCM:
4719             /* Lengths can only be too large for GCM if size_t is bigger than 32
4720              * bits. Without the guard this code will generate warnings on 32bit
4721              * builds. */
4722 #if SIZE_MAX > UINT32_MAX
4723             if (((uint64_t) ad_length) >> 61 != 0 ||
4724                 ((uint64_t) plaintext_length) > 0xFFFFFFFE0ull) {
4725                 status = PSA_ERROR_INVALID_ARGUMENT;
4726                 goto exit;
4727             }
4728 #endif
4729             break;
4730 #endif /* PSA_WANT_ALG_GCM */
4731 #if defined(PSA_WANT_ALG_CCM)
4732         case PSA_ALG_CCM:
4733             if (ad_length > 0xFF00) {
4734                 status = PSA_ERROR_INVALID_ARGUMENT;
4735                 goto exit;
4736             }
4737             break;
4738 #endif /* PSA_WANT_ALG_CCM */
4739 #if defined(PSA_WANT_ALG_CHACHA20_POLY1305)
4740         case PSA_ALG_CHACHA20_POLY1305:
4741             /* No length restrictions for ChaChaPoly. */
4742             break;
4743 #endif /* PSA_WANT_ALG_CHACHA20_POLY1305 */
4744         default:
4745             break;
4746     }
4747 
4748     status = psa_driver_wrapper_aead_set_lengths(operation, ad_length,
4749                                                  plaintext_length);
4750 
4751 exit:
4752     if (status == PSA_SUCCESS) {
4753         operation->ad_remaining = ad_length;
4754         operation->body_remaining = plaintext_length;
4755         operation->lengths_set = 1;
4756     } else {
4757         psa_aead_abort(operation);
4758     }
4759 
4760     return status;
4761 }
4762 
4763 /* Pass additional data to an active multipart AEAD operation. */
4764 psa_status_t psa_aead_update_ad(psa_aead_operation_t *operation,
4765                                 const uint8_t *input,
4766                                 size_t input_length)
4767 {
4768     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4769 
4770     if (operation->id == 0) {
4771         status = PSA_ERROR_BAD_STATE;
4772         goto exit;
4773     }
4774 
4775     if (!operation->nonce_set || operation->body_started) {
4776         status = PSA_ERROR_BAD_STATE;
4777         goto exit;
4778     }
4779 
4780     if (operation->lengths_set) {
4781         if (operation->ad_remaining < input_length) {
4782             status = PSA_ERROR_INVALID_ARGUMENT;
4783             goto exit;
4784         }
4785 
4786         operation->ad_remaining -= input_length;
4787     }
4788 #if defined(PSA_WANT_ALG_CCM)
4789     else if (operation->alg == PSA_ALG_CCM) {
4790         status = PSA_ERROR_BAD_STATE;
4791         goto exit;
4792     }
4793 #endif /* PSA_WANT_ALG_CCM */
4794 
4795     status = psa_driver_wrapper_aead_update_ad(operation, input,
4796                                                input_length);
4797 
4798 exit:
4799     if (status == PSA_SUCCESS) {
4800         operation->ad_started = 1;
4801     } else {
4802         psa_aead_abort(operation);
4803     }
4804 
4805     return status;
4806 }
4807 
4808 /* Encrypt or decrypt a message fragment in an active multipart AEAD
4809    operation.*/
4810 psa_status_t psa_aead_update(psa_aead_operation_t *operation,
4811                              const uint8_t *input,
4812                              size_t input_length,
4813                              uint8_t *output,
4814                              size_t output_size,
4815                              size_t *output_length)
4816 {
4817     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4818 
4819     *output_length = 0;
4820 
4821     if (operation->id == 0) {
4822         status = PSA_ERROR_BAD_STATE;
4823         goto exit;
4824     }
4825 
4826     if (!operation->nonce_set) {
4827         status = PSA_ERROR_BAD_STATE;
4828         goto exit;
4829     }
4830 
4831     if (operation->lengths_set) {
4832         /* Additional data length was supplied, but not all the additional
4833            data was supplied.*/
4834         if (operation->ad_remaining != 0) {
4835             status = PSA_ERROR_INVALID_ARGUMENT;
4836             goto exit;
4837         }
4838 
4839         /* Too much data provided. */
4840         if (operation->body_remaining < input_length) {
4841             status = PSA_ERROR_INVALID_ARGUMENT;
4842             goto exit;
4843         }
4844 
4845         operation->body_remaining -= input_length;
4846     }
4847 #if defined(PSA_WANT_ALG_CCM)
4848     else if (operation->alg == PSA_ALG_CCM) {
4849         status = PSA_ERROR_BAD_STATE;
4850         goto exit;
4851     }
4852 #endif /* PSA_WANT_ALG_CCM */
4853 
4854     status = psa_driver_wrapper_aead_update(operation, input, input_length,
4855                                             output, output_size,
4856                                             output_length);
4857 
4858 exit:
4859     if (status == PSA_SUCCESS) {
4860         operation->body_started = 1;
4861     } else {
4862         psa_aead_abort(operation);
4863     }
4864 
4865     return status;
4866 }
4867 
4868 static psa_status_t psa_aead_final_checks(const psa_aead_operation_t *operation)
4869 {
4870     if (operation->id == 0 || !operation->nonce_set) {
4871         return PSA_ERROR_BAD_STATE;
4872     }
4873 
4874     if (operation->lengths_set && (operation->ad_remaining != 0 ||
4875                                    operation->body_remaining != 0)) {
4876         return PSA_ERROR_INVALID_ARGUMENT;
4877     }
4878 
4879     return PSA_SUCCESS;
4880 }
4881 
4882 /* Finish encrypting a message in a multipart AEAD operation. */
4883 psa_status_t psa_aead_finish(psa_aead_operation_t *operation,
4884                              uint8_t *ciphertext,
4885                              size_t ciphertext_size,
4886                              size_t *ciphertext_length,
4887                              uint8_t *tag,
4888                              size_t tag_size,
4889                              size_t *tag_length)
4890 {
4891     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4892 
4893     *ciphertext_length = 0;
4894     *tag_length = tag_size;
4895 
4896     status = psa_aead_final_checks(operation);
4897     if (status != PSA_SUCCESS) {
4898         goto exit;
4899     }
4900 
4901     if (!operation->is_encrypt) {
4902         status = PSA_ERROR_BAD_STATE;
4903         goto exit;
4904     }
4905 
4906     status = psa_driver_wrapper_aead_finish(operation, ciphertext,
4907                                             ciphertext_size,
4908                                             ciphertext_length,
4909                                             tag, tag_size, tag_length);
4910 
4911 exit:
4912 
4913 
4914     /* In case the operation fails and the user fails to check for failure or
4915      * the zero tag size, make sure the tag is set to something implausible.
4916      * Even if the operation succeeds, make sure we clear the rest of the
4917      * buffer to prevent potential leakage of anything previously placed in
4918      * the same buffer.*/
4919     psa_wipe_tag_output_buffer(tag, status, tag_size, *tag_length);
4920 
4921     psa_aead_abort(operation);
4922 
4923     return status;
4924 }
4925 
4926 /* Finish authenticating and decrypting a message in a multipart AEAD
4927    operation.*/
4928 psa_status_t psa_aead_verify(psa_aead_operation_t *operation,
4929                              uint8_t *plaintext,
4930                              size_t plaintext_size,
4931                              size_t *plaintext_length,
4932                              const uint8_t *tag,
4933                              size_t tag_length)
4934 {
4935     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4936 
4937     *plaintext_length = 0;
4938 
4939     status = psa_aead_final_checks(operation);
4940     if (status != PSA_SUCCESS) {
4941         goto exit;
4942     }
4943 
4944     if (operation->is_encrypt) {
4945         status = PSA_ERROR_BAD_STATE;
4946         goto exit;
4947     }
4948 
4949     status = psa_driver_wrapper_aead_verify(operation, plaintext,
4950                                             plaintext_size,
4951                                             plaintext_length,
4952                                             tag, tag_length);
4953 
4954 exit:
4955     psa_aead_abort(operation);
4956 
4957     return status;
4958 }
4959 
4960 /* Abort an AEAD operation. */
4961 psa_status_t psa_aead_abort(psa_aead_operation_t *operation)
4962 {
4963     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4964 
4965     if (operation->id == 0) {
4966         /* The object has (apparently) been initialized but it is not (yet)
4967          * in use. It's ok to call abort on such an object, and there's
4968          * nothing to do. */
4969         return PSA_SUCCESS;
4970     }
4971 
4972     status = psa_driver_wrapper_aead_abort(operation);
4973 
4974     memset(operation, 0, sizeof(*operation));
4975 
4976     return status;
4977 }
4978 
4979 /****************************************************************/
4980 /* Generators */
4981 /****************************************************************/
4982 
4983 #if defined(BUILTIN_ALG_ANY_HKDF) || \
4984     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
4985     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS) || \
4986     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS) || \
4987     defined(PSA_HAVE_SOFT_PBKDF2)
4988 #define AT_LEAST_ONE_BUILTIN_KDF
4989 #endif /* At least one builtin KDF */
4990 
4991 #if defined(BUILTIN_ALG_ANY_HKDF) || \
4992     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
4993     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
4994 static psa_status_t psa_key_derivation_start_hmac(
4995     psa_mac_operation_t *operation,
4996     psa_algorithm_t hash_alg,
4997     const uint8_t *hmac_key,
4998     size_t hmac_key_length)
4999 {
5000     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
5001     psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
5002     psa_set_key_type(&attributes, PSA_KEY_TYPE_HMAC);
5003     psa_set_key_bits(&attributes, PSA_BYTES_TO_BITS(hmac_key_length));
5004     psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_HASH);
5005 
5006     operation->is_sign = 1;
5007     operation->mac_size = PSA_HASH_LENGTH(hash_alg);
5008 
5009     status = psa_driver_wrapper_mac_sign_setup(operation,
5010                                                &attributes,
5011                                                hmac_key, hmac_key_length,
5012                                                PSA_ALG_HMAC(hash_alg));
5013 
5014     psa_reset_key_attributes(&attributes);
5015     return status;
5016 }
5017 #endif /* KDF algorithms reliant on HMAC */
5018 
5019 #define HKDF_STATE_INIT 0 /* no input yet */
5020 #define HKDF_STATE_STARTED 1 /* got salt */
5021 #define HKDF_STATE_KEYED 2 /* got key */
5022 #define HKDF_STATE_OUTPUT 3 /* output started */
5023 
5024 static psa_algorithm_t psa_key_derivation_get_kdf_alg(
5025     const psa_key_derivation_operation_t *operation)
5026 {
5027     if (PSA_ALG_IS_KEY_AGREEMENT(operation->alg)) {
5028         return PSA_ALG_KEY_AGREEMENT_GET_KDF(operation->alg);
5029     } else {
5030         return operation->alg;
5031     }
5032 }
5033 
5034 psa_status_t psa_key_derivation_abort(psa_key_derivation_operation_t *operation)
5035 {
5036     psa_status_t status = PSA_SUCCESS;
5037     psa_algorithm_t kdf_alg = psa_key_derivation_get_kdf_alg(operation);
5038     if (kdf_alg == 0) {
5039         /* The object has (apparently) been initialized but it is not
5040          * in use. It's ok to call abort on such an object, and there's
5041          * nothing to do. */
5042     } else
5043 #if defined(BUILTIN_ALG_ANY_HKDF)
5044     if (PSA_ALG_IS_ANY_HKDF(kdf_alg)) {
5045         mbedtls_free(operation->ctx.hkdf.info);
5046         status = psa_mac_abort(&operation->ctx.hkdf.hmac);
5047     } else
5048 #endif /* BUILTIN_ALG_ANY_HKDF */
5049 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
5050     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
5051     if (PSA_ALG_IS_TLS12_PRF(kdf_alg) ||
5052         /* TLS-1.2 PSK-to-MS KDF uses the same core as TLS-1.2 PRF */
5053         PSA_ALG_IS_TLS12_PSK_TO_MS(kdf_alg)) {
5054         if (operation->ctx.tls12_prf.secret != NULL) {
5055             mbedtls_zeroize_and_free(operation->ctx.tls12_prf.secret,
5056                                      operation->ctx.tls12_prf.secret_length);
5057         }
5058 
5059         if (operation->ctx.tls12_prf.seed != NULL) {
5060             mbedtls_zeroize_and_free(operation->ctx.tls12_prf.seed,
5061                                      operation->ctx.tls12_prf.seed_length);
5062         }
5063 
5064         if (operation->ctx.tls12_prf.label != NULL) {
5065             mbedtls_zeroize_and_free(operation->ctx.tls12_prf.label,
5066                                      operation->ctx.tls12_prf.label_length);
5067         }
5068 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
5069         if (operation->ctx.tls12_prf.other_secret != NULL) {
5070             mbedtls_zeroize_and_free(operation->ctx.tls12_prf.other_secret,
5071                                      operation->ctx.tls12_prf.other_secret_length);
5072         }
5073 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
5074         status = PSA_SUCCESS;
5075 
5076         /* We leave the fields Ai and output_block to be erased safely by the
5077          * mbedtls_platform_zeroize() in the end of this function. */
5078     } else
5079 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) ||
5080         * defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS) */
5081 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS)
5082     if (kdf_alg == PSA_ALG_TLS12_ECJPAKE_TO_PMS) {
5083         mbedtls_platform_zeroize(operation->ctx.tls12_ecjpake_to_pms.data,
5084                                  sizeof(operation->ctx.tls12_ecjpake_to_pms.data));
5085     } else
5086 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS) */
5087 #if defined(PSA_HAVE_SOFT_PBKDF2)
5088     if (PSA_ALG_IS_PBKDF2(kdf_alg)) {
5089         if (operation->ctx.pbkdf2.salt != NULL) {
5090             mbedtls_zeroize_and_free(operation->ctx.pbkdf2.salt,
5091                                      operation->ctx.pbkdf2.salt_length);
5092         }
5093 
5094         status = PSA_SUCCESS;
5095     } else
5096 #endif /* defined(PSA_HAVE_SOFT_PBKDF2) */
5097     {
5098         status = PSA_ERROR_BAD_STATE;
5099     }
5100     mbedtls_platform_zeroize(operation, sizeof(*operation));
5101     return status;
5102 }
5103 
5104 psa_status_t psa_key_derivation_get_capacity(const psa_key_derivation_operation_t *operation,
5105                                              size_t *capacity)
5106 {
5107     if (operation->alg == 0) {
5108         /* This is a blank key derivation operation. */
5109         return PSA_ERROR_BAD_STATE;
5110     }
5111 
5112     *capacity = operation->capacity;
5113     return PSA_SUCCESS;
5114 }
5115 
5116 psa_status_t psa_key_derivation_set_capacity(psa_key_derivation_operation_t *operation,
5117                                              size_t capacity)
5118 {
5119     if (operation->alg == 0) {
5120         return PSA_ERROR_BAD_STATE;
5121     }
5122     if (capacity > operation->capacity) {
5123         return PSA_ERROR_INVALID_ARGUMENT;
5124     }
5125     operation->capacity = capacity;
5126     return PSA_SUCCESS;
5127 }
5128 
5129 #if defined(BUILTIN_ALG_ANY_HKDF)
5130 /* Read some bytes from an HKDF-based operation. */
5131 static psa_status_t psa_key_derivation_hkdf_read(psa_hkdf_key_derivation_t *hkdf,
5132                                                  psa_algorithm_t kdf_alg,
5133                                                  uint8_t *output,
5134                                                  size_t output_length)
5135 {
5136     psa_algorithm_t hash_alg = PSA_ALG_HKDF_GET_HASH(kdf_alg);
5137     uint8_t hash_length = PSA_HASH_LENGTH(hash_alg);
5138     size_t hmac_output_length;
5139     psa_status_t status;
5140 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT)
5141     const uint8_t last_block = PSA_ALG_IS_HKDF_EXTRACT(kdf_alg) ? 0 : 0xff;
5142 #else
5143     const uint8_t last_block = 0xff;
5144 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT */
5145 
5146     if (hkdf->state < HKDF_STATE_KEYED ||
5147         (!hkdf->info_set
5148 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT)
5149          && !PSA_ALG_IS_HKDF_EXTRACT(kdf_alg)
5150 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT */
5151         )) {
5152         return PSA_ERROR_BAD_STATE;
5153     }
5154     hkdf->state = HKDF_STATE_OUTPUT;
5155 
5156     while (output_length != 0) {
5157         /* Copy what remains of the current block */
5158         uint8_t n = hash_length - hkdf->offset_in_block;
5159         if (n > output_length) {
5160             n = (uint8_t) output_length;
5161         }
5162         memcpy(output, hkdf->output_block + hkdf->offset_in_block, n);
5163         output += n;
5164         output_length -= n;
5165         hkdf->offset_in_block += n;
5166         if (output_length == 0) {
5167             break;
5168         }
5169         /* We can't be wanting more output after the last block, otherwise
5170          * the capacity check in psa_key_derivation_output_bytes() would have
5171          * prevented this call. It could happen only if the operation
5172          * object was corrupted or if this function is called directly
5173          * inside the library. */
5174         if (hkdf->block_number == last_block) {
5175             return PSA_ERROR_BAD_STATE;
5176         }
5177 
5178         /* We need a new block */
5179         ++hkdf->block_number;
5180         hkdf->offset_in_block = 0;
5181 
5182         status = psa_key_derivation_start_hmac(&hkdf->hmac,
5183                                                hash_alg,
5184                                                hkdf->prk,
5185                                                hash_length);
5186         if (status != PSA_SUCCESS) {
5187             return status;
5188         }
5189 
5190         if (hkdf->block_number != 1) {
5191             status = psa_mac_update(&hkdf->hmac,
5192                                     hkdf->output_block,
5193                                     hash_length);
5194             if (status != PSA_SUCCESS) {
5195                 return status;
5196             }
5197         }
5198         status = psa_mac_update(&hkdf->hmac,
5199                                 hkdf->info,
5200                                 hkdf->info_length);
5201         if (status != PSA_SUCCESS) {
5202             return status;
5203         }
5204         status = psa_mac_update(&hkdf->hmac,
5205                                 &hkdf->block_number, 1);
5206         if (status != PSA_SUCCESS) {
5207             return status;
5208         }
5209         status = psa_mac_sign_finish(&hkdf->hmac,
5210                                      hkdf->output_block,
5211                                      sizeof(hkdf->output_block),
5212                                      &hmac_output_length);
5213         if (status != PSA_SUCCESS) {
5214             return status;
5215         }
5216     }
5217 
5218     return PSA_SUCCESS;
5219 }
5220 #endif /* BUILTIN_ALG_ANY_HKDF */
5221 
5222 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
5223     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
5224 static psa_status_t psa_key_derivation_tls12_prf_generate_next_block(
5225     psa_tls12_prf_key_derivation_t *tls12_prf,
5226     psa_algorithm_t alg)
5227 {
5228     psa_algorithm_t hash_alg = PSA_ALG_HKDF_GET_HASH(alg);
5229     uint8_t hash_length = PSA_HASH_LENGTH(hash_alg);
5230     psa_mac_operation_t hmac = PSA_MAC_OPERATION_INIT;
5231     size_t hmac_output_length;
5232     psa_status_t status, cleanup_status;
5233 
5234     /* We can't be wanting more output after block 0xff, otherwise
5235      * the capacity check in psa_key_derivation_output_bytes() would have
5236      * prevented this call. It could happen only if the operation
5237      * object was corrupted or if this function is called directly
5238      * inside the library. */
5239     if (tls12_prf->block_number == 0xff) {
5240         return PSA_ERROR_CORRUPTION_DETECTED;
5241     }
5242 
5243     /* We need a new block */
5244     ++tls12_prf->block_number;
5245     tls12_prf->left_in_block = hash_length;
5246 
5247     /* Recall the definition of the TLS-1.2-PRF from RFC 5246:
5248      *
5249      * PRF(secret, label, seed) = P_<hash>(secret, label + seed)
5250      *
5251      * P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
5252      *                        HMAC_hash(secret, A(2) + seed) +
5253      *                        HMAC_hash(secret, A(3) + seed) + ...
5254      *
5255      * A(0) = seed
5256      * A(i) = HMAC_hash(secret, A(i-1))
5257      *
5258      * The `psa_tls12_prf_key_derivation` structure saves the block
5259      * `HMAC_hash(secret, A(i) + seed)` from which the output
5260      * is currently extracted as `output_block` and where i is
5261      * `block_number`.
5262      */
5263 
5264     status = psa_key_derivation_start_hmac(&hmac,
5265                                            hash_alg,
5266                                            tls12_prf->secret,
5267                                            tls12_prf->secret_length);
5268     if (status != PSA_SUCCESS) {
5269         goto cleanup;
5270     }
5271 
5272     /* Calculate A(i) where i = tls12_prf->block_number. */
5273     if (tls12_prf->block_number == 1) {
5274         /* A(1) = HMAC_hash(secret, A(0)), where A(0) = seed. (The RFC overloads
5275          * the variable seed and in this instance means it in the context of the
5276          * P_hash function, where seed = label + seed.) */
5277         status = psa_mac_update(&hmac,
5278                                 tls12_prf->label,
5279                                 tls12_prf->label_length);
5280         if (status != PSA_SUCCESS) {
5281             goto cleanup;
5282         }
5283         status = psa_mac_update(&hmac,
5284                                 tls12_prf->seed,
5285                                 tls12_prf->seed_length);
5286         if (status != PSA_SUCCESS) {
5287             goto cleanup;
5288         }
5289     } else {
5290         /* A(i) = HMAC_hash(secret, A(i-1)) */
5291         status = psa_mac_update(&hmac, tls12_prf->Ai, hash_length);
5292         if (status != PSA_SUCCESS) {
5293             goto cleanup;
5294         }
5295     }
5296 
5297     status = psa_mac_sign_finish(&hmac,
5298                                  tls12_prf->Ai, hash_length,
5299                                  &hmac_output_length);
5300     if (hmac_output_length != hash_length) {
5301         status = PSA_ERROR_CORRUPTION_DETECTED;
5302     }
5303     if (status != PSA_SUCCESS) {
5304         goto cleanup;
5305     }
5306 
5307     /* Calculate HMAC_hash(secret, A(i) + label + seed). */
5308     status = psa_key_derivation_start_hmac(&hmac,
5309                                            hash_alg,
5310                                            tls12_prf->secret,
5311                                            tls12_prf->secret_length);
5312     if (status != PSA_SUCCESS) {
5313         goto cleanup;
5314     }
5315     status = psa_mac_update(&hmac, tls12_prf->Ai, hash_length);
5316     if (status != PSA_SUCCESS) {
5317         goto cleanup;
5318     }
5319     status = psa_mac_update(&hmac, tls12_prf->label, tls12_prf->label_length);
5320     if (status != PSA_SUCCESS) {
5321         goto cleanup;
5322     }
5323     status = psa_mac_update(&hmac, tls12_prf->seed, tls12_prf->seed_length);
5324     if (status != PSA_SUCCESS) {
5325         goto cleanup;
5326     }
5327     status = psa_mac_sign_finish(&hmac,
5328                                  tls12_prf->output_block, hash_length,
5329                                  &hmac_output_length);
5330     if (status != PSA_SUCCESS) {
5331         goto cleanup;
5332     }
5333 
5334 
5335 cleanup:
5336     cleanup_status = psa_mac_abort(&hmac);
5337     if (status == PSA_SUCCESS && cleanup_status != PSA_SUCCESS) {
5338         status = cleanup_status;
5339     }
5340 
5341     return status;
5342 }
5343 
5344 static psa_status_t psa_key_derivation_tls12_prf_read(
5345     psa_tls12_prf_key_derivation_t *tls12_prf,
5346     psa_algorithm_t alg,
5347     uint8_t *output,
5348     size_t output_length)
5349 {
5350     psa_algorithm_t hash_alg = PSA_ALG_TLS12_PRF_GET_HASH(alg);
5351     uint8_t hash_length = PSA_HASH_LENGTH(hash_alg);
5352     psa_status_t status;
5353     uint8_t offset, length;
5354 
5355     switch (tls12_prf->state) {
5356         case PSA_TLS12_PRF_STATE_LABEL_SET:
5357             tls12_prf->state = PSA_TLS12_PRF_STATE_OUTPUT;
5358             break;
5359         case PSA_TLS12_PRF_STATE_OUTPUT:
5360             break;
5361         default:
5362             return PSA_ERROR_BAD_STATE;
5363     }
5364 
5365     while (output_length != 0) {
5366         /* Check if we have fully processed the current block. */
5367         if (tls12_prf->left_in_block == 0) {
5368             status = psa_key_derivation_tls12_prf_generate_next_block(tls12_prf,
5369                                                                       alg);
5370             if (status != PSA_SUCCESS) {
5371                 return status;
5372             }
5373 
5374             continue;
5375         }
5376 
5377         if (tls12_prf->left_in_block > output_length) {
5378             length = (uint8_t) output_length;
5379         } else {
5380             length = tls12_prf->left_in_block;
5381         }
5382 
5383         offset = hash_length - tls12_prf->left_in_block;
5384         memcpy(output, tls12_prf->output_block + offset, length);
5385         output += length;
5386         output_length -= length;
5387         tls12_prf->left_in_block -= length;
5388     }
5389 
5390     return PSA_SUCCESS;
5391 }
5392 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF ||
5393         * MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
5394 
5395 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS)
5396 static psa_status_t psa_key_derivation_tls12_ecjpake_to_pms_read(
5397     psa_tls12_ecjpake_to_pms_t *ecjpake,
5398     uint8_t *output,
5399     size_t output_length)
5400 {
5401     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
5402     size_t output_size = 0;
5403 
5404     if (output_length != 32) {
5405         return PSA_ERROR_INVALID_ARGUMENT;
5406     }
5407 
5408     status = psa_hash_compute(PSA_ALG_SHA_256, ecjpake->data,
5409                               PSA_TLS12_ECJPAKE_TO_PMS_DATA_SIZE, output, output_length,
5410                               &output_size);
5411     if (status != PSA_SUCCESS) {
5412         return status;
5413     }
5414 
5415     if (output_size != output_length) {
5416         return PSA_ERROR_GENERIC_ERROR;
5417     }
5418 
5419     return PSA_SUCCESS;
5420 }
5421 #endif
5422 
5423 #if defined(PSA_HAVE_SOFT_PBKDF2)
5424 static psa_status_t psa_key_derivation_pbkdf2_generate_block(
5425     psa_pbkdf2_key_derivation_t *pbkdf2,
5426     psa_algorithm_t prf_alg,
5427     uint8_t prf_output_length,
5428     psa_key_attributes_t *attributes)
5429 {
5430     psa_status_t status;
5431     psa_mac_operation_t mac_operation = PSA_MAC_OPERATION_INIT;
5432     size_t mac_output_length;
5433     uint8_t U_i[PSA_MAC_MAX_SIZE];
5434     uint8_t *U_accumulator = pbkdf2->output_block;
5435     uint64_t i;
5436     uint8_t block_counter[4];
5437 
5438     mac_operation.is_sign = 1;
5439     mac_operation.mac_size = prf_output_length;
5440     MBEDTLS_PUT_UINT32_BE(pbkdf2->block_number, block_counter, 0);
5441 
5442     status = psa_driver_wrapper_mac_sign_setup(&mac_operation,
5443                                                attributes,
5444                                                pbkdf2->password,
5445                                                pbkdf2->password_length,
5446                                                prf_alg);
5447     if (status != PSA_SUCCESS) {
5448         goto cleanup;
5449     }
5450     status = psa_mac_update(&mac_operation, pbkdf2->salt, pbkdf2->salt_length);
5451     if (status != PSA_SUCCESS) {
5452         goto cleanup;
5453     }
5454     status = psa_mac_update(&mac_operation, block_counter, sizeof(block_counter));
5455     if (status != PSA_SUCCESS) {
5456         goto cleanup;
5457     }
5458     status = psa_mac_sign_finish(&mac_operation, U_i, sizeof(U_i),
5459                                  &mac_output_length);
5460     if (status != PSA_SUCCESS) {
5461         goto cleanup;
5462     }
5463 
5464     if (mac_output_length != prf_output_length) {
5465         status = PSA_ERROR_CORRUPTION_DETECTED;
5466         goto cleanup;
5467     }
5468 
5469     memcpy(U_accumulator, U_i, prf_output_length);
5470 
5471     for (i = 1; i < pbkdf2->input_cost; i++) {
5472         /* We are passing prf_output_length as mac_size because the driver
5473          * function directly sets mac_output_length as mac_size upon success.
5474          * See https://github.com/Mbed-TLS/mbedtls/issues/7801 */
5475         status = psa_driver_wrapper_mac_compute(attributes,
5476                                                 pbkdf2->password,
5477                                                 pbkdf2->password_length,
5478                                                 prf_alg, U_i, prf_output_length,
5479                                                 U_i, prf_output_length,
5480                                                 &mac_output_length);
5481         if (status != PSA_SUCCESS) {
5482             goto cleanup;
5483         }
5484 
5485         mbedtls_xor(U_accumulator, U_accumulator, U_i, prf_output_length);
5486     }
5487 
5488 cleanup:
5489     /* Zeroise buffers to clear sensitive data from memory. */
5490     mbedtls_platform_zeroize(U_i, PSA_MAC_MAX_SIZE);
5491     return status;
5492 }
5493 
5494 static psa_status_t psa_key_derivation_pbkdf2_read(
5495     psa_pbkdf2_key_derivation_t *pbkdf2,
5496     psa_algorithm_t kdf_alg,
5497     uint8_t *output,
5498     size_t output_length)
5499 {
5500     psa_status_t status;
5501     psa_algorithm_t prf_alg;
5502     uint8_t prf_output_length;
5503     psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
5504     psa_set_key_bits(&attributes, PSA_BYTES_TO_BITS(pbkdf2->password_length));
5505     psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_MESSAGE);
5506 
5507     if (PSA_ALG_IS_PBKDF2_HMAC(kdf_alg)) {
5508         prf_alg = PSA_ALG_HMAC(PSA_ALG_PBKDF2_HMAC_GET_HASH(kdf_alg));
5509         prf_output_length = PSA_HASH_LENGTH(prf_alg);
5510         psa_set_key_type(&attributes, PSA_KEY_TYPE_HMAC);
5511     } else if (kdf_alg == PSA_ALG_PBKDF2_AES_CMAC_PRF_128) {
5512         prf_alg = PSA_ALG_CMAC;
5513         prf_output_length = PSA_MAC_LENGTH(PSA_KEY_TYPE_AES, 128U, PSA_ALG_CMAC);
5514         psa_set_key_type(&attributes, PSA_KEY_TYPE_AES);
5515     } else {
5516         return PSA_ERROR_INVALID_ARGUMENT;
5517     }
5518 
5519     switch (pbkdf2->state) {
5520         case PSA_PBKDF2_STATE_PASSWORD_SET:
5521             /* Initially we need a new block so bytes_used is equal to block size*/
5522             pbkdf2->bytes_used = prf_output_length;
5523             pbkdf2->state = PSA_PBKDF2_STATE_OUTPUT;
5524             break;
5525         case PSA_PBKDF2_STATE_OUTPUT:
5526             break;
5527         default:
5528             return PSA_ERROR_BAD_STATE;
5529     }
5530 
5531     while (output_length != 0) {
5532         uint8_t n = prf_output_length - pbkdf2->bytes_used;
5533         if (n > output_length) {
5534             n = (uint8_t) output_length;
5535         }
5536         memcpy(output, pbkdf2->output_block + pbkdf2->bytes_used, n);
5537         output += n;
5538         output_length -= n;
5539         pbkdf2->bytes_used += n;
5540 
5541         if (output_length == 0) {
5542             break;
5543         }
5544 
5545         /* We need a new block */
5546         pbkdf2->bytes_used = 0;
5547         pbkdf2->block_number++;
5548 
5549         status = psa_key_derivation_pbkdf2_generate_block(pbkdf2, prf_alg,
5550                                                           prf_output_length,
5551                                                           &attributes);
5552         if (status != PSA_SUCCESS) {
5553             return status;
5554         }
5555     }
5556 
5557     return PSA_SUCCESS;
5558 }
5559 #endif /* PSA_HAVE_SOFT_PBKDF2 */
5560 
5561 psa_status_t psa_key_derivation_output_bytes(
5562     psa_key_derivation_operation_t *operation,
5563     uint8_t *output,
5564     size_t output_length)
5565 {
5566     psa_status_t status;
5567     psa_algorithm_t kdf_alg = psa_key_derivation_get_kdf_alg(operation);
5568 
5569     if (operation->alg == 0) {
5570         /* This is a blank operation. */
5571         return PSA_ERROR_BAD_STATE;
5572     }
5573 
5574     if (output_length > operation->capacity) {
5575         operation->capacity = 0;
5576         /* Go through the error path to wipe all confidential data now
5577          * that the operation object is useless. */
5578         status = PSA_ERROR_INSUFFICIENT_DATA;
5579         goto exit;
5580     }
5581     if (output_length == 0 && operation->capacity == 0) {
5582         /* Edge case: this is a finished operation, and 0 bytes
5583          * were requested. The right error in this case could
5584          * be either INSUFFICIENT_CAPACITY or BAD_STATE. Return
5585          * INSUFFICIENT_CAPACITY, which is right for a finished
5586          * operation, for consistency with the case when
5587          * output_length > 0. */
5588         return PSA_ERROR_INSUFFICIENT_DATA;
5589     }
5590     operation->capacity -= output_length;
5591 
5592 #if defined(BUILTIN_ALG_ANY_HKDF)
5593     if (PSA_ALG_IS_ANY_HKDF(kdf_alg)) {
5594         status = psa_key_derivation_hkdf_read(&operation->ctx.hkdf, kdf_alg,
5595                                               output, output_length);
5596     } else
5597 #endif /* BUILTIN_ALG_ANY_HKDF */
5598 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
5599     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
5600     if (PSA_ALG_IS_TLS12_PRF(kdf_alg) ||
5601         PSA_ALG_IS_TLS12_PSK_TO_MS(kdf_alg)) {
5602         status = psa_key_derivation_tls12_prf_read(&operation->ctx.tls12_prf,
5603                                                    kdf_alg, output,
5604                                                    output_length);
5605     } else
5606 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF ||
5607         * MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
5608 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS)
5609     if (kdf_alg == PSA_ALG_TLS12_ECJPAKE_TO_PMS) {
5610         status = psa_key_derivation_tls12_ecjpake_to_pms_read(
5611             &operation->ctx.tls12_ecjpake_to_pms, output, output_length);
5612     } else
5613 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS */
5614 #if defined(PSA_HAVE_SOFT_PBKDF2)
5615     if (PSA_ALG_IS_PBKDF2(kdf_alg)) {
5616         status = psa_key_derivation_pbkdf2_read(&operation->ctx.pbkdf2, kdf_alg,
5617                                                 output, output_length);
5618     } else
5619 #endif /* PSA_HAVE_SOFT_PBKDF2 */
5620 
5621     {
5622         (void) kdf_alg;
5623         return PSA_ERROR_BAD_STATE;
5624     }
5625 
5626 exit:
5627     if (status != PSA_SUCCESS) {
5628         /* Preserve the algorithm upon errors, but clear all sensitive state.
5629          * This allows us to differentiate between exhausted operations and
5630          * blank operations, so we can return PSA_ERROR_BAD_STATE on blank
5631          * operations. */
5632         psa_algorithm_t alg = operation->alg;
5633         psa_key_derivation_abort(operation);
5634         operation->alg = alg;
5635         memset(output, '!', output_length);
5636     }
5637     return status;
5638 }
5639 
5640 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES)
5641 static void psa_des_set_key_parity(uint8_t *data, size_t data_size)
5642 {
5643     if (data_size >= 8) {
5644         mbedtls_des_key_set_parity(data);
5645     }
5646     if (data_size >= 16) {
5647         mbedtls_des_key_set_parity(data + 8);
5648     }
5649     if (data_size >= 24) {
5650         mbedtls_des_key_set_parity(data + 16);
5651     }
5652 }
5653 #endif /* MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES */
5654 
5655 /*
5656  * ECC keys on a Weierstrass elliptic curve require the generation
5657  * of a private key which is an integer
5658  * in the range [1, N - 1], where N is the boundary of the private key domain:
5659  * N is the prime p for Diffie-Hellman, or the order of the
5660  * curve’s base point for ECC.
5661  *
5662  * Let m be the bit size of N, such that 2^m > N >= 2^(m-1).
5663  * This function generates the private key using the following process:
5664  *
5665  * 1. Draw a byte string of length ceiling(m/8) bytes.
5666  * 2. If m is not a multiple of 8, set the most significant
5667  *    (8 * ceiling(m/8) - m) bits of the first byte in the string to zero.
5668  * 3. Convert the string to integer k by decoding it as a big-endian byte string.
5669  * 4. If k > N - 2, discard the result and return to step 1.
5670  * 5. Output k + 1 as the private key.
5671  *
5672  * This method allows compliance to NIST standards, specifically the methods titled
5673  * Key-Pair Generation by Testing Candidates in the following publications:
5674  * - NIST Special Publication 800-56A: Recommendation for Pair-Wise Key-Establishment
5675  *   Schemes Using Discrete Logarithm Cryptography [SP800-56A] §5.6.1.1.4 for
5676  *   Diffie-Hellman keys.
5677  *
5678  * - [SP800-56A] §5.6.1.2.2 or FIPS Publication 186-4: Digital Signature
5679  *   Standard (DSS) [FIPS186-4] §B.4.2 for elliptic curve keys.
5680  *
5681  * Note: Function allocates memory for *data buffer, so given *data should be
5682  *       always NULL.
5683  */
5684 #if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE)
5685 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_DERIVE)
5686 static psa_status_t psa_generate_derived_ecc_key_weierstrass_helper(
5687     psa_key_slot_t *slot,
5688     size_t bits,
5689     psa_key_derivation_operation_t *operation,
5690     uint8_t **data
5691     )
5692 {
5693     unsigned key_out_of_range = 1;
5694     mbedtls_mpi k;
5695     mbedtls_mpi diff_N_2;
5696     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
5697     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
5698     size_t m;
5699     size_t m_bytes;
5700 
5701     mbedtls_mpi_init(&k);
5702     mbedtls_mpi_init(&diff_N_2);
5703 
5704     psa_ecc_family_t curve = PSA_KEY_TYPE_ECC_GET_FAMILY(
5705         slot->attr.type);
5706     mbedtls_ecp_group_id grp_id =
5707         mbedtls_ecc_group_of_psa(curve, bits, 0);
5708 
5709     if (grp_id == MBEDTLS_ECP_DP_NONE) {
5710         ret = MBEDTLS_ERR_ASN1_INVALID_DATA;
5711         goto cleanup;
5712     }
5713 
5714     mbedtls_ecp_group ecp_group;
5715     mbedtls_ecp_group_init(&ecp_group);
5716 
5717     MBEDTLS_MPI_CHK(mbedtls_ecp_group_load(&ecp_group, grp_id));
5718 
5719     /* N is the boundary of the private key domain (ecp_group.N). */
5720     /* Let m be the bit size of N. */
5721     m = ecp_group.nbits;
5722 
5723     m_bytes = PSA_BITS_TO_BYTES(m);
5724 
5725     /* Calculate N - 2 - it will be needed later. */
5726     MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&diff_N_2, &ecp_group.N, 2));
5727 
5728     /* Note: This function is always called with *data == NULL and it
5729      * allocates memory for the data buffer. */
5730     *data = mbedtls_calloc(1, m_bytes);
5731     if (*data == NULL) {
5732         ret = MBEDTLS_ERR_ASN1_ALLOC_FAILED;
5733         goto cleanup;
5734     }
5735 
5736     while (key_out_of_range) {
5737         /* 1. Draw a byte string of length ceiling(m/8) bytes. */
5738         if ((status = psa_key_derivation_output_bytes(operation, *data, m_bytes)) != 0) {
5739             goto cleanup;
5740         }
5741 
5742         /* 2. If m is not a multiple of 8 */
5743         if (m % 8 != 0) {
5744             /* Set the most significant
5745              * (8 * ceiling(m/8) - m) bits of the first byte in
5746              * the string to zero.
5747              */
5748             uint8_t clear_bit_mask = (1 << (m % 8)) - 1;
5749             (*data)[0] &= clear_bit_mask;
5750         }
5751 
5752         /* 3. Convert the string to integer k by decoding it as a
5753          *    big-endian byte string.
5754          */
5755         MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&k, *data, m_bytes));
5756 
5757         /* 4. If k > N - 2, discard the result and return to step 1.
5758          *    Result of comparison is returned. When it indicates error
5759          *    then this function is called again.
5760          */
5761         MBEDTLS_MPI_CHK(mbedtls_mpi_lt_mpi_ct(&diff_N_2, &k, &key_out_of_range));
5762     }
5763 
5764     /* 5. Output k + 1 as the private key. */
5765     MBEDTLS_MPI_CHK(mbedtls_mpi_add_int(&k, &k, 1));
5766     MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&k, *data, m_bytes));
5767 cleanup:
5768     if (ret != 0) {
5769         status = mbedtls_to_psa_error(ret);
5770     }
5771     if (status != PSA_SUCCESS) {
5772         mbedtls_free(*data);
5773         *data = NULL;
5774     }
5775     mbedtls_mpi_free(&k);
5776     mbedtls_mpi_free(&diff_N_2);
5777     return status;
5778 }
5779 
5780 /* ECC keys on a Montgomery elliptic curve draws a byte string whose length
5781  * is determined by the curve, and sets the mandatory bits accordingly. That is:
5782  *
5783  * - Curve25519 (PSA_ECC_FAMILY_MONTGOMERY, 255 bits):
5784  *   draw a 32-byte string and process it as specified in
5785  *   Elliptic Curves for Security [RFC7748] §5.
5786  *
5787  * - Curve448 (PSA_ECC_FAMILY_MONTGOMERY, 448 bits):
5788  *   draw a 56-byte string and process it as specified in [RFC7748] §5.
5789  *
5790  * Note: Function allocates memory for *data buffer, so given *data should be
5791  *       always NULL.
5792  */
5793 
5794 static psa_status_t psa_generate_derived_ecc_key_montgomery_helper(
5795     size_t bits,
5796     psa_key_derivation_operation_t *operation,
5797     uint8_t **data
5798     )
5799 {
5800     size_t output_length;
5801     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
5802 
5803     switch (bits) {
5804         case 255:
5805             output_length = 32;
5806             break;
5807         case 448:
5808             output_length = 56;
5809             break;
5810         default:
5811             return PSA_ERROR_INVALID_ARGUMENT;
5812             break;
5813     }
5814 
5815     *data = mbedtls_calloc(1, output_length);
5816 
5817     if (*data == NULL) {
5818         return PSA_ERROR_INSUFFICIENT_MEMORY;
5819     }
5820 
5821     status = psa_key_derivation_output_bytes(operation, *data, output_length);
5822 
5823     if (status != PSA_SUCCESS) {
5824         return status;
5825     }
5826 
5827     switch (bits) {
5828         case 255:
5829             (*data)[0] &= 248;
5830             (*data)[31] &= 127;
5831             (*data)[31] |= 64;
5832             break;
5833         case 448:
5834             (*data)[0] &= 252;
5835             (*data)[55] |= 128;
5836             break;
5837         default:
5838             return PSA_ERROR_CORRUPTION_DETECTED;
5839             break;
5840     }
5841 
5842     return status;
5843 }
5844 #else /* MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_DERIVE */
5845 static psa_status_t psa_generate_derived_ecc_key_weierstrass_helper(
5846     psa_key_slot_t *slot, size_t bits,
5847     psa_key_derivation_operation_t *operation, uint8_t **data)
5848 {
5849     (void) slot;
5850     (void) bits;
5851     (void) operation;
5852     (void) data;
5853     return PSA_ERROR_NOT_SUPPORTED;
5854 }
5855 
5856 static psa_status_t psa_generate_derived_ecc_key_montgomery_helper(
5857     size_t bits, psa_key_derivation_operation_t *operation, uint8_t **data)
5858 {
5859     (void) bits;
5860     (void) operation;
5861     (void) data;
5862     return PSA_ERROR_NOT_SUPPORTED;
5863 }
5864 #endif /* MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_DERIVE */
5865 #endif /* PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE */
5866 
5867 static psa_status_t psa_generate_derived_key_internal(
5868     psa_key_slot_t *slot,
5869     size_t bits,
5870     psa_key_derivation_operation_t *operation)
5871 {
5872     uint8_t *data = NULL;
5873     size_t bytes = PSA_BITS_TO_BYTES(bits);
5874     size_t storage_size = bytes;
5875     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
5876     psa_key_attributes_t attributes;
5877 
5878     if (PSA_KEY_TYPE_IS_PUBLIC_KEY(slot->attr.type)) {
5879         return PSA_ERROR_INVALID_ARGUMENT;
5880     }
5881 
5882 #if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE) || \
5883     defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_DERIVE)
5884     if (PSA_KEY_TYPE_IS_ECC(slot->attr.type)) {
5885         psa_ecc_family_t curve = PSA_KEY_TYPE_ECC_GET_FAMILY(slot->attr.type);
5886         if (PSA_ECC_FAMILY_IS_WEIERSTRASS(curve)) {
5887             /* Weierstrass elliptic curve */
5888             status = psa_generate_derived_ecc_key_weierstrass_helper(slot, bits, operation, &data);
5889             if (status != PSA_SUCCESS) {
5890                 goto exit;
5891             }
5892         } else {
5893             /* Montgomery elliptic curve */
5894             status = psa_generate_derived_ecc_key_montgomery_helper(bits, operation, &data);
5895             if (status != PSA_SUCCESS) {
5896                 goto exit;
5897             }
5898         }
5899     } else
5900 #endif /* defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE) ||
5901           defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_DERIVE) */
5902     if (key_type_is_raw_bytes(slot->attr.type)) {
5903         if (bits % 8 != 0) {
5904             return PSA_ERROR_INVALID_ARGUMENT;
5905         }
5906         data = mbedtls_calloc(1, bytes);
5907         if (data == NULL) {
5908             return PSA_ERROR_INSUFFICIENT_MEMORY;
5909         }
5910 
5911         status = psa_key_derivation_output_bytes(operation, data, bytes);
5912         if (status != PSA_SUCCESS) {
5913             goto exit;
5914         }
5915 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES)
5916         if (slot->attr.type == PSA_KEY_TYPE_DES) {
5917             psa_des_set_key_parity(data, bytes);
5918         }
5919 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES) */
5920     } else {
5921         return PSA_ERROR_NOT_SUPPORTED;
5922     }
5923 
5924     slot->attr.bits = (psa_key_bits_t) bits;
5925     attributes = (psa_key_attributes_t) {
5926         .core = slot->attr
5927     };
5928 
5929     if (psa_key_lifetime_is_external(attributes.core.lifetime)) {
5930         status = psa_driver_wrapper_get_key_buffer_size(&attributes,
5931                                                         &storage_size);
5932         if (status != PSA_SUCCESS) {
5933             goto exit;
5934         }
5935     }
5936     status = psa_allocate_buffer_to_slot(slot, storage_size);
5937     if (status != PSA_SUCCESS) {
5938         goto exit;
5939     }
5940 
5941     status = psa_driver_wrapper_import_key(&attributes,
5942                                            data, bytes,
5943                                            slot->key.data,
5944                                            slot->key.bytes,
5945                                            &slot->key.bytes, &bits);
5946     if (bits != slot->attr.bits) {
5947         status = PSA_ERROR_INVALID_ARGUMENT;
5948     }
5949 
5950 exit:
5951     mbedtls_free(data);
5952     return status;
5953 }
5954 
5955 psa_status_t psa_key_derivation_output_key(const psa_key_attributes_t *attributes,
5956                                            psa_key_derivation_operation_t *operation,
5957                                            mbedtls_svc_key_id_t *key)
5958 {
5959     psa_status_t status;
5960     psa_key_slot_t *slot = NULL;
5961     psa_se_drv_table_entry_t *driver = NULL;
5962 
5963     *key = MBEDTLS_SVC_KEY_ID_INIT;
5964 
5965     /* Reject any attempt to create a zero-length key so that we don't
5966      * risk tripping up later, e.g. on a malloc(0) that returns NULL. */
5967     if (psa_get_key_bits(attributes) == 0) {
5968         return PSA_ERROR_INVALID_ARGUMENT;
5969     }
5970 
5971     if (operation->alg == PSA_ALG_NONE) {
5972         return PSA_ERROR_BAD_STATE;
5973     }
5974 
5975     if (!operation->can_output_key) {
5976         return PSA_ERROR_NOT_PERMITTED;
5977     }
5978 
5979     status = psa_start_key_creation(PSA_KEY_CREATION_DERIVE, attributes,
5980                                     &slot, &driver);
5981 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
5982     if (driver != NULL) {
5983         /* Deriving a key in a secure element is not implemented yet. */
5984         status = PSA_ERROR_NOT_SUPPORTED;
5985     }
5986 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
5987     if (status == PSA_SUCCESS) {
5988         status = psa_generate_derived_key_internal(slot,
5989                                                    attributes->core.bits,
5990                                                    operation);
5991     }
5992     if (status == PSA_SUCCESS) {
5993         status = psa_finish_key_creation(slot, driver, key);
5994     }
5995     if (status != PSA_SUCCESS) {
5996         psa_fail_key_creation(slot, driver);
5997     }
5998 
5999     return status;
6000 }
6001 
6002 
6003 
6004 /****************************************************************/
6005 /* Key derivation */
6006 /****************************************************************/
6007 
6008 #if defined(AT_LEAST_ONE_BUILTIN_KDF)
6009 static int is_kdf_alg_supported(psa_algorithm_t kdf_alg)
6010 {
6011 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF)
6012     if (PSA_ALG_IS_HKDF(kdf_alg)) {
6013         return 1;
6014     }
6015 #endif
6016 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT)
6017     if (PSA_ALG_IS_HKDF_EXTRACT(kdf_alg)) {
6018         return 1;
6019     }
6020 #endif
6021 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXPAND)
6022     if (PSA_ALG_IS_HKDF_EXPAND(kdf_alg)) {
6023         return 1;
6024     }
6025 #endif
6026 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF)
6027     if (PSA_ALG_IS_TLS12_PRF(kdf_alg)) {
6028         return 1;
6029     }
6030 #endif
6031 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
6032     if (PSA_ALG_IS_TLS12_PSK_TO_MS(kdf_alg)) {
6033         return 1;
6034     }
6035 #endif
6036 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS)
6037     if (kdf_alg == PSA_ALG_TLS12_ECJPAKE_TO_PMS) {
6038         return 1;
6039     }
6040 #endif
6041 #if defined(MBEDTLS_PSA_BUILTIN_ALG_PBKDF2_HMAC)
6042     if (PSA_ALG_IS_PBKDF2_HMAC(kdf_alg)) {
6043         return 1;
6044     }
6045 #endif
6046 #if defined(MBEDTLS_PSA_BUILTIN_ALG_PBKDF2_AES_CMAC_PRF_128)
6047     if (kdf_alg == PSA_ALG_PBKDF2_AES_CMAC_PRF_128) {
6048         return 1;
6049     }
6050 #endif
6051     return 0;
6052 }
6053 
6054 static psa_status_t psa_hash_try_support(psa_algorithm_t alg)
6055 {
6056     psa_hash_operation_t operation = PSA_HASH_OPERATION_INIT;
6057     psa_status_t status = psa_hash_setup(&operation, alg);
6058     psa_hash_abort(&operation);
6059     return status;
6060 }
6061 
6062 static psa_status_t psa_key_derivation_setup_kdf(
6063     psa_key_derivation_operation_t *operation,
6064     psa_algorithm_t kdf_alg)
6065 {
6066     /* Make sure that operation->ctx is properly zero-initialised. (Macro
6067      * initialisers for this union leave some bytes unspecified.) */
6068     memset(&operation->ctx, 0, sizeof(operation->ctx));
6069 
6070     /* Make sure that kdf_alg is a supported key derivation algorithm. */
6071     if (!is_kdf_alg_supported(kdf_alg)) {
6072         return PSA_ERROR_NOT_SUPPORTED;
6073     }
6074 
6075     /* All currently supported key derivation algorithms (apart from
6076      * ecjpake to pms and pbkdf2_aes_cmac_128) are based on a hash algorithm. */
6077     psa_algorithm_t hash_alg = PSA_ALG_HKDF_GET_HASH(kdf_alg);
6078     size_t hash_size = PSA_HASH_LENGTH(hash_alg);
6079     if (kdf_alg == PSA_ALG_TLS12_ECJPAKE_TO_PMS) {
6080         hash_size = PSA_HASH_LENGTH(PSA_ALG_SHA_256);
6081     } else if (kdf_alg == PSA_ALG_PBKDF2_AES_CMAC_PRF_128) {
6082         hash_size = PSA_MAC_LENGTH(PSA_KEY_TYPE_AES, 128U, PSA_ALG_CMAC);
6083     } else {
6084         if (hash_size == 0) {
6085             return PSA_ERROR_NOT_SUPPORTED;
6086         }
6087 
6088         /* Make sure that hash_alg is a supported hash algorithm. Otherwise
6089          * we might fail later, which is somewhat unfriendly and potentially
6090          * risk-prone. */
6091         psa_status_t status = psa_hash_try_support(hash_alg);
6092         if (status != PSA_SUCCESS) {
6093             return status;
6094         }
6095     }
6096 
6097     if ((PSA_ALG_IS_TLS12_PRF(kdf_alg) ||
6098          PSA_ALG_IS_TLS12_PSK_TO_MS(kdf_alg)) &&
6099         !(hash_alg == PSA_ALG_SHA_256 || hash_alg == PSA_ALG_SHA_384)) {
6100         return PSA_ERROR_NOT_SUPPORTED;
6101     }
6102 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT) || \
6103     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS)
6104     if (PSA_ALG_IS_HKDF_EXTRACT(kdf_alg) ||
6105         (kdf_alg == PSA_ALG_TLS12_ECJPAKE_TO_PMS)) {
6106         operation->capacity = hash_size;
6107     } else
6108 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT ||
6109           MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS */
6110     operation->capacity = 255 * hash_size;
6111     return PSA_SUCCESS;
6112 }
6113 
6114 static psa_status_t psa_key_agreement_try_support(psa_algorithm_t alg)
6115 {
6116 #if defined(PSA_WANT_ALG_ECDH)
6117     if (alg == PSA_ALG_ECDH) {
6118         return PSA_SUCCESS;
6119     }
6120 #endif
6121 #if defined(PSA_WANT_ALG_FFDH)
6122     if (alg == PSA_ALG_FFDH) {
6123         return PSA_SUCCESS;
6124     }
6125 #endif
6126     (void) alg;
6127     return PSA_ERROR_NOT_SUPPORTED;
6128 }
6129 
6130 static int psa_key_derivation_allows_free_form_secret_input(
6131     psa_algorithm_t kdf_alg)
6132 {
6133 #if defined(PSA_WANT_ALG_TLS12_ECJPAKE_TO_PMS)
6134     if (kdf_alg == PSA_ALG_TLS12_ECJPAKE_TO_PMS) {
6135         return 0;
6136     }
6137 #endif
6138     (void) kdf_alg;
6139     return 1;
6140 }
6141 #endif /* AT_LEAST_ONE_BUILTIN_KDF */
6142 
6143 psa_status_t psa_key_derivation_setup(psa_key_derivation_operation_t *operation,
6144                                       psa_algorithm_t alg)
6145 {
6146     psa_status_t status;
6147 
6148     if (operation->alg != 0) {
6149         return PSA_ERROR_BAD_STATE;
6150     }
6151 
6152     if (PSA_ALG_IS_RAW_KEY_AGREEMENT(alg)) {
6153         return PSA_ERROR_INVALID_ARGUMENT;
6154     } else if (PSA_ALG_IS_KEY_AGREEMENT(alg)) {
6155 #if defined(AT_LEAST_ONE_BUILTIN_KDF)
6156         psa_algorithm_t kdf_alg = PSA_ALG_KEY_AGREEMENT_GET_KDF(alg);
6157         psa_algorithm_t ka_alg = PSA_ALG_KEY_AGREEMENT_GET_BASE(alg);
6158         status = psa_key_agreement_try_support(ka_alg);
6159         if (status != PSA_SUCCESS) {
6160             return status;
6161         }
6162         if (!psa_key_derivation_allows_free_form_secret_input(kdf_alg)) {
6163             return PSA_ERROR_INVALID_ARGUMENT;
6164         }
6165         status = psa_key_derivation_setup_kdf(operation, kdf_alg);
6166 #else
6167         return PSA_ERROR_NOT_SUPPORTED;
6168 #endif /* AT_LEAST_ONE_BUILTIN_KDF */
6169     } else if (PSA_ALG_IS_KEY_DERIVATION(alg)) {
6170 #if defined(AT_LEAST_ONE_BUILTIN_KDF)
6171         status = psa_key_derivation_setup_kdf(operation, alg);
6172 #else
6173         return PSA_ERROR_NOT_SUPPORTED;
6174 #endif /* AT_LEAST_ONE_BUILTIN_KDF */
6175     } else {
6176         return PSA_ERROR_INVALID_ARGUMENT;
6177     }
6178 
6179     if (status == PSA_SUCCESS) {
6180         operation->alg = alg;
6181     }
6182     return status;
6183 }
6184 
6185 #if defined(BUILTIN_ALG_ANY_HKDF)
6186 static psa_status_t psa_hkdf_input(psa_hkdf_key_derivation_t *hkdf,
6187                                    psa_algorithm_t kdf_alg,
6188                                    psa_key_derivation_step_t step,
6189                                    const uint8_t *data,
6190                                    size_t data_length)
6191 {
6192     psa_algorithm_t hash_alg = PSA_ALG_HKDF_GET_HASH(kdf_alg);
6193     psa_status_t status;
6194     switch (step) {
6195         case PSA_KEY_DERIVATION_INPUT_SALT:
6196 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXPAND)
6197             if (PSA_ALG_IS_HKDF_EXPAND(kdf_alg)) {
6198                 return PSA_ERROR_INVALID_ARGUMENT;
6199             }
6200 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXPAND */
6201             if (hkdf->state != HKDF_STATE_INIT) {
6202                 return PSA_ERROR_BAD_STATE;
6203             } else {
6204                 status = psa_key_derivation_start_hmac(&hkdf->hmac,
6205                                                        hash_alg,
6206                                                        data, data_length);
6207                 if (status != PSA_SUCCESS) {
6208                     return status;
6209                 }
6210                 hkdf->state = HKDF_STATE_STARTED;
6211                 return PSA_SUCCESS;
6212             }
6213         case PSA_KEY_DERIVATION_INPUT_SECRET:
6214 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXPAND)
6215             if (PSA_ALG_IS_HKDF_EXPAND(kdf_alg)) {
6216                 /* We shouldn't be in different state as HKDF_EXPAND only allows
6217                  * two inputs: SECRET (this case) and INFO which does not modify
6218                  * the state. It could happen only if the hkdf
6219                  * object was corrupted. */
6220                 if (hkdf->state != HKDF_STATE_INIT) {
6221                     return PSA_ERROR_BAD_STATE;
6222                 }
6223 
6224                 /* Allow only input that fits expected prk size */
6225                 if (data_length != PSA_HASH_LENGTH(hash_alg)) {
6226                     return PSA_ERROR_INVALID_ARGUMENT;
6227                 }
6228 
6229                 memcpy(hkdf->prk, data, data_length);
6230             } else
6231 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXPAND */
6232             {
6233                 /* HKDF: If no salt was provided, use an empty salt.
6234                  * HKDF-EXTRACT: salt is mandatory. */
6235                 if (hkdf->state == HKDF_STATE_INIT) {
6236 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT)
6237                     if (PSA_ALG_IS_HKDF_EXTRACT(kdf_alg)) {
6238                         return PSA_ERROR_BAD_STATE;
6239                     }
6240 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT */
6241                     status = psa_key_derivation_start_hmac(&hkdf->hmac,
6242                                                            hash_alg,
6243                                                            NULL, 0);
6244                     if (status != PSA_SUCCESS) {
6245                         return status;
6246                     }
6247                     hkdf->state = HKDF_STATE_STARTED;
6248                 }
6249                 if (hkdf->state != HKDF_STATE_STARTED) {
6250                     return PSA_ERROR_BAD_STATE;
6251                 }
6252                 status = psa_mac_update(&hkdf->hmac,
6253                                         data, data_length);
6254                 if (status != PSA_SUCCESS) {
6255                     return status;
6256                 }
6257                 status = psa_mac_sign_finish(&hkdf->hmac,
6258                                              hkdf->prk,
6259                                              sizeof(hkdf->prk),
6260                                              &data_length);
6261                 if (status != PSA_SUCCESS) {
6262                     return status;
6263                 }
6264             }
6265 
6266             hkdf->state = HKDF_STATE_KEYED;
6267             hkdf->block_number = 0;
6268 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT)
6269             if (PSA_ALG_IS_HKDF_EXTRACT(kdf_alg)) {
6270                 /* The only block of output is the PRK. */
6271                 memcpy(hkdf->output_block, hkdf->prk, PSA_HASH_LENGTH(hash_alg));
6272                 hkdf->offset_in_block = 0;
6273             } else
6274 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT */
6275             {
6276                 /* Block 0 is empty, and the next block will be
6277                  * generated by psa_key_derivation_hkdf_read(). */
6278                 hkdf->offset_in_block = PSA_HASH_LENGTH(hash_alg);
6279             }
6280 
6281             return PSA_SUCCESS;
6282         case PSA_KEY_DERIVATION_INPUT_INFO:
6283 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT)
6284             if (PSA_ALG_IS_HKDF_EXTRACT(kdf_alg)) {
6285                 return PSA_ERROR_INVALID_ARGUMENT;
6286             }
6287 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT */
6288 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXPAND)
6289             if (PSA_ALG_IS_HKDF_EXPAND(kdf_alg) &&
6290                 hkdf->state == HKDF_STATE_INIT) {
6291                 return PSA_ERROR_BAD_STATE;
6292             }
6293 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT */
6294             if (hkdf->state == HKDF_STATE_OUTPUT) {
6295                 return PSA_ERROR_BAD_STATE;
6296             }
6297             if (hkdf->info_set) {
6298                 return PSA_ERROR_BAD_STATE;
6299             }
6300             hkdf->info_length = data_length;
6301             if (data_length != 0) {
6302                 hkdf->info = mbedtls_calloc(1, data_length);
6303                 if (hkdf->info == NULL) {
6304                     return PSA_ERROR_INSUFFICIENT_MEMORY;
6305                 }
6306                 memcpy(hkdf->info, data, data_length);
6307             }
6308             hkdf->info_set = 1;
6309             return PSA_SUCCESS;
6310         default:
6311             return PSA_ERROR_INVALID_ARGUMENT;
6312     }
6313 }
6314 #endif /* BUILTIN_ALG_ANY_HKDF */
6315 
6316 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
6317     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
6318 static psa_status_t psa_tls12_prf_set_seed(psa_tls12_prf_key_derivation_t *prf,
6319                                            const uint8_t *data,
6320                                            size_t data_length)
6321 {
6322     if (prf->state != PSA_TLS12_PRF_STATE_INIT) {
6323         return PSA_ERROR_BAD_STATE;
6324     }
6325 
6326     if (data_length != 0) {
6327         prf->seed = mbedtls_calloc(1, data_length);
6328         if (prf->seed == NULL) {
6329             return PSA_ERROR_INSUFFICIENT_MEMORY;
6330         }
6331 
6332         memcpy(prf->seed, data, data_length);
6333         prf->seed_length = data_length;
6334     }
6335 
6336     prf->state = PSA_TLS12_PRF_STATE_SEED_SET;
6337 
6338     return PSA_SUCCESS;
6339 }
6340 
6341 static psa_status_t psa_tls12_prf_set_key(psa_tls12_prf_key_derivation_t *prf,
6342                                           const uint8_t *data,
6343                                           size_t data_length)
6344 {
6345     if (prf->state != PSA_TLS12_PRF_STATE_SEED_SET &&
6346         prf->state != PSA_TLS12_PRF_STATE_OTHER_KEY_SET) {
6347         return PSA_ERROR_BAD_STATE;
6348     }
6349 
6350     if (data_length != 0) {
6351         prf->secret = mbedtls_calloc(1, data_length);
6352         if (prf->secret == NULL) {
6353             return PSA_ERROR_INSUFFICIENT_MEMORY;
6354         }
6355 
6356         memcpy(prf->secret, data, data_length);
6357         prf->secret_length = data_length;
6358     }
6359 
6360     prf->state = PSA_TLS12_PRF_STATE_KEY_SET;
6361 
6362     return PSA_SUCCESS;
6363 }
6364 
6365 static psa_status_t psa_tls12_prf_set_label(psa_tls12_prf_key_derivation_t *prf,
6366                                             const uint8_t *data,
6367                                             size_t data_length)
6368 {
6369     if (prf->state != PSA_TLS12_PRF_STATE_KEY_SET) {
6370         return PSA_ERROR_BAD_STATE;
6371     }
6372 
6373     if (data_length != 0) {
6374         prf->label = mbedtls_calloc(1, data_length);
6375         if (prf->label == NULL) {
6376             return PSA_ERROR_INSUFFICIENT_MEMORY;
6377         }
6378 
6379         memcpy(prf->label, data, data_length);
6380         prf->label_length = data_length;
6381     }
6382 
6383     prf->state = PSA_TLS12_PRF_STATE_LABEL_SET;
6384 
6385     return PSA_SUCCESS;
6386 }
6387 
6388 static psa_status_t psa_tls12_prf_input(psa_tls12_prf_key_derivation_t *prf,
6389                                         psa_key_derivation_step_t step,
6390                                         const uint8_t *data,
6391                                         size_t data_length)
6392 {
6393     switch (step) {
6394         case PSA_KEY_DERIVATION_INPUT_SEED:
6395             return psa_tls12_prf_set_seed(prf, data, data_length);
6396         case PSA_KEY_DERIVATION_INPUT_SECRET:
6397             return psa_tls12_prf_set_key(prf, data, data_length);
6398         case PSA_KEY_DERIVATION_INPUT_LABEL:
6399             return psa_tls12_prf_set_label(prf, data, data_length);
6400         default:
6401             return PSA_ERROR_INVALID_ARGUMENT;
6402     }
6403 }
6404 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) ||
6405         * MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
6406 
6407 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
6408 static psa_status_t psa_tls12_prf_psk_to_ms_set_key(
6409     psa_tls12_prf_key_derivation_t *prf,
6410     const uint8_t *data,
6411     size_t data_length)
6412 {
6413     psa_status_t status;
6414     const size_t pms_len = (prf->state == PSA_TLS12_PRF_STATE_OTHER_KEY_SET ?
6415                             4 + data_length + prf->other_secret_length :
6416                             4 + 2 * data_length);
6417 
6418     if (data_length > PSA_TLS12_PSK_TO_MS_PSK_MAX_SIZE) {
6419         return PSA_ERROR_INVALID_ARGUMENT;
6420     }
6421 
6422     uint8_t *pms = mbedtls_calloc(1, pms_len);
6423     if (pms == NULL) {
6424         return PSA_ERROR_INSUFFICIENT_MEMORY;
6425     }
6426     uint8_t *cur = pms;
6427 
6428     /* pure-PSK:
6429      * Quoting RFC 4279, Section 2:
6430      *
6431      * The premaster secret is formed as follows: if the PSK is N octets
6432      * long, concatenate a uint16 with the value N, N zero octets, a second
6433      * uint16 with the value N, and the PSK itself.
6434      *
6435      * mixed-PSK:
6436      * In a DHE-PSK, RSA-PSK, ECDHE-PSK the premaster secret is formed as
6437      * follows: concatenate a uint16 with the length of the other secret,
6438      * the other secret itself, uint16 with the length of PSK, and the
6439      * PSK itself.
6440      * For details please check:
6441      * - RFC 4279, Section 4 for the definition of RSA-PSK,
6442      * - RFC 4279, Section 3 for the definition of DHE-PSK,
6443      * - RFC 5489 for the definition of ECDHE-PSK.
6444      */
6445 
6446     if (prf->state == PSA_TLS12_PRF_STATE_OTHER_KEY_SET) {
6447         *cur++ = MBEDTLS_BYTE_1(prf->other_secret_length);
6448         *cur++ = MBEDTLS_BYTE_0(prf->other_secret_length);
6449         if (prf->other_secret_length != 0) {
6450             memcpy(cur, prf->other_secret, prf->other_secret_length);
6451             mbedtls_platform_zeroize(prf->other_secret, prf->other_secret_length);
6452             cur += prf->other_secret_length;
6453         }
6454     } else {
6455         *cur++ = MBEDTLS_BYTE_1(data_length);
6456         *cur++ = MBEDTLS_BYTE_0(data_length);
6457         memset(cur, 0, data_length);
6458         cur += data_length;
6459     }
6460 
6461     *cur++ = MBEDTLS_BYTE_1(data_length);
6462     *cur++ = MBEDTLS_BYTE_0(data_length);
6463     memcpy(cur, data, data_length);
6464     cur += data_length;
6465 
6466     status = psa_tls12_prf_set_key(prf, pms, cur - pms);
6467 
6468     mbedtls_zeroize_and_free(pms, pms_len);
6469     return status;
6470 }
6471 
6472 static psa_status_t psa_tls12_prf_psk_to_ms_set_other_key(
6473     psa_tls12_prf_key_derivation_t *prf,
6474     const uint8_t *data,
6475     size_t data_length)
6476 {
6477     if (prf->state != PSA_TLS12_PRF_STATE_SEED_SET) {
6478         return PSA_ERROR_BAD_STATE;
6479     }
6480 
6481     if (data_length != 0) {
6482         prf->other_secret = mbedtls_calloc(1, data_length);
6483         if (prf->other_secret == NULL) {
6484             return PSA_ERROR_INSUFFICIENT_MEMORY;
6485         }
6486 
6487         memcpy(prf->other_secret, data, data_length);
6488         prf->other_secret_length = data_length;
6489     } else {
6490         prf->other_secret_length = 0;
6491     }
6492 
6493     prf->state = PSA_TLS12_PRF_STATE_OTHER_KEY_SET;
6494 
6495     return PSA_SUCCESS;
6496 }
6497 
6498 static psa_status_t psa_tls12_prf_psk_to_ms_input(
6499     psa_tls12_prf_key_derivation_t *prf,
6500     psa_key_derivation_step_t step,
6501     const uint8_t *data,
6502     size_t data_length)
6503 {
6504     switch (step) {
6505         case PSA_KEY_DERIVATION_INPUT_SECRET:
6506             return psa_tls12_prf_psk_to_ms_set_key(prf,
6507                                                    data, data_length);
6508             break;
6509         case PSA_KEY_DERIVATION_INPUT_OTHER_SECRET:
6510             return psa_tls12_prf_psk_to_ms_set_other_key(prf,
6511                                                          data,
6512                                                          data_length);
6513             break;
6514         default:
6515             return psa_tls12_prf_input(prf, step, data, data_length);
6516             break;
6517 
6518     }
6519 }
6520 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
6521 
6522 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS)
6523 static psa_status_t psa_tls12_ecjpake_to_pms_input(
6524     psa_tls12_ecjpake_to_pms_t *ecjpake,
6525     psa_key_derivation_step_t step,
6526     const uint8_t *data,
6527     size_t data_length)
6528 {
6529     if (data_length != PSA_TLS12_ECJPAKE_TO_PMS_INPUT_SIZE ||
6530         step != PSA_KEY_DERIVATION_INPUT_SECRET) {
6531         return PSA_ERROR_INVALID_ARGUMENT;
6532     }
6533 
6534     /* Check if the passed point is in an uncompressed form */
6535     if (data[0] != 0x04) {
6536         return PSA_ERROR_INVALID_ARGUMENT;
6537     }
6538 
6539     /* Only K.X has to be extracted - bytes 1 to 32 inclusive. */
6540     memcpy(ecjpake->data, data + 1, PSA_TLS12_ECJPAKE_TO_PMS_DATA_SIZE);
6541 
6542     return PSA_SUCCESS;
6543 }
6544 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS */
6545 
6546 #if defined(PSA_HAVE_SOFT_PBKDF2)
6547 static psa_status_t psa_pbkdf2_set_input_cost(
6548     psa_pbkdf2_key_derivation_t *pbkdf2,
6549     psa_key_derivation_step_t step,
6550     uint64_t data)
6551 {
6552     if (step != PSA_KEY_DERIVATION_INPUT_COST) {
6553         return PSA_ERROR_INVALID_ARGUMENT;
6554     }
6555 
6556     if (pbkdf2->state != PSA_PBKDF2_STATE_INIT) {
6557         return PSA_ERROR_BAD_STATE;
6558     }
6559 
6560     if (data > PSA_VENDOR_PBKDF2_MAX_ITERATIONS) {
6561         return PSA_ERROR_NOT_SUPPORTED;
6562     }
6563 
6564     if (data == 0) {
6565         return PSA_ERROR_INVALID_ARGUMENT;
6566     }
6567 
6568     pbkdf2->input_cost = data;
6569     pbkdf2->state = PSA_PBKDF2_STATE_INPUT_COST_SET;
6570 
6571     return PSA_SUCCESS;
6572 }
6573 
6574 static psa_status_t psa_pbkdf2_set_salt(psa_pbkdf2_key_derivation_t *pbkdf2,
6575                                         const uint8_t *data,
6576                                         size_t data_length)
6577 {
6578     if (pbkdf2->state == PSA_PBKDF2_STATE_INPUT_COST_SET) {
6579         pbkdf2->state = PSA_PBKDF2_STATE_SALT_SET;
6580     } else if (pbkdf2->state == PSA_PBKDF2_STATE_SALT_SET) {
6581         /* Appending to existing salt. No state change. */
6582     } else {
6583         return PSA_ERROR_BAD_STATE;
6584     }
6585 
6586     if (data_length == 0) {
6587         /* Appending an empty string, nothing to do. */
6588     } else {
6589         uint8_t *next_salt;
6590 
6591         next_salt = mbedtls_calloc(1, data_length + pbkdf2->salt_length);
6592         if (next_salt == NULL) {
6593             return PSA_ERROR_INSUFFICIENT_MEMORY;
6594         }
6595 
6596         if (pbkdf2->salt_length != 0) {
6597             memcpy(next_salt, pbkdf2->salt, pbkdf2->salt_length);
6598         }
6599         memcpy(next_salt + pbkdf2->salt_length, data, data_length);
6600         pbkdf2->salt_length += data_length;
6601         mbedtls_free(pbkdf2->salt);
6602         pbkdf2->salt = next_salt;
6603     }
6604     return PSA_SUCCESS;
6605 }
6606 
6607 #if defined(MBEDTLS_PSA_BUILTIN_ALG_PBKDF2_HMAC)
6608 static psa_status_t psa_pbkdf2_hmac_set_password(psa_algorithm_t hash_alg,
6609                                                  const uint8_t *input,
6610                                                  size_t input_len,
6611                                                  uint8_t *output,
6612                                                  size_t *output_len)
6613 {
6614     psa_status_t status = PSA_SUCCESS;
6615     if (input_len > PSA_HASH_BLOCK_LENGTH(hash_alg)) {
6616         status = psa_hash_compute(hash_alg, input, input_len, output,
6617                                   PSA_HMAC_MAX_HASH_BLOCK_SIZE, output_len);
6618     } else {
6619         memcpy(output, input, input_len);
6620         *output_len = PSA_HASH_BLOCK_LENGTH(hash_alg);
6621     }
6622     return status;
6623 }
6624 #endif /* MBEDTLS_PSA_BUILTIN_ALG_PBKDF2_HMAC */
6625 
6626 #if defined(MBEDTLS_PSA_BUILTIN_ALG_PBKDF2_AES_CMAC_PRF_128)
6627 static psa_status_t psa_pbkdf2_cmac_set_password(const uint8_t *input,
6628                                                  size_t input_len,
6629                                                  uint8_t *output,
6630                                                  size_t *output_len)
6631 {
6632     psa_status_t status = PSA_SUCCESS;
6633     if (input_len != PSA_MAC_LENGTH(PSA_KEY_TYPE_AES, 128U, PSA_ALG_CMAC)) {
6634         psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
6635         uint8_t zeros[16] = { 0 };
6636         psa_set_key_type(&attributes, PSA_KEY_TYPE_AES);
6637         psa_set_key_bits(&attributes, PSA_BYTES_TO_BITS(sizeof(zeros)));
6638         psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_MESSAGE);
6639         /* Passing PSA_MAC_LENGTH(PSA_KEY_TYPE_AES, 128U, PSA_ALG_CMAC) as
6640          * mac_size as the driver function sets mac_output_length = mac_size
6641          * on success. See https://github.com/Mbed-TLS/mbedtls/issues/7801 */
6642         status = psa_driver_wrapper_mac_compute(&attributes,
6643                                                 zeros, sizeof(zeros),
6644                                                 PSA_ALG_CMAC, input, input_len,
6645                                                 output,
6646                                                 PSA_MAC_LENGTH(PSA_KEY_TYPE_AES,
6647                                                                128U,
6648                                                                PSA_ALG_CMAC),
6649                                                 output_len);
6650     } else {
6651         memcpy(output, input, input_len);
6652         *output_len = PSA_MAC_LENGTH(PSA_KEY_TYPE_AES, 128U, PSA_ALG_CMAC);
6653     }
6654     return status;
6655 }
6656 #endif /* MBEDTLS_PSA_BUILTIN_ALG_PBKDF2_AES_CMAC_PRF_128 */
6657 
6658 static psa_status_t psa_pbkdf2_set_password(psa_pbkdf2_key_derivation_t *pbkdf2,
6659                                             psa_algorithm_t kdf_alg,
6660                                             const uint8_t *data,
6661                                             size_t data_length)
6662 {
6663     psa_status_t status = PSA_SUCCESS;
6664     if (pbkdf2->state != PSA_PBKDF2_STATE_SALT_SET) {
6665         return PSA_ERROR_BAD_STATE;
6666     }
6667 
6668 #if defined(MBEDTLS_PSA_BUILTIN_ALG_PBKDF2_HMAC)
6669     if (PSA_ALG_IS_PBKDF2_HMAC(kdf_alg)) {
6670         psa_algorithm_t hash_alg = PSA_ALG_PBKDF2_HMAC_GET_HASH(kdf_alg);
6671         status = psa_pbkdf2_hmac_set_password(hash_alg, data, data_length,
6672                                               pbkdf2->password,
6673                                               &pbkdf2->password_length);
6674     } else
6675 #endif /* MBEDTLS_PSA_BUILTIN_ALG_PBKDF2_HMAC */
6676 #if defined(MBEDTLS_PSA_BUILTIN_ALG_PBKDF2_AES_CMAC_PRF_128)
6677     if (kdf_alg == PSA_ALG_PBKDF2_AES_CMAC_PRF_128) {
6678         status = psa_pbkdf2_cmac_set_password(data, data_length,
6679                                               pbkdf2->password,
6680                                               &pbkdf2->password_length);
6681     } else
6682 #endif /* MBEDTLS_PSA_BUILTIN_ALG_PBKDF2_AES_CMAC_PRF_128 */
6683     {
6684         return PSA_ERROR_INVALID_ARGUMENT;
6685     }
6686 
6687     pbkdf2->state = PSA_PBKDF2_STATE_PASSWORD_SET;
6688 
6689     return status;
6690 }
6691 
6692 static psa_status_t psa_pbkdf2_input(psa_pbkdf2_key_derivation_t *pbkdf2,
6693                                      psa_algorithm_t kdf_alg,
6694                                      psa_key_derivation_step_t step,
6695                                      const uint8_t *data,
6696                                      size_t data_length)
6697 {
6698     switch (step) {
6699         case PSA_KEY_DERIVATION_INPUT_SALT:
6700             return psa_pbkdf2_set_salt(pbkdf2, data, data_length);
6701         case PSA_KEY_DERIVATION_INPUT_PASSWORD:
6702             return psa_pbkdf2_set_password(pbkdf2, kdf_alg, data, data_length);
6703         default:
6704             return PSA_ERROR_INVALID_ARGUMENT;
6705     }
6706 }
6707 #endif /* PSA_HAVE_SOFT_PBKDF2 */
6708 
6709 /** Check whether the given key type is acceptable for the given
6710  * input step of a key derivation.
6711  *
6712  * Secret inputs must have the type #PSA_KEY_TYPE_DERIVE.
6713  * Non-secret inputs must have the type #PSA_KEY_TYPE_RAW_DATA.
6714  * Both secret and non-secret inputs can alternatively have the type
6715  * #PSA_KEY_TYPE_NONE, which is never the type of a key object, meaning
6716  * that the input was passed as a buffer rather than via a key object.
6717  */
6718 static int psa_key_derivation_check_input_type(
6719     psa_key_derivation_step_t step,
6720     psa_key_type_t key_type)
6721 {
6722     switch (step) {
6723         case PSA_KEY_DERIVATION_INPUT_SECRET:
6724             if (key_type == PSA_KEY_TYPE_DERIVE) {
6725                 return PSA_SUCCESS;
6726             }
6727             if (key_type == PSA_KEY_TYPE_NONE) {
6728                 return PSA_SUCCESS;
6729             }
6730             break;
6731         case PSA_KEY_DERIVATION_INPUT_OTHER_SECRET:
6732             if (key_type == PSA_KEY_TYPE_DERIVE) {
6733                 return PSA_SUCCESS;
6734             }
6735             if (key_type == PSA_KEY_TYPE_NONE) {
6736                 return PSA_SUCCESS;
6737             }
6738             break;
6739         case PSA_KEY_DERIVATION_INPUT_LABEL:
6740         case PSA_KEY_DERIVATION_INPUT_SALT:
6741         case PSA_KEY_DERIVATION_INPUT_INFO:
6742         case PSA_KEY_DERIVATION_INPUT_SEED:
6743             if (key_type == PSA_KEY_TYPE_RAW_DATA) {
6744                 return PSA_SUCCESS;
6745             }
6746             if (key_type == PSA_KEY_TYPE_NONE) {
6747                 return PSA_SUCCESS;
6748             }
6749             break;
6750         case PSA_KEY_DERIVATION_INPUT_PASSWORD:
6751             if (key_type == PSA_KEY_TYPE_PASSWORD) {
6752                 return PSA_SUCCESS;
6753             }
6754             if (key_type == PSA_KEY_TYPE_DERIVE) {
6755                 return PSA_SUCCESS;
6756             }
6757             if (key_type == PSA_KEY_TYPE_NONE) {
6758                 return PSA_SUCCESS;
6759             }
6760             break;
6761     }
6762     return PSA_ERROR_INVALID_ARGUMENT;
6763 }
6764 
6765 static psa_status_t psa_key_derivation_input_internal(
6766     psa_key_derivation_operation_t *operation,
6767     psa_key_derivation_step_t step,
6768     psa_key_type_t key_type,
6769     const uint8_t *data,
6770     size_t data_length)
6771 {
6772     psa_status_t status;
6773     psa_algorithm_t kdf_alg = psa_key_derivation_get_kdf_alg(operation);
6774 
6775     status = psa_key_derivation_check_input_type(step, key_type);
6776     if (status != PSA_SUCCESS) {
6777         goto exit;
6778     }
6779 
6780 #if defined(BUILTIN_ALG_ANY_HKDF)
6781     if (PSA_ALG_IS_ANY_HKDF(kdf_alg)) {
6782         status = psa_hkdf_input(&operation->ctx.hkdf, kdf_alg,
6783                                 step, data, data_length);
6784     } else
6785 #endif /* BUILTIN_ALG_ANY_HKDF */
6786 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF)
6787     if (PSA_ALG_IS_TLS12_PRF(kdf_alg)) {
6788         status = psa_tls12_prf_input(&operation->ctx.tls12_prf,
6789                                      step, data, data_length);
6790     } else
6791 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF */
6792 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
6793     if (PSA_ALG_IS_TLS12_PSK_TO_MS(kdf_alg)) {
6794         status = psa_tls12_prf_psk_to_ms_input(&operation->ctx.tls12_prf,
6795                                                step, data, data_length);
6796     } else
6797 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
6798 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS)
6799     if (kdf_alg == PSA_ALG_TLS12_ECJPAKE_TO_PMS) {
6800         status = psa_tls12_ecjpake_to_pms_input(
6801             &operation->ctx.tls12_ecjpake_to_pms, step, data, data_length);
6802     } else
6803 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS */
6804 #if defined(PSA_HAVE_SOFT_PBKDF2)
6805     if (PSA_ALG_IS_PBKDF2(kdf_alg)) {
6806         status = psa_pbkdf2_input(&operation->ctx.pbkdf2, kdf_alg,
6807                                   step, data, data_length);
6808     } else
6809 #endif /* PSA_HAVE_SOFT_PBKDF2 */
6810     {
6811         /* This can't happen unless the operation object was not initialized */
6812         (void) data;
6813         (void) data_length;
6814         (void) kdf_alg;
6815         return PSA_ERROR_BAD_STATE;
6816     }
6817 
6818 exit:
6819     if (status != PSA_SUCCESS) {
6820         psa_key_derivation_abort(operation);
6821     }
6822     return status;
6823 }
6824 
6825 static psa_status_t psa_key_derivation_input_integer_internal(
6826     psa_key_derivation_operation_t *operation,
6827     psa_key_derivation_step_t step,
6828     uint64_t value)
6829 {
6830     psa_status_t status;
6831     psa_algorithm_t kdf_alg = psa_key_derivation_get_kdf_alg(operation);
6832 
6833 #if defined(PSA_HAVE_SOFT_PBKDF2)
6834     if (PSA_ALG_IS_PBKDF2(kdf_alg)) {
6835         status = psa_pbkdf2_set_input_cost(
6836             &operation->ctx.pbkdf2, step, value);
6837     } else
6838 #endif /* PSA_HAVE_SOFT_PBKDF2 */
6839     {
6840         (void) step;
6841         (void) value;
6842         (void) kdf_alg;
6843         status = PSA_ERROR_INVALID_ARGUMENT;
6844     }
6845 
6846     if (status != PSA_SUCCESS) {
6847         psa_key_derivation_abort(operation);
6848     }
6849     return status;
6850 }
6851 
6852 psa_status_t psa_key_derivation_input_bytes(
6853     psa_key_derivation_operation_t *operation,
6854     psa_key_derivation_step_t step,
6855     const uint8_t *data,
6856     size_t data_length)
6857 {
6858     return psa_key_derivation_input_internal(operation, step,
6859                                              PSA_KEY_TYPE_NONE,
6860                                              data, data_length);
6861 }
6862 
6863 psa_status_t psa_key_derivation_input_integer(
6864     psa_key_derivation_operation_t *operation,
6865     psa_key_derivation_step_t step,
6866     uint64_t value)
6867 {
6868     return psa_key_derivation_input_integer_internal(operation, step, value);
6869 }
6870 
6871 psa_status_t psa_key_derivation_input_key(
6872     psa_key_derivation_operation_t *operation,
6873     psa_key_derivation_step_t step,
6874     mbedtls_svc_key_id_t key)
6875 {
6876     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
6877     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
6878     psa_key_slot_t *slot;
6879 
6880     status = psa_get_and_lock_transparent_key_slot_with_policy(
6881         key, &slot, PSA_KEY_USAGE_DERIVE, operation->alg);
6882     if (status != PSA_SUCCESS) {
6883         psa_key_derivation_abort(operation);
6884         return status;
6885     }
6886 
6887     /* Passing a key object as a SECRET or PASSWORD input unlocks the
6888      * permission to output to a key object. */
6889     if (step == PSA_KEY_DERIVATION_INPUT_SECRET ||
6890         step == PSA_KEY_DERIVATION_INPUT_PASSWORD) {
6891         operation->can_output_key = 1;
6892     }
6893 
6894     status = psa_key_derivation_input_internal(operation,
6895                                                step, slot->attr.type,
6896                                                slot->key.data,
6897                                                slot->key.bytes);
6898 
6899     unlock_status = psa_unlock_key_slot(slot);
6900 
6901     return (status == PSA_SUCCESS) ? unlock_status : status;
6902 }
6903 
6904 
6905 
6906 /****************************************************************/
6907 /* Key agreement */
6908 /****************************************************************/
6909 
6910 psa_status_t psa_key_agreement_raw_builtin(const psa_key_attributes_t *attributes,
6911                                            const uint8_t *key_buffer,
6912                                            size_t key_buffer_size,
6913                                            psa_algorithm_t alg,
6914                                            const uint8_t *peer_key,
6915                                            size_t peer_key_length,
6916                                            uint8_t *shared_secret,
6917                                            size_t shared_secret_size,
6918                                            size_t *shared_secret_length)
6919 {
6920     switch (alg) {
6921 #if defined(MBEDTLS_PSA_BUILTIN_ALG_ECDH)
6922         case PSA_ALG_ECDH:
6923             return mbedtls_psa_key_agreement_ecdh(attributes, key_buffer,
6924                                                   key_buffer_size, alg,
6925                                                   peer_key, peer_key_length,
6926                                                   shared_secret,
6927                                                   shared_secret_size,
6928                                                   shared_secret_length);
6929 #endif /* MBEDTLS_PSA_BUILTIN_ALG_ECDH */
6930 
6931 #if defined(MBEDTLS_PSA_BUILTIN_ALG_FFDH)
6932         case PSA_ALG_FFDH:
6933             return mbedtls_psa_ffdh_key_agreement(attributes,
6934                                                   peer_key,
6935                                                   peer_key_length,
6936                                                   key_buffer,
6937                                                   key_buffer_size,
6938                                                   shared_secret,
6939                                                   shared_secret_size,
6940                                                   shared_secret_length);
6941 #endif /* MBEDTLS_PSA_BUILTIN_ALG_FFDH */
6942 
6943         default:
6944             (void) attributes;
6945             (void) key_buffer;
6946             (void) key_buffer_size;
6947             (void) peer_key;
6948             (void) peer_key_length;
6949             (void) shared_secret;
6950             (void) shared_secret_size;
6951             (void) shared_secret_length;
6952             return PSA_ERROR_NOT_SUPPORTED;
6953     }
6954 }
6955 
6956 /** Internal function for raw key agreement
6957  *  Calls the driver wrapper which will hand off key agreement task
6958  *  to the driver's implementation if a driver is present.
6959  *  Fallback specified in the driver wrapper is built-in raw key agreement
6960  *  (psa_key_agreement_raw_builtin).
6961  */
6962 static psa_status_t psa_key_agreement_raw_internal(psa_algorithm_t alg,
6963                                                    psa_key_slot_t *private_key,
6964                                                    const uint8_t *peer_key,
6965                                                    size_t peer_key_length,
6966                                                    uint8_t *shared_secret,
6967                                                    size_t shared_secret_size,
6968                                                    size_t *shared_secret_length)
6969 {
6970     if (!PSA_ALG_IS_RAW_KEY_AGREEMENT(alg)) {
6971         return PSA_ERROR_NOT_SUPPORTED;
6972     }
6973 
6974     psa_key_attributes_t attributes = {
6975         .core = private_key->attr
6976     };
6977 
6978     return psa_driver_wrapper_key_agreement(&attributes,
6979                                             private_key->key.data,
6980                                             private_key->key.bytes, alg,
6981                                             peer_key, peer_key_length,
6982                                             shared_secret,
6983                                             shared_secret_size,
6984                                             shared_secret_length);
6985 }
6986 
6987 /* Note that if this function fails, you must call psa_key_derivation_abort()
6988  * to potentially free embedded data structures and wipe confidential data.
6989  */
6990 static psa_status_t psa_key_agreement_internal(psa_key_derivation_operation_t *operation,
6991                                                psa_key_derivation_step_t step,
6992                                                psa_key_slot_t *private_key,
6993                                                const uint8_t *peer_key,
6994                                                size_t peer_key_length)
6995 {
6996     psa_status_t status;
6997     uint8_t shared_secret[PSA_RAW_KEY_AGREEMENT_OUTPUT_MAX_SIZE];
6998     size_t shared_secret_length = 0;
6999     psa_algorithm_t ka_alg = PSA_ALG_KEY_AGREEMENT_GET_BASE(operation->alg);
7000 
7001     /* Step 1: run the secret agreement algorithm to generate the shared
7002      * secret. */
7003     status = psa_key_agreement_raw_internal(ka_alg,
7004                                             private_key,
7005                                             peer_key, peer_key_length,
7006                                             shared_secret,
7007                                             sizeof(shared_secret),
7008                                             &shared_secret_length);
7009     if (status != PSA_SUCCESS) {
7010         goto exit;
7011     }
7012 
7013     /* Step 2: set up the key derivation to generate key material from
7014      * the shared secret. A shared secret is permitted wherever a key
7015      * of type DERIVE is permitted. */
7016     status = psa_key_derivation_input_internal(operation, step,
7017                                                PSA_KEY_TYPE_DERIVE,
7018                                                shared_secret,
7019                                                shared_secret_length);
7020 exit:
7021     mbedtls_platform_zeroize(shared_secret, shared_secret_length);
7022     return status;
7023 }
7024 
7025 psa_status_t psa_key_derivation_key_agreement(psa_key_derivation_operation_t *operation,
7026                                               psa_key_derivation_step_t step,
7027                                               mbedtls_svc_key_id_t private_key,
7028                                               const uint8_t *peer_key,
7029                                               size_t peer_key_length)
7030 {
7031     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
7032     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
7033     psa_key_slot_t *slot;
7034 
7035     if (!PSA_ALG_IS_KEY_AGREEMENT(operation->alg)) {
7036         return PSA_ERROR_INVALID_ARGUMENT;
7037     }
7038     status = psa_get_and_lock_transparent_key_slot_with_policy(
7039         private_key, &slot, PSA_KEY_USAGE_DERIVE, operation->alg);
7040     if (status != PSA_SUCCESS) {
7041         return status;
7042     }
7043     status = psa_key_agreement_internal(operation, step,
7044                                         slot,
7045                                         peer_key, peer_key_length);
7046     if (status != PSA_SUCCESS) {
7047         psa_key_derivation_abort(operation);
7048     } else {
7049         /* If a private key has been added as SECRET, we allow the derived
7050          * key material to be used as a key in PSA Crypto. */
7051         if (step == PSA_KEY_DERIVATION_INPUT_SECRET) {
7052             operation->can_output_key = 1;
7053         }
7054     }
7055 
7056     unlock_status = psa_unlock_key_slot(slot);
7057 
7058     return (status == PSA_SUCCESS) ? unlock_status : status;
7059 }
7060 
7061 psa_status_t psa_raw_key_agreement(psa_algorithm_t alg,
7062                                    mbedtls_svc_key_id_t private_key,
7063                                    const uint8_t *peer_key,
7064                                    size_t peer_key_length,
7065                                    uint8_t *output,
7066                                    size_t output_size,
7067                                    size_t *output_length)
7068 {
7069     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
7070     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
7071     psa_key_slot_t *slot = NULL;
7072     size_t expected_length;
7073 
7074     if (!PSA_ALG_IS_KEY_AGREEMENT(alg)) {
7075         status = PSA_ERROR_INVALID_ARGUMENT;
7076         goto exit;
7077     }
7078     status = psa_get_and_lock_transparent_key_slot_with_policy(
7079         private_key, &slot, PSA_KEY_USAGE_DERIVE, alg);
7080     if (status != PSA_SUCCESS) {
7081         goto exit;
7082     }
7083 
7084     /* PSA_RAW_KEY_AGREEMENT_OUTPUT_SIZE() is in general an upper bound
7085      * for the output size. The PSA specification only guarantees that this
7086      * function works if output_size >= PSA_RAW_KEY_AGREEMENT_OUTPUT_SIZE(...),
7087      * but it might be nice to allow smaller buffers if the output fits.
7088      * At the time of writing this comment, with only ECDH implemented,
7089      * PSA_RAW_KEY_AGREEMENT_OUTPUT_SIZE() is exact so the point is moot.
7090      * If FFDH is implemented, PSA_RAW_KEY_AGREEMENT_OUTPUT_SIZE() can easily
7091      * be exact for it as well. */
7092     expected_length =
7093         PSA_RAW_KEY_AGREEMENT_OUTPUT_SIZE(slot->attr.type, slot->attr.bits);
7094     if (output_size < expected_length) {
7095         status = PSA_ERROR_BUFFER_TOO_SMALL;
7096         goto exit;
7097     }
7098 
7099     status = psa_key_agreement_raw_internal(alg, slot,
7100                                             peer_key, peer_key_length,
7101                                             output, output_size,
7102                                             output_length);
7103 
7104 exit:
7105     if (status != PSA_SUCCESS) {
7106         /* If an error happens and is not handled properly, the output
7107          * may be used as a key to protect sensitive data. Arrange for such
7108          * a key to be random, which is likely to result in decryption or
7109          * verification errors. This is better than filling the buffer with
7110          * some constant data such as zeros, which would result in the data
7111          * being protected with a reproducible, easily knowable key.
7112          */
7113         psa_generate_random(output, output_size);
7114         *output_length = output_size;
7115     }
7116 
7117     unlock_status = psa_unlock_key_slot(slot);
7118 
7119     return (status == PSA_SUCCESS) ? unlock_status : status;
7120 }
7121 
7122 
7123 
7124 /****************************************************************/
7125 /* Random generation */
7126 /****************************************************************/
7127 
7128 #if defined(MBEDTLS_PSA_INJECT_ENTROPY)
7129 #include "entropy_poll.h"
7130 #endif
7131 
7132 /** Initialize the PSA random generator.
7133  */
7134 static void mbedtls_psa_random_init(mbedtls_psa_random_context_t *rng)
7135 {
7136 #if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
7137     memset(rng, 0, sizeof(*rng));
7138 #else /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
7139 
7140     /* Set default configuration if
7141      * mbedtls_psa_crypto_configure_entropy_sources() hasn't been called. */
7142     if (rng->entropy_init == NULL) {
7143         rng->entropy_init = mbedtls_entropy_init;
7144     }
7145     if (rng->entropy_free == NULL) {
7146         rng->entropy_free = mbedtls_entropy_free;
7147     }
7148 
7149     rng->entropy_init(&rng->entropy);
7150 #if defined(MBEDTLS_PSA_INJECT_ENTROPY) && \
7151     defined(MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES)
7152     /* The PSA entropy injection feature depends on using NV seed as an entropy
7153      * source. Add NV seed as an entropy source for PSA entropy injection. */
7154     mbedtls_entropy_add_source(&rng->entropy,
7155                                mbedtls_nv_seed_poll, NULL,
7156                                MBEDTLS_ENTROPY_BLOCK_SIZE,
7157                                MBEDTLS_ENTROPY_SOURCE_STRONG);
7158 #endif
7159 
7160     mbedtls_psa_drbg_init(MBEDTLS_PSA_RANDOM_STATE);
7161 #endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
7162 }
7163 
7164 /** Deinitialize the PSA random generator.
7165  */
7166 static void mbedtls_psa_random_free(mbedtls_psa_random_context_t *rng)
7167 {
7168 #if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
7169     memset(rng, 0, sizeof(*rng));
7170 #else /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
7171     mbedtls_psa_drbg_free(MBEDTLS_PSA_RANDOM_STATE);
7172     rng->entropy_free(&rng->entropy);
7173 #endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
7174 }
7175 
7176 /** Seed the PSA random generator.
7177  */
7178 static psa_status_t mbedtls_psa_random_seed(mbedtls_psa_random_context_t *rng)
7179 {
7180 #if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
7181     /* Do nothing: the external RNG seeds itself. */
7182     (void) rng;
7183     return PSA_SUCCESS;
7184 #else /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
7185     const unsigned char drbg_seed[] = "PSA";
7186     int ret = mbedtls_psa_drbg_seed(&rng->entropy,
7187                                     drbg_seed, sizeof(drbg_seed) - 1);
7188     return mbedtls_to_psa_error(ret);
7189 #endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
7190 }
7191 
7192 psa_status_t psa_generate_random(uint8_t *output,
7193                                  size_t output_size)
7194 {
7195     GUARD_MODULE_INITIALIZED;
7196 
7197 #if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
7198 
7199     size_t output_length = 0;
7200     psa_status_t status = mbedtls_psa_external_get_random(&global_data.rng,
7201                                                           output, output_size,
7202                                                           &output_length);
7203     if (status != PSA_SUCCESS) {
7204         return status;
7205     }
7206     /* Breaking up a request into smaller chunks is currently not supported
7207      * for the external RNG interface. */
7208     if (output_length != output_size) {
7209         return PSA_ERROR_INSUFFICIENT_ENTROPY;
7210     }
7211     return PSA_SUCCESS;
7212 
7213 #else /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
7214 
7215     while (output_size > 0) {
7216         size_t request_size =
7217             (output_size > MBEDTLS_PSA_RANDOM_MAX_REQUEST ?
7218              MBEDTLS_PSA_RANDOM_MAX_REQUEST :
7219              output_size);
7220         int ret = mbedtls_psa_get_random(MBEDTLS_PSA_RANDOM_STATE,
7221                                          output, request_size);
7222         if (ret != 0) {
7223             return mbedtls_to_psa_error(ret);
7224         }
7225         output_size -= request_size;
7226         output += request_size;
7227     }
7228     return PSA_SUCCESS;
7229 #endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
7230 }
7231 
7232 /* Wrapper function allowing the classic API to use the PSA RNG.
7233  *
7234  * `mbedtls_psa_get_random(MBEDTLS_PSA_RANDOM_STATE, ...)` calls
7235  * `psa_generate_random(...)`. The state parameter is ignored since the
7236  * PSA API doesn't support passing an explicit state.
7237  *
7238  * In the non-external case, psa_generate_random() calls an
7239  * `mbedtls_xxx_drbg_random` function which has exactly the same signature
7240  * and semantics as mbedtls_psa_get_random(). As an optimization,
7241  * instead of doing this back-and-forth between the PSA API and the
7242  * classic API, psa_crypto_random_impl.h defines `mbedtls_psa_get_random`
7243  * as a constant function pointer to `mbedtls_xxx_drbg_random`.
7244  */
7245 #if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
7246 int mbedtls_psa_get_random(void *p_rng,
7247                            unsigned char *output,
7248                            size_t output_size)
7249 {
7250     /* This function takes a pointer to the RNG state because that's what
7251      * classic mbedtls functions using an RNG expect. The PSA RNG manages
7252      * its own state internally and doesn't let the caller access that state.
7253      * So we just ignore the state parameter, and in practice we'll pass
7254      * NULL. */
7255     (void) p_rng;
7256     psa_status_t status = psa_generate_random(output, output_size);
7257     if (status == PSA_SUCCESS) {
7258         return 0;
7259     } else {
7260         return MBEDTLS_ERR_ENTROPY_SOURCE_FAILED;
7261     }
7262 }
7263 #endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
7264 
7265 #if defined(MBEDTLS_PSA_INJECT_ENTROPY)
7266 psa_status_t mbedtls_psa_inject_entropy(const uint8_t *seed,
7267                                         size_t seed_size)
7268 {
7269     if (global_data.initialized) {
7270         return PSA_ERROR_NOT_PERMITTED;
7271     }
7272 
7273     if (((seed_size < MBEDTLS_ENTROPY_MIN_PLATFORM) ||
7274          (seed_size < MBEDTLS_ENTROPY_BLOCK_SIZE)) ||
7275         (seed_size > MBEDTLS_ENTROPY_MAX_SEED_SIZE)) {
7276         return PSA_ERROR_INVALID_ARGUMENT;
7277     }
7278 
7279     return mbedtls_psa_storage_inject_entropy(seed, seed_size);
7280 }
7281 #endif /* MBEDTLS_PSA_INJECT_ENTROPY */
7282 
7283 /** Validate the key type and size for key generation
7284  *
7285  * \param  type  The key type
7286  * \param  bits  The number of bits of the key
7287  *
7288  * \retval #PSA_SUCCESS
7289  *         The key type and size are valid.
7290  * \retval #PSA_ERROR_INVALID_ARGUMENT
7291  *         The size in bits of the key is not valid.
7292  * \retval #PSA_ERROR_NOT_SUPPORTED
7293  *         The type and/or the size in bits of the key or the combination of
7294  *         the two is not supported.
7295  */
7296 static psa_status_t psa_validate_key_type_and_size_for_key_generation(
7297     psa_key_type_t type, size_t bits)
7298 {
7299     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
7300 
7301     if (key_type_is_raw_bytes(type)) {
7302         status = psa_validate_unstructured_key_bit_size(type, bits);
7303         if (status != PSA_SUCCESS) {
7304             return status;
7305         }
7306     } else
7307 #if defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_GENERATE)
7308     if (PSA_KEY_TYPE_IS_RSA(type) && PSA_KEY_TYPE_IS_KEY_PAIR(type)) {
7309         if (bits > PSA_VENDOR_RSA_MAX_KEY_BITS) {
7310             return PSA_ERROR_NOT_SUPPORTED;
7311         }
7312         if (bits < PSA_VENDOR_RSA_GENERATE_MIN_KEY_BITS) {
7313             return PSA_ERROR_NOT_SUPPORTED;
7314         }
7315 
7316         /* Accept only byte-aligned keys, for the same reasons as
7317          * in psa_import_rsa_key(). */
7318         if (bits % 8 != 0) {
7319             return PSA_ERROR_NOT_SUPPORTED;
7320         }
7321     } else
7322 #endif /* defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_GENERATE) */
7323 
7324 #if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_GENERATE)
7325     if (PSA_KEY_TYPE_IS_ECC(type) && PSA_KEY_TYPE_IS_KEY_PAIR(type)) {
7326         /* To avoid empty block, return successfully here. */
7327         return PSA_SUCCESS;
7328     } else
7329 #endif /* defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_GENERATE) */
7330 
7331 #if defined(PSA_WANT_KEY_TYPE_DH_KEY_PAIR_GENERATE)
7332     if (PSA_KEY_TYPE_IS_DH(type) && PSA_KEY_TYPE_IS_KEY_PAIR(type)) {
7333         if (psa_is_dh_key_size_valid(bits) == 0) {
7334             return PSA_ERROR_NOT_SUPPORTED;
7335         }
7336     } else
7337 #endif /* defined(PSA_WANT_KEY_TYPE_DH_KEY_PAIR_GENERATE) */
7338     {
7339         return PSA_ERROR_NOT_SUPPORTED;
7340     }
7341 
7342     return PSA_SUCCESS;
7343 }
7344 
7345 psa_status_t psa_generate_key_internal(
7346     const psa_key_attributes_t *attributes,
7347     uint8_t *key_buffer, size_t key_buffer_size, size_t *key_buffer_length)
7348 {
7349     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
7350     psa_key_type_t type = attributes->core.type;
7351 
7352     if ((attributes->domain_parameters == NULL) &&
7353         (attributes->domain_parameters_size != 0)) {
7354         return PSA_ERROR_INVALID_ARGUMENT;
7355     }
7356 
7357     if (key_type_is_raw_bytes(type)) {
7358         status = psa_generate_random(key_buffer, key_buffer_size);
7359         if (status != PSA_SUCCESS) {
7360             return status;
7361         }
7362 
7363 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES)
7364         if (type == PSA_KEY_TYPE_DES) {
7365             psa_des_set_key_parity(key_buffer, key_buffer_size);
7366         }
7367 #endif /* MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES */
7368     } else
7369 
7370 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_GENERATE)
7371     if (type == PSA_KEY_TYPE_RSA_KEY_PAIR) {
7372         return mbedtls_psa_rsa_generate_key(attributes,
7373                                             key_buffer,
7374                                             key_buffer_size,
7375                                             key_buffer_length);
7376     } else
7377 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_GENERATE) */
7378 
7379 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_GENERATE)
7380     if (PSA_KEY_TYPE_IS_ECC(type) && PSA_KEY_TYPE_IS_KEY_PAIR(type)) {
7381         return mbedtls_psa_ecp_generate_key(attributes,
7382                                             key_buffer,
7383                                             key_buffer_size,
7384                                             key_buffer_length);
7385     } else
7386 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_GENERATE) */
7387 
7388 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_KEY_PAIR_GENERATE)
7389     if (PSA_KEY_TYPE_IS_DH(type) && PSA_KEY_TYPE_IS_KEY_PAIR(type)) {
7390         return mbedtls_psa_ffdh_generate_key(attributes,
7391                                              key_buffer,
7392                                              key_buffer_size,
7393                                              key_buffer_length);
7394     } else
7395 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_KEY_PAIR_GENERATE) */
7396     {
7397         (void) key_buffer_length;
7398         return PSA_ERROR_NOT_SUPPORTED;
7399     }
7400 
7401     return PSA_SUCCESS;
7402 }
7403 
7404 psa_status_t psa_generate_key(const psa_key_attributes_t *attributes,
7405                               mbedtls_svc_key_id_t *key)
7406 {
7407     psa_status_t status;
7408     psa_key_slot_t *slot = NULL;
7409     psa_se_drv_table_entry_t *driver = NULL;
7410     size_t key_buffer_size;
7411 
7412     *key = MBEDTLS_SVC_KEY_ID_INIT;
7413 
7414     /* Reject any attempt to create a zero-length key so that we don't
7415      * risk tripping up later, e.g. on a malloc(0) that returns NULL. */
7416     if (psa_get_key_bits(attributes) == 0) {
7417         return PSA_ERROR_INVALID_ARGUMENT;
7418     }
7419 
7420     /* Reject any attempt to create a public key. */
7421     if (PSA_KEY_TYPE_IS_PUBLIC_KEY(attributes->core.type)) {
7422         return PSA_ERROR_INVALID_ARGUMENT;
7423     }
7424 
7425     status = psa_start_key_creation(PSA_KEY_CREATION_GENERATE, attributes,
7426                                     &slot, &driver);
7427     if (status != PSA_SUCCESS) {
7428         goto exit;
7429     }
7430 
7431     /* In the case of a transparent key or an opaque key stored in local
7432      * storage ( thus not in the case of generating a key in a secure element
7433      * with storage ( MBEDTLS_PSA_CRYPTO_SE_C ) ),we have to allocate a
7434      * buffer to hold the generated key material. */
7435     if (slot->key.data == NULL) {
7436         if (PSA_KEY_LIFETIME_GET_LOCATION(attributes->core.lifetime) ==
7437             PSA_KEY_LOCATION_LOCAL_STORAGE) {
7438             status = psa_validate_key_type_and_size_for_key_generation(
7439                 attributes->core.type, attributes->core.bits);
7440             if (status != PSA_SUCCESS) {
7441                 goto exit;
7442             }
7443 
7444             key_buffer_size = PSA_EXPORT_KEY_OUTPUT_SIZE(
7445                 attributes->core.type,
7446                 attributes->core.bits);
7447         } else {
7448             status = psa_driver_wrapper_get_key_buffer_size(
7449                 attributes, &key_buffer_size);
7450             if (status != PSA_SUCCESS) {
7451                 goto exit;
7452             }
7453         }
7454 
7455         status = psa_allocate_buffer_to_slot(slot, key_buffer_size);
7456         if (status != PSA_SUCCESS) {
7457             goto exit;
7458         }
7459     }
7460 
7461     status = psa_driver_wrapper_generate_key(attributes,
7462                                              slot->key.data, slot->key.bytes, &slot->key.bytes);
7463 
7464     if (status != PSA_SUCCESS) {
7465         psa_remove_key_data_from_memory(slot);
7466     }
7467 
7468 exit:
7469     if (status == PSA_SUCCESS) {
7470         status = psa_finish_key_creation(slot, driver, key);
7471     }
7472     if (status != PSA_SUCCESS) {
7473         psa_fail_key_creation(slot, driver);
7474     }
7475 
7476     return status;
7477 }
7478 
7479 /****************************************************************/
7480 /* Module setup */
7481 /****************************************************************/
7482 
7483 #if !defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
7484 psa_status_t mbedtls_psa_crypto_configure_entropy_sources(
7485     void (* entropy_init)(mbedtls_entropy_context *ctx),
7486     void (* entropy_free)(mbedtls_entropy_context *ctx))
7487 {
7488     if (global_data.rng_state != RNG_NOT_INITIALIZED) {
7489         return PSA_ERROR_BAD_STATE;
7490     }
7491     global_data.rng.entropy_init = entropy_init;
7492     global_data.rng.entropy_free = entropy_free;
7493     return PSA_SUCCESS;
7494 }
7495 #endif /* !defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG) */
7496 
7497 void mbedtls_psa_crypto_free(void)
7498 {
7499     psa_wipe_all_key_slots();
7500     if (global_data.rng_state != RNG_NOT_INITIALIZED) {
7501         mbedtls_psa_random_free(&global_data.rng);
7502     }
7503     /* Wipe all remaining data, including configuration.
7504      * In particular, this sets all state indicator to the value
7505      * indicating "uninitialized". */
7506     mbedtls_platform_zeroize(&global_data, sizeof(global_data));
7507 
7508     /* Terminate drivers */
7509     psa_driver_wrapper_free();
7510 }
7511 
7512 #if defined(PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS)
7513 /** Recover a transaction that was interrupted by a power failure.
7514  *
7515  * This function is called during initialization, before psa_crypto_init()
7516  * returns. If this function returns a failure status, the initialization
7517  * fails.
7518  */
7519 static psa_status_t psa_crypto_recover_transaction(
7520     const psa_crypto_transaction_t *transaction)
7521 {
7522     switch (transaction->unknown.type) {
7523         case PSA_CRYPTO_TRANSACTION_CREATE_KEY:
7524         case PSA_CRYPTO_TRANSACTION_DESTROY_KEY:
7525         /* TODO - fall through to the failure case until this
7526          * is implemented.
7527          * https://github.com/ARMmbed/mbed-crypto/issues/218
7528          */
7529         default:
7530             /* We found an unsupported transaction in the storage.
7531              * We don't know what state the storage is in. Give up. */
7532             return PSA_ERROR_DATA_INVALID;
7533     }
7534 }
7535 #endif /* PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS */
7536 
7537 psa_status_t psa_crypto_init(void)
7538 {
7539     psa_status_t status;
7540 
7541     /* Double initialization is explicitly allowed. */
7542     if (global_data.initialized != 0) {
7543         return PSA_SUCCESS;
7544     }
7545 
7546     status = psa_initialize_key_slots();
7547     if (status != PSA_SUCCESS) {
7548         goto exit;
7549     }
7550 
7551     /* Init drivers */
7552     status = psa_driver_wrapper_init();
7553     if (status != PSA_SUCCESS) {
7554         goto exit;
7555     }
7556     global_data.drivers_initialized = 1;
7557 
7558     /* Initialize and seed the random generator. */
7559     mbedtls_psa_random_init(&global_data.rng);
7560     global_data.rng_state = RNG_INITIALIZED;
7561     status = mbedtls_psa_random_seed(&global_data.rng);
7562     if (status != PSA_SUCCESS) {
7563         goto exit;
7564     }
7565     global_data.rng_state = RNG_SEEDED;
7566 
7567 #if defined(PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS)
7568     status = psa_crypto_load_transaction();
7569     if (status == PSA_SUCCESS) {
7570         status = psa_crypto_recover_transaction(&psa_crypto_transaction);
7571         if (status != PSA_SUCCESS) {
7572             goto exit;
7573         }
7574         status = psa_crypto_stop_transaction();
7575     } else if (status == PSA_ERROR_DOES_NOT_EXIST) {
7576         /* There's no transaction to complete. It's all good. */
7577         status = PSA_SUCCESS;
7578     }
7579 #endif /* PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS */
7580 
7581     /* All done. */
7582     global_data.initialized = 1;
7583 
7584 exit:
7585     if (status != PSA_SUCCESS) {
7586         mbedtls_psa_crypto_free();
7587     }
7588     return status;
7589 }
7590 
7591 #if defined(PSA_WANT_ALG_SOME_PAKE)
7592 psa_status_t psa_crypto_driver_pake_get_password_len(
7593     const psa_crypto_driver_pake_inputs_t *inputs,
7594     size_t *password_len)
7595 {
7596     if (inputs->password_len == 0) {
7597         return PSA_ERROR_BAD_STATE;
7598     }
7599 
7600     *password_len = inputs->password_len;
7601 
7602     return PSA_SUCCESS;
7603 }
7604 
7605 psa_status_t psa_crypto_driver_pake_get_password(
7606     const psa_crypto_driver_pake_inputs_t *inputs,
7607     uint8_t *buffer, size_t buffer_size, size_t *buffer_length)
7608 {
7609     if (inputs->password_len == 0) {
7610         return PSA_ERROR_BAD_STATE;
7611     }
7612 
7613     if (buffer_size < inputs->password_len) {
7614         return PSA_ERROR_BUFFER_TOO_SMALL;
7615     }
7616 
7617     memcpy(buffer, inputs->password, inputs->password_len);
7618     *buffer_length = inputs->password_len;
7619 
7620     return PSA_SUCCESS;
7621 }
7622 
7623 psa_status_t psa_crypto_driver_pake_get_user_len(
7624     const psa_crypto_driver_pake_inputs_t *inputs,
7625     size_t *user_len)
7626 {
7627     if (inputs->user_len == 0) {
7628         return PSA_ERROR_BAD_STATE;
7629     }
7630 
7631     *user_len = inputs->user_len;
7632 
7633     return PSA_SUCCESS;
7634 }
7635 
7636 psa_status_t psa_crypto_driver_pake_get_user(
7637     const psa_crypto_driver_pake_inputs_t *inputs,
7638     uint8_t *user_id, size_t user_id_size, size_t *user_id_len)
7639 {
7640     if (inputs->user_len == 0) {
7641         return PSA_ERROR_BAD_STATE;
7642     }
7643 
7644     if (user_id_size < inputs->user_len) {
7645         return PSA_ERROR_BUFFER_TOO_SMALL;
7646     }
7647 
7648     memcpy(user_id, inputs->user, inputs->user_len);
7649     *user_id_len = inputs->user_len;
7650 
7651     return PSA_SUCCESS;
7652 }
7653 
7654 psa_status_t psa_crypto_driver_pake_get_peer_len(
7655     const psa_crypto_driver_pake_inputs_t *inputs,
7656     size_t *peer_len)
7657 {
7658     if (inputs->peer_len == 0) {
7659         return PSA_ERROR_BAD_STATE;
7660     }
7661 
7662     *peer_len = inputs->peer_len;
7663 
7664     return PSA_SUCCESS;
7665 }
7666 
7667 psa_status_t psa_crypto_driver_pake_get_peer(
7668     const psa_crypto_driver_pake_inputs_t *inputs,
7669     uint8_t *peer_id, size_t peer_id_size, size_t *peer_id_length)
7670 {
7671     if (inputs->peer_len == 0) {
7672         return PSA_ERROR_BAD_STATE;
7673     }
7674 
7675     if (peer_id_size < inputs->peer_len) {
7676         return PSA_ERROR_BUFFER_TOO_SMALL;
7677     }
7678 
7679     memcpy(peer_id, inputs->peer, inputs->peer_len);
7680     *peer_id_length = inputs->peer_len;
7681 
7682     return PSA_SUCCESS;
7683 }
7684 
7685 psa_status_t psa_crypto_driver_pake_get_cipher_suite(
7686     const psa_crypto_driver_pake_inputs_t *inputs,
7687     psa_pake_cipher_suite_t *cipher_suite)
7688 {
7689     if (inputs->cipher_suite.algorithm == PSA_ALG_NONE) {
7690         return PSA_ERROR_BAD_STATE;
7691     }
7692 
7693     *cipher_suite = inputs->cipher_suite;
7694 
7695     return PSA_SUCCESS;
7696 }
7697 
7698 psa_status_t psa_pake_setup(
7699     psa_pake_operation_t *operation,
7700     const psa_pake_cipher_suite_t *cipher_suite)
7701 {
7702     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
7703 
7704     if (operation->stage != PSA_PAKE_OPERATION_STAGE_SETUP) {
7705         status = PSA_ERROR_BAD_STATE;
7706         goto exit;
7707     }
7708 
7709     if (PSA_ALG_IS_PAKE(cipher_suite->algorithm) == 0 ||
7710         PSA_ALG_IS_HASH(cipher_suite->hash) == 0) {
7711         status = PSA_ERROR_INVALID_ARGUMENT;
7712         goto exit;
7713     }
7714 
7715     memset(&operation->data.inputs, 0, sizeof(operation->data.inputs));
7716 
7717     operation->alg = cipher_suite->algorithm;
7718     operation->primitive = PSA_PAKE_PRIMITIVE(cipher_suite->type,
7719                                               cipher_suite->family, cipher_suite->bits);
7720     operation->data.inputs.cipher_suite = *cipher_suite;
7721 
7722 #if defined(PSA_WANT_ALG_JPAKE)
7723     if (operation->alg == PSA_ALG_JPAKE) {
7724         psa_jpake_computation_stage_t *computation_stage =
7725             &operation->computation_stage.jpake;
7726 
7727         memset(computation_stage, 0, sizeof(*computation_stage));
7728         computation_stage->step = PSA_PAKE_STEP_KEY_SHARE;
7729     } else
7730 #endif /* PSA_WANT_ALG_JPAKE */
7731     {
7732         status = PSA_ERROR_NOT_SUPPORTED;
7733         goto exit;
7734     }
7735 
7736     operation->stage = PSA_PAKE_OPERATION_STAGE_COLLECT_INPUTS;
7737 
7738     return PSA_SUCCESS;
7739 exit:
7740     psa_pake_abort(operation);
7741     return status;
7742 }
7743 
7744 psa_status_t psa_pake_set_password_key(
7745     psa_pake_operation_t *operation,
7746     mbedtls_svc_key_id_t password)
7747 {
7748     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
7749     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
7750     psa_key_slot_t *slot = NULL;
7751     psa_key_attributes_t attributes;
7752     psa_key_type_t type;
7753 
7754     if (operation->stage != PSA_PAKE_OPERATION_STAGE_COLLECT_INPUTS) {
7755         status = PSA_ERROR_BAD_STATE;
7756         goto exit;
7757     }
7758 
7759     status = psa_get_and_lock_key_slot_with_policy(password, &slot,
7760                                                    PSA_KEY_USAGE_DERIVE,
7761                                                    operation->alg);
7762     if (status != PSA_SUCCESS) {
7763         goto exit;
7764     }
7765 
7766     attributes = (psa_key_attributes_t) {
7767         .core = slot->attr
7768     };
7769 
7770     type = psa_get_key_type(&attributes);
7771 
7772     if (type != PSA_KEY_TYPE_PASSWORD &&
7773         type != PSA_KEY_TYPE_PASSWORD_HASH) {
7774         status = PSA_ERROR_INVALID_ARGUMENT;
7775         goto exit;
7776     }
7777 
7778     operation->data.inputs.password = mbedtls_calloc(1, slot->key.bytes);
7779     if (operation->data.inputs.password == NULL) {
7780         status = PSA_ERROR_INSUFFICIENT_MEMORY;
7781         goto exit;
7782     }
7783 
7784     memcpy(operation->data.inputs.password, slot->key.data, slot->key.bytes);
7785     operation->data.inputs.password_len = slot->key.bytes;
7786     operation->data.inputs.attributes = attributes;
7787 exit:
7788     if (status != PSA_SUCCESS) {
7789         psa_pake_abort(operation);
7790     }
7791     unlock_status = psa_unlock_key_slot(slot);
7792     return (status == PSA_SUCCESS) ? unlock_status : status;
7793 }
7794 
7795 psa_status_t psa_pake_set_user(
7796     psa_pake_operation_t *operation,
7797     const uint8_t *user_id,
7798     size_t user_id_len)
7799 {
7800     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
7801 
7802     if (operation->stage != PSA_PAKE_OPERATION_STAGE_COLLECT_INPUTS) {
7803         status = PSA_ERROR_BAD_STATE;
7804         goto exit;
7805     }
7806 
7807     if (user_id_len == 0) {
7808         status = PSA_ERROR_INVALID_ARGUMENT;
7809         goto exit;
7810     }
7811 
7812     if (operation->data.inputs.user_len != 0) {
7813         status = PSA_ERROR_BAD_STATE;
7814         goto exit;
7815     }
7816 
7817     operation->data.inputs.user = mbedtls_calloc(1, user_id_len);
7818     if (operation->data.inputs.user == NULL) {
7819         status = PSA_ERROR_INSUFFICIENT_MEMORY;
7820         goto exit;
7821     }
7822 
7823     memcpy(operation->data.inputs.user, user_id, user_id_len);
7824     operation->data.inputs.user_len = user_id_len;
7825 
7826     return PSA_SUCCESS;
7827 exit:
7828     psa_pake_abort(operation);
7829     return status;
7830 }
7831 
7832 psa_status_t psa_pake_set_peer(
7833     psa_pake_operation_t *operation,
7834     const uint8_t *peer_id,
7835     size_t peer_id_len)
7836 {
7837     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
7838 
7839     if (operation->stage != PSA_PAKE_OPERATION_STAGE_COLLECT_INPUTS) {
7840         status = PSA_ERROR_BAD_STATE;
7841         goto exit;
7842     }
7843 
7844     if (peer_id_len == 0) {
7845         status = PSA_ERROR_INVALID_ARGUMENT;
7846         goto exit;
7847     }
7848 
7849     if (operation->data.inputs.peer_len != 0) {
7850         status = PSA_ERROR_BAD_STATE;
7851         goto exit;
7852     }
7853 
7854     operation->data.inputs.peer = mbedtls_calloc(1, peer_id_len);
7855     if (operation->data.inputs.peer == NULL) {
7856         status = PSA_ERROR_INSUFFICIENT_MEMORY;
7857         goto exit;
7858     }
7859 
7860     memcpy(operation->data.inputs.peer, peer_id, peer_id_len);
7861     operation->data.inputs.peer_len = peer_id_len;
7862 
7863     return PSA_SUCCESS;
7864 exit:
7865     psa_pake_abort(operation);
7866     return status;
7867 }
7868 
7869 psa_status_t psa_pake_set_role(
7870     psa_pake_operation_t *operation,
7871     psa_pake_role_t role)
7872 {
7873     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
7874 
7875     if (operation->stage != PSA_PAKE_OPERATION_STAGE_COLLECT_INPUTS) {
7876         status = PSA_ERROR_BAD_STATE;
7877         goto exit;
7878     }
7879 
7880     switch (operation->alg) {
7881 #if defined(PSA_WANT_ALG_JPAKE)
7882         case PSA_ALG_JPAKE:
7883             if (role == PSA_PAKE_ROLE_NONE) {
7884                 return PSA_SUCCESS;
7885             }
7886             status = PSA_ERROR_INVALID_ARGUMENT;
7887             break;
7888 #endif
7889         default:
7890             (void) role;
7891             status = PSA_ERROR_NOT_SUPPORTED;
7892             goto exit;
7893     }
7894 exit:
7895     psa_pake_abort(operation);
7896     return status;
7897 }
7898 
7899 /* Auxiliary function to convert core computation stage to single driver step. */
7900 #if defined(PSA_WANT_ALG_JPAKE)
7901 static psa_crypto_driver_pake_step_t convert_jpake_computation_stage_to_driver_step(
7902     psa_jpake_computation_stage_t *stage)
7903 {
7904     psa_crypto_driver_pake_step_t key_share_step;
7905     if (stage->round == PSA_JPAKE_FIRST) {
7906         int is_x1;
7907 
7908         if (stage->io_mode == PSA_JPAKE_OUTPUT) {
7909             is_x1 = (stage->outputs < 1);
7910         } else {
7911             is_x1 = (stage->inputs < 1);
7912         }
7913 
7914         key_share_step = is_x1 ?
7915                          PSA_JPAKE_X1_STEP_KEY_SHARE :
7916                          PSA_JPAKE_X2_STEP_KEY_SHARE;
7917     } else if (stage->round == PSA_JPAKE_SECOND) {
7918         key_share_step = (stage->io_mode == PSA_JPAKE_OUTPUT) ?
7919                          PSA_JPAKE_X2S_STEP_KEY_SHARE :
7920                          PSA_JPAKE_X4S_STEP_KEY_SHARE;
7921     } else {
7922         return PSA_JPAKE_STEP_INVALID;
7923     }
7924     return (psa_crypto_driver_pake_step_t) (key_share_step + stage->step - PSA_PAKE_STEP_KEY_SHARE);
7925 }
7926 #endif /* PSA_WANT_ALG_JPAKE */
7927 
7928 static psa_status_t psa_pake_complete_inputs(
7929     psa_pake_operation_t *operation)
7930 {
7931     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
7932     /* Create copy of the inputs on stack as inputs share memory
7933        with the driver context which will be setup by the driver. */
7934     psa_crypto_driver_pake_inputs_t inputs = operation->data.inputs;
7935 
7936     if (inputs.password_len == 0) {
7937         return PSA_ERROR_BAD_STATE;
7938     }
7939 
7940     if (operation->alg == PSA_ALG_JPAKE) {
7941         if (inputs.user_len == 0 || inputs.peer_len == 0) {
7942             return PSA_ERROR_BAD_STATE;
7943         }
7944     }
7945 
7946     /* Clear driver context */
7947     mbedtls_platform_zeroize(&operation->data, sizeof(operation->data));
7948 
7949     status = psa_driver_wrapper_pake_setup(operation, &inputs);
7950 
7951     /* Driver is responsible for creating its own copy of the password. */
7952     mbedtls_zeroize_and_free(inputs.password, inputs.password_len);
7953 
7954     /* User and peer are translated to role. */
7955     mbedtls_free(inputs.user);
7956     mbedtls_free(inputs.peer);
7957 
7958     if (status == PSA_SUCCESS) {
7959 #if defined(PSA_WANT_ALG_JPAKE)
7960         if (operation->alg == PSA_ALG_JPAKE) {
7961             operation->stage = PSA_PAKE_OPERATION_STAGE_COMPUTATION;
7962         } else
7963 #endif /* PSA_WANT_ALG_JPAKE */
7964         {
7965             status = PSA_ERROR_NOT_SUPPORTED;
7966         }
7967     }
7968     return status;
7969 }
7970 
7971 #if defined(PSA_WANT_ALG_JPAKE)
7972 static psa_status_t psa_jpake_prologue(
7973     psa_pake_operation_t *operation,
7974     psa_pake_step_t step,
7975     psa_jpake_io_mode_t io_mode)
7976 {
7977     if (step != PSA_PAKE_STEP_KEY_SHARE &&
7978         step != PSA_PAKE_STEP_ZK_PUBLIC &&
7979         step != PSA_PAKE_STEP_ZK_PROOF) {
7980         return PSA_ERROR_INVALID_ARGUMENT;
7981     }
7982 
7983     psa_jpake_computation_stage_t *computation_stage =
7984         &operation->computation_stage.jpake;
7985 
7986     if (computation_stage->round != PSA_JPAKE_FIRST &&
7987         computation_stage->round != PSA_JPAKE_SECOND) {
7988         return PSA_ERROR_BAD_STATE;
7989     }
7990 
7991     /* Check that the step we are given is the one we were expecting */
7992     if (step != computation_stage->step) {
7993         return PSA_ERROR_BAD_STATE;
7994     }
7995 
7996     if (step == PSA_PAKE_STEP_KEY_SHARE &&
7997         computation_stage->inputs == 0 &&
7998         computation_stage->outputs == 0) {
7999         /* Start of the round, so function decides whether we are inputting
8000          * or outputting */
8001         computation_stage->io_mode = io_mode;
8002     } else if (computation_stage->io_mode != io_mode) {
8003         /* Middle of the round so the mode we are in must match the function
8004          * called by the user */
8005         return PSA_ERROR_BAD_STATE;
8006     }
8007 
8008     return PSA_SUCCESS;
8009 }
8010 
8011 static psa_status_t psa_jpake_epilogue(
8012     psa_pake_operation_t *operation,
8013     psa_jpake_io_mode_t io_mode)
8014 {
8015     psa_jpake_computation_stage_t *stage =
8016         &operation->computation_stage.jpake;
8017 
8018     if (stage->step == PSA_PAKE_STEP_ZK_PROOF) {
8019         /* End of an input/output */
8020         if (io_mode == PSA_JPAKE_INPUT) {
8021             stage->inputs++;
8022             if (stage->inputs == PSA_JPAKE_EXPECTED_INPUTS(stage->round)) {
8023                 stage->io_mode = PSA_JPAKE_OUTPUT;
8024             }
8025         }
8026         if (io_mode == PSA_JPAKE_OUTPUT) {
8027             stage->outputs++;
8028             if (stage->outputs == PSA_JPAKE_EXPECTED_OUTPUTS(stage->round)) {
8029                 stage->io_mode = PSA_JPAKE_INPUT;
8030             }
8031         }
8032         if (stage->inputs == PSA_JPAKE_EXPECTED_INPUTS(stage->round) &&
8033             stage->outputs == PSA_JPAKE_EXPECTED_OUTPUTS(stage->round)) {
8034             /* End of a round, move to the next round */
8035             stage->inputs = 0;
8036             stage->outputs = 0;
8037             stage->round++;
8038         }
8039         stage->step = PSA_PAKE_STEP_KEY_SHARE;
8040     } else {
8041         stage->step++;
8042     }
8043     return PSA_SUCCESS;
8044 }
8045 
8046 #endif /* PSA_WANT_ALG_JPAKE */
8047 
8048 psa_status_t psa_pake_output(
8049     psa_pake_operation_t *operation,
8050     psa_pake_step_t step,
8051     uint8_t *output,
8052     size_t output_size,
8053     size_t *output_length)
8054 {
8055     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
8056     psa_crypto_driver_pake_step_t driver_step = PSA_JPAKE_STEP_INVALID;
8057     *output_length = 0;
8058 
8059     if (operation->stage == PSA_PAKE_OPERATION_STAGE_COLLECT_INPUTS) {
8060         status = psa_pake_complete_inputs(operation);
8061         if (status != PSA_SUCCESS) {
8062             goto exit;
8063         }
8064     }
8065 
8066     if (operation->stage != PSA_PAKE_OPERATION_STAGE_COMPUTATION) {
8067         status = PSA_ERROR_BAD_STATE;
8068         goto exit;
8069     }
8070 
8071     if (output_size == 0) {
8072         status = PSA_ERROR_INVALID_ARGUMENT;
8073         goto exit;
8074     }
8075 
8076     switch (operation->alg) {
8077 #if defined(PSA_WANT_ALG_JPAKE)
8078         case PSA_ALG_JPAKE:
8079             status = psa_jpake_prologue(operation, step, PSA_JPAKE_OUTPUT);
8080             if (status != PSA_SUCCESS) {
8081                 goto exit;
8082             }
8083             driver_step = convert_jpake_computation_stage_to_driver_step(
8084                 &operation->computation_stage.jpake);
8085             break;
8086 #endif /* PSA_WANT_ALG_JPAKE */
8087         default:
8088             (void) step;
8089             status = PSA_ERROR_NOT_SUPPORTED;
8090             goto exit;
8091     }
8092 
8093     status = psa_driver_wrapper_pake_output(operation, driver_step,
8094                                             output, output_size, output_length);
8095 
8096     if (status != PSA_SUCCESS) {
8097         goto exit;
8098     }
8099 
8100     switch (operation->alg) {
8101 #if defined(PSA_WANT_ALG_JPAKE)
8102         case PSA_ALG_JPAKE:
8103             status = psa_jpake_epilogue(operation, PSA_JPAKE_OUTPUT);
8104             if (status != PSA_SUCCESS) {
8105                 goto exit;
8106             }
8107             break;
8108 #endif /* PSA_WANT_ALG_JPAKE */
8109         default:
8110             status = PSA_ERROR_NOT_SUPPORTED;
8111             goto exit;
8112     }
8113 
8114     return PSA_SUCCESS;
8115 exit:
8116     psa_pake_abort(operation);
8117     return status;
8118 }
8119 
8120 psa_status_t psa_pake_input(
8121     psa_pake_operation_t *operation,
8122     psa_pake_step_t step,
8123     const uint8_t *input,
8124     size_t input_length)
8125 {
8126     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
8127     psa_crypto_driver_pake_step_t driver_step = PSA_JPAKE_STEP_INVALID;
8128     const size_t max_input_length = (size_t) PSA_PAKE_INPUT_SIZE(operation->alg,
8129                                                                  operation->primitive,
8130                                                                  step);
8131 
8132     if (operation->stage == PSA_PAKE_OPERATION_STAGE_COLLECT_INPUTS) {
8133         status = psa_pake_complete_inputs(operation);
8134         if (status != PSA_SUCCESS) {
8135             goto exit;
8136         }
8137     }
8138 
8139     if (operation->stage != PSA_PAKE_OPERATION_STAGE_COMPUTATION) {
8140         status =  PSA_ERROR_BAD_STATE;
8141         goto exit;
8142     }
8143 
8144     if (input_length == 0 || input_length > max_input_length) {
8145         status = PSA_ERROR_INVALID_ARGUMENT;
8146         goto exit;
8147     }
8148 
8149     switch (operation->alg) {
8150 #if defined(PSA_WANT_ALG_JPAKE)
8151         case PSA_ALG_JPAKE:
8152             status = psa_jpake_prologue(operation, step, PSA_JPAKE_INPUT);
8153             if (status != PSA_SUCCESS) {
8154                 goto exit;
8155             }
8156             driver_step = convert_jpake_computation_stage_to_driver_step(
8157                 &operation->computation_stage.jpake);
8158             break;
8159 #endif /* PSA_WANT_ALG_JPAKE */
8160         default:
8161             (void) step;
8162             status = PSA_ERROR_NOT_SUPPORTED;
8163             goto exit;
8164     }
8165 
8166     status = psa_driver_wrapper_pake_input(operation, driver_step,
8167                                            input, input_length);
8168 
8169     if (status != PSA_SUCCESS) {
8170         goto exit;
8171     }
8172 
8173     switch (operation->alg) {
8174 #if defined(PSA_WANT_ALG_JPAKE)
8175         case PSA_ALG_JPAKE:
8176             status = psa_jpake_epilogue(operation, PSA_JPAKE_INPUT);
8177             if (status != PSA_SUCCESS) {
8178                 goto exit;
8179             }
8180             break;
8181 #endif /* PSA_WANT_ALG_JPAKE */
8182         default:
8183             status = PSA_ERROR_NOT_SUPPORTED;
8184             goto exit;
8185     }
8186 
8187     return PSA_SUCCESS;
8188 exit:
8189     psa_pake_abort(operation);
8190     return status;
8191 }
8192 
8193 psa_status_t psa_pake_get_implicit_key(
8194     psa_pake_operation_t *operation,
8195     psa_key_derivation_operation_t *output)
8196 {
8197     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
8198     psa_status_t abort_status = PSA_ERROR_CORRUPTION_DETECTED;
8199     uint8_t shared_key[MBEDTLS_PSA_JPAKE_BUFFER_SIZE];
8200     size_t shared_key_len = 0;
8201 
8202     if (operation->stage != PSA_PAKE_OPERATION_STAGE_COMPUTATION) {
8203         status = PSA_ERROR_BAD_STATE;
8204         goto exit;
8205     }
8206 
8207 #if defined(PSA_WANT_ALG_JPAKE)
8208     if (operation->alg == PSA_ALG_JPAKE) {
8209         psa_jpake_computation_stage_t *computation_stage =
8210             &operation->computation_stage.jpake;
8211         if (computation_stage->round != PSA_JPAKE_FINISHED) {
8212             status = PSA_ERROR_BAD_STATE;
8213             goto exit;
8214         }
8215     } else
8216 #endif /* PSA_WANT_ALG_JPAKE */
8217     {
8218         status = PSA_ERROR_NOT_SUPPORTED;
8219         goto exit;
8220     }
8221 
8222     status = psa_driver_wrapper_pake_get_implicit_key(operation,
8223                                                       shared_key,
8224                                                       sizeof(shared_key),
8225                                                       &shared_key_len);
8226 
8227     if (status != PSA_SUCCESS) {
8228         goto exit;
8229     }
8230 
8231     status = psa_key_derivation_input_bytes(output,
8232                                             PSA_KEY_DERIVATION_INPUT_SECRET,
8233                                             shared_key,
8234                                             shared_key_len);
8235 
8236     mbedtls_platform_zeroize(shared_key, sizeof(shared_key));
8237 exit:
8238     abort_status = psa_pake_abort(operation);
8239     return status == PSA_SUCCESS ? abort_status : status;
8240 }
8241 
8242 psa_status_t psa_pake_abort(
8243     psa_pake_operation_t *operation)
8244 {
8245     psa_status_t status = PSA_SUCCESS;
8246 
8247     if (operation->stage == PSA_PAKE_OPERATION_STAGE_COMPUTATION) {
8248         status = psa_driver_wrapper_pake_abort(operation);
8249     }
8250 
8251     if (operation->stage == PSA_PAKE_OPERATION_STAGE_COLLECT_INPUTS) {
8252         if (operation->data.inputs.password != NULL) {
8253             mbedtls_zeroize_and_free(operation->data.inputs.password,
8254                                      operation->data.inputs.password_len);
8255         }
8256         if (operation->data.inputs.user != NULL) {
8257             mbedtls_free(operation->data.inputs.user);
8258         }
8259         if (operation->data.inputs.peer != NULL) {
8260             mbedtls_free(operation->data.inputs.peer);
8261         }
8262     }
8263     memset(operation, 0, sizeof(psa_pake_operation_t));
8264 
8265     return status;
8266 }
8267 #endif /* PSA_WANT_ALG_SOME_PAKE */
8268 
8269 #endif /* MBEDTLS_PSA_CRYPTO_C */
8270