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