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