xref: /optee_os/lib/libmbedtls/mbedtls/library/psa_crypto.c (revision 5d5d7d0b1c038a6836be9f0b38585f5aa6a4dd01)
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     /* Ensure all of the context is zeroized, since PSA_HASH_OPERATION_INIT only
2404      * directly zeroes the int-sized dummy member of the context union. */
2405     memset(&operation->ctx, 0, sizeof(operation->ctx));
2406 
2407     status = psa_driver_wrapper_hash_setup(operation, alg);
2408 
2409 exit:
2410     if (status != PSA_SUCCESS) {
2411         psa_hash_abort(operation);
2412     }
2413 
2414     return status;
2415 }
2416 
2417 psa_status_t psa_hash_update(psa_hash_operation_t *operation,
2418                              const uint8_t *input_external,
2419                              size_t input_length)
2420 {
2421     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2422     LOCAL_INPUT_DECLARE(input_external, input);
2423 
2424     if (operation->id == 0) {
2425         status = PSA_ERROR_BAD_STATE;
2426         goto exit;
2427     }
2428 
2429     /* Don't require hash implementations to behave correctly on a
2430      * zero-length input, which may have an invalid pointer. */
2431     if (input_length == 0) {
2432         return PSA_SUCCESS;
2433     }
2434 
2435     LOCAL_INPUT_ALLOC(input_external, input_length, input);
2436     status = psa_driver_wrapper_hash_update(operation, input, input_length);
2437 
2438 exit:
2439     if (status != PSA_SUCCESS) {
2440         psa_hash_abort(operation);
2441     }
2442 
2443     LOCAL_INPUT_FREE(input_external, input);
2444     return status;
2445 }
2446 
2447 static psa_status_t psa_hash_finish_internal(psa_hash_operation_t *operation,
2448                                              uint8_t *hash,
2449                                              size_t hash_size,
2450                                              size_t *hash_length)
2451 {
2452     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2453 
2454     *hash_length = 0;
2455     if (operation->id == 0) {
2456         return PSA_ERROR_BAD_STATE;
2457     }
2458 
2459     status = psa_driver_wrapper_hash_finish(
2460         operation, hash, hash_size, hash_length);
2461     psa_hash_abort(operation);
2462 
2463     return status;
2464 }
2465 
2466 psa_status_t psa_hash_finish(psa_hash_operation_t *operation,
2467                              uint8_t *hash_external,
2468                              size_t hash_size,
2469                              size_t *hash_length)
2470 {
2471     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2472     LOCAL_OUTPUT_DECLARE(hash_external, hash);
2473 
2474     LOCAL_OUTPUT_ALLOC(hash_external, hash_size, hash);
2475     status = psa_hash_finish_internal(operation, hash, hash_size, hash_length);
2476 
2477 #if !defined(MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS)
2478 exit:
2479 #endif
2480     LOCAL_OUTPUT_FREE(hash_external, hash);
2481     return status;
2482 }
2483 
2484 psa_status_t psa_hash_verify(psa_hash_operation_t *operation,
2485                              const uint8_t *hash_external,
2486                              size_t hash_length)
2487 {
2488     uint8_t actual_hash[PSA_HASH_MAX_SIZE];
2489     size_t actual_hash_length;
2490     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2491     LOCAL_INPUT_DECLARE(hash_external, hash);
2492 
2493     status = psa_hash_finish_internal(
2494         operation,
2495         actual_hash, sizeof(actual_hash),
2496         &actual_hash_length);
2497 
2498     if (status != PSA_SUCCESS) {
2499         goto exit;
2500     }
2501 
2502     if (actual_hash_length != hash_length) {
2503         status = PSA_ERROR_INVALID_SIGNATURE;
2504         goto exit;
2505     }
2506 
2507     LOCAL_INPUT_ALLOC(hash_external, hash_length, hash);
2508     if (mbedtls_ct_memcmp(hash, actual_hash, actual_hash_length) != 0) {
2509         status = PSA_ERROR_INVALID_SIGNATURE;
2510     }
2511 
2512 exit:
2513     mbedtls_platform_zeroize(actual_hash, sizeof(actual_hash));
2514     if (status != PSA_SUCCESS) {
2515         psa_hash_abort(operation);
2516     }
2517     LOCAL_INPUT_FREE(hash_external, hash);
2518     return status;
2519 }
2520 
2521 psa_status_t psa_hash_compute(psa_algorithm_t alg,
2522                               const uint8_t *input_external, size_t input_length,
2523                               uint8_t *hash_external, size_t hash_size,
2524                               size_t *hash_length)
2525 {
2526     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2527     LOCAL_INPUT_DECLARE(input_external, input);
2528     LOCAL_OUTPUT_DECLARE(hash_external, hash);
2529 
2530     *hash_length = 0;
2531     if (!PSA_ALG_IS_HASH(alg)) {
2532         return PSA_ERROR_INVALID_ARGUMENT;
2533     }
2534 
2535     LOCAL_INPUT_ALLOC(input_external, input_length, input);
2536     LOCAL_OUTPUT_ALLOC(hash_external, hash_size, hash);
2537     status = psa_driver_wrapper_hash_compute(alg, input, input_length,
2538                                              hash, hash_size, hash_length);
2539 
2540 #if !defined(MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS)
2541 exit:
2542 #endif
2543     LOCAL_INPUT_FREE(input_external, input);
2544     LOCAL_OUTPUT_FREE(hash_external, hash);
2545     return status;
2546 }
2547 
2548 psa_status_t psa_hash_compare(psa_algorithm_t alg,
2549                               const uint8_t *input_external, size_t input_length,
2550                               const uint8_t *hash_external, size_t hash_length)
2551 {
2552     uint8_t actual_hash[PSA_HASH_MAX_SIZE];
2553     size_t actual_hash_length;
2554     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2555 
2556     LOCAL_INPUT_DECLARE(input_external, input);
2557     LOCAL_INPUT_DECLARE(hash_external, hash);
2558 
2559     if (!PSA_ALG_IS_HASH(alg)) {
2560         status = PSA_ERROR_INVALID_ARGUMENT;
2561         return status;
2562     }
2563 
2564     LOCAL_INPUT_ALLOC(input_external, input_length, input);
2565     status = psa_driver_wrapper_hash_compute(
2566         alg, input, input_length,
2567         actual_hash, sizeof(actual_hash),
2568         &actual_hash_length);
2569     if (status != PSA_SUCCESS) {
2570         goto exit;
2571     }
2572     if (actual_hash_length != hash_length) {
2573         status = PSA_ERROR_INVALID_SIGNATURE;
2574         goto exit;
2575     }
2576 
2577     LOCAL_INPUT_ALLOC(hash_external, hash_length, hash);
2578     if (mbedtls_ct_memcmp(hash, actual_hash, actual_hash_length) != 0) {
2579         status = PSA_ERROR_INVALID_SIGNATURE;
2580     }
2581 
2582 exit:
2583     mbedtls_platform_zeroize(actual_hash, sizeof(actual_hash));
2584 
2585     LOCAL_INPUT_FREE(input_external, input);
2586     LOCAL_INPUT_FREE(hash_external, hash);
2587 
2588     return status;
2589 }
2590 
2591 psa_status_t psa_hash_clone(const psa_hash_operation_t *source_operation,
2592                             psa_hash_operation_t *target_operation)
2593 {
2594     if (source_operation->id == 0 ||
2595         target_operation->id != 0) {
2596         return PSA_ERROR_BAD_STATE;
2597     }
2598 
2599     psa_status_t status = psa_driver_wrapper_hash_clone(source_operation,
2600                                                         target_operation);
2601     if (status != PSA_SUCCESS) {
2602         psa_hash_abort(target_operation);
2603     }
2604 
2605     return status;
2606 }
2607 
2608 
2609 /****************************************************************/
2610 /* MAC */
2611 /****************************************************************/
2612 
2613 psa_status_t psa_mac_abort(psa_mac_operation_t *operation)
2614 {
2615     /* Aborting a non-active operation is allowed */
2616     if (operation->id == 0) {
2617         return PSA_SUCCESS;
2618     }
2619 
2620     psa_status_t status = psa_driver_wrapper_mac_abort(operation);
2621     operation->mac_size = 0;
2622     operation->is_sign = 0;
2623     operation->id = 0;
2624 
2625     return status;
2626 }
2627 
2628 static psa_status_t psa_mac_finalize_alg_and_key_validation(
2629     psa_algorithm_t alg,
2630     const psa_key_attributes_t *attributes,
2631     uint8_t *mac_size)
2632 {
2633     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2634     psa_key_type_t key_type = psa_get_key_type(attributes);
2635     size_t key_bits = psa_get_key_bits(attributes);
2636 
2637     if (!PSA_ALG_IS_MAC(alg)) {
2638         return PSA_ERROR_INVALID_ARGUMENT;
2639     }
2640 
2641     /* Validate the combination of key type and algorithm */
2642     status = psa_mac_key_can_do(alg, key_type);
2643     if (status != PSA_SUCCESS) {
2644         return status;
2645     }
2646 
2647     /* Get the output length for the algorithm and key combination */
2648     *mac_size = PSA_MAC_LENGTH(key_type, key_bits, alg);
2649 
2650     if (*mac_size < 4) {
2651         /* A very short MAC is too short for security since it can be
2652          * brute-forced. Ancient protocols with 32-bit MACs do exist,
2653          * so we make this our minimum, even though 32 bits is still
2654          * too small for security. */
2655         return PSA_ERROR_NOT_SUPPORTED;
2656     }
2657 
2658     if (*mac_size > PSA_MAC_LENGTH(key_type, key_bits,
2659                                    PSA_ALG_FULL_LENGTH_MAC(alg))) {
2660         /* It's impossible to "truncate" to a larger length than the full length
2661          * of the algorithm. */
2662         return PSA_ERROR_INVALID_ARGUMENT;
2663     }
2664 
2665     if (*mac_size > PSA_MAC_MAX_SIZE) {
2666         /* PSA_MAC_LENGTH returns the correct length even for a MAC algorithm
2667          * that is disabled in the compile-time configuration. The result can
2668          * therefore be larger than PSA_MAC_MAX_SIZE, which does take the
2669          * configuration into account. In this case, force a return of
2670          * PSA_ERROR_NOT_SUPPORTED here. Otherwise psa_mac_verify(), or
2671          * psa_mac_compute(mac_size=PSA_MAC_MAX_SIZE), would return
2672          * PSA_ERROR_BUFFER_TOO_SMALL for an unsupported algorithm whose MAC size
2673          * is larger than PSA_MAC_MAX_SIZE, which is misleading and which breaks
2674          * systematically generated tests. */
2675         return PSA_ERROR_NOT_SUPPORTED;
2676     }
2677 
2678     return PSA_SUCCESS;
2679 }
2680 
2681 static psa_status_t psa_mac_setup(psa_mac_operation_t *operation,
2682                                   mbedtls_svc_key_id_t key,
2683                                   psa_algorithm_t alg,
2684                                   int is_sign)
2685 {
2686     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2687     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
2688     psa_key_slot_t *slot = NULL;
2689 
2690     /* A context must be freshly initialized before it can be set up. */
2691     if (operation->id != 0) {
2692         status = PSA_ERROR_BAD_STATE;
2693         goto exit;
2694     }
2695 
2696     status = psa_get_and_lock_key_slot_with_policy(
2697         key,
2698         &slot,
2699         is_sign ? PSA_KEY_USAGE_SIGN_MESSAGE : PSA_KEY_USAGE_VERIFY_MESSAGE,
2700         alg);
2701     if (status != PSA_SUCCESS) {
2702         goto exit;
2703     }
2704 
2705     status = psa_mac_finalize_alg_and_key_validation(alg, &slot->attr,
2706                                                      &operation->mac_size);
2707     if (status != PSA_SUCCESS) {
2708         goto exit;
2709     }
2710 
2711     operation->is_sign = is_sign;
2712     /* Dispatch the MAC setup call with validated input */
2713     if (is_sign) {
2714         status = psa_driver_wrapper_mac_sign_setup(operation,
2715                                                    &slot->attr,
2716                                                    slot->key.data,
2717                                                    slot->key.bytes,
2718                                                    alg);
2719     } else {
2720         status = psa_driver_wrapper_mac_verify_setup(operation,
2721                                                      &slot->attr,
2722                                                      slot->key.data,
2723                                                      slot->key.bytes,
2724                                                      alg);
2725     }
2726 
2727 exit:
2728     if (status != PSA_SUCCESS) {
2729         psa_mac_abort(operation);
2730     }
2731 
2732     unlock_status = psa_unregister_read_under_mutex(slot);
2733 
2734     return (status == PSA_SUCCESS) ? unlock_status : status;
2735 }
2736 
2737 psa_status_t psa_mac_sign_setup(psa_mac_operation_t *operation,
2738                                 mbedtls_svc_key_id_t key,
2739                                 psa_algorithm_t alg)
2740 {
2741     return psa_mac_setup(operation, key, alg, 1);
2742 }
2743 
2744 psa_status_t psa_mac_verify_setup(psa_mac_operation_t *operation,
2745                                   mbedtls_svc_key_id_t key,
2746                                   psa_algorithm_t alg)
2747 {
2748     return psa_mac_setup(operation, key, alg, 0);
2749 }
2750 
2751 psa_status_t psa_mac_update(psa_mac_operation_t *operation,
2752                             const uint8_t *input_external,
2753                             size_t input_length)
2754 {
2755     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2756     LOCAL_INPUT_DECLARE(input_external, input);
2757 
2758     if (operation->id == 0) {
2759         status = PSA_ERROR_BAD_STATE;
2760         return status;
2761     }
2762 
2763     /* Don't require hash implementations to behave correctly on a
2764      * zero-length input, which may have an invalid pointer. */
2765     if (input_length == 0) {
2766         status = PSA_SUCCESS;
2767         return status;
2768     }
2769 
2770     LOCAL_INPUT_ALLOC(input_external, input_length, input);
2771     status = psa_driver_wrapper_mac_update(operation, input, input_length);
2772 
2773     if (status != PSA_SUCCESS) {
2774         psa_mac_abort(operation);
2775     }
2776 
2777 #if !defined(MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS)
2778 exit:
2779 #endif
2780     LOCAL_INPUT_FREE(input_external, input);
2781 
2782     return status;
2783 }
2784 
2785 psa_status_t psa_mac_sign_finish(psa_mac_operation_t *operation,
2786                                  uint8_t *mac_external,
2787                                  size_t mac_size,
2788                                  size_t *mac_length)
2789 {
2790     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2791     psa_status_t abort_status = PSA_ERROR_CORRUPTION_DETECTED;
2792     LOCAL_OUTPUT_DECLARE(mac_external, mac);
2793     LOCAL_OUTPUT_ALLOC(mac_external, mac_size, mac);
2794 
2795     if (operation->id == 0) {
2796         status = PSA_ERROR_BAD_STATE;
2797         goto exit;
2798     }
2799 
2800     if (!operation->is_sign) {
2801         status = PSA_ERROR_BAD_STATE;
2802         goto exit;
2803     }
2804 
2805     /* Sanity check. This will guarantee that mac_size != 0 (and so mac != NULL)
2806      * once all the error checks are done. */
2807     if (operation->mac_size == 0) {
2808         status = PSA_ERROR_BAD_STATE;
2809         goto exit;
2810     }
2811 
2812     if (mac_size < operation->mac_size) {
2813         status = PSA_ERROR_BUFFER_TOO_SMALL;
2814         goto exit;
2815     }
2816 
2817 
2818     status = psa_driver_wrapper_mac_sign_finish(operation,
2819                                                 mac, operation->mac_size,
2820                                                 mac_length);
2821 
2822 exit:
2823     /* In case of success, set the potential excess room in the output buffer
2824      * to an invalid value, to avoid potentially leaking a longer MAC.
2825      * In case of error, set the output length and content to a safe default,
2826      * such that in case the caller misses an error check, the output would be
2827      * an unachievable MAC.
2828      */
2829     if (status != PSA_SUCCESS) {
2830         *mac_length = mac_size;
2831         operation->mac_size = 0;
2832     }
2833 
2834     if (mac != NULL) {
2835         psa_wipe_tag_output_buffer(mac, status, mac_size, *mac_length);
2836     }
2837 
2838     abort_status = psa_mac_abort(operation);
2839     LOCAL_OUTPUT_FREE(mac_external, mac);
2840 
2841     return status == PSA_SUCCESS ? abort_status : status;
2842 }
2843 
2844 psa_status_t psa_mac_verify_finish(psa_mac_operation_t *operation,
2845                                    const uint8_t *mac_external,
2846                                    size_t mac_length)
2847 {
2848     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2849     psa_status_t abort_status = PSA_ERROR_CORRUPTION_DETECTED;
2850     LOCAL_INPUT_DECLARE(mac_external, mac);
2851 
2852     if (operation->id == 0) {
2853         status = PSA_ERROR_BAD_STATE;
2854         goto exit;
2855     }
2856 
2857     if (operation->is_sign) {
2858         status = PSA_ERROR_BAD_STATE;
2859         goto exit;
2860     }
2861 
2862     if (operation->mac_size != mac_length) {
2863         status = PSA_ERROR_INVALID_SIGNATURE;
2864         goto exit;
2865     }
2866 
2867     LOCAL_INPUT_ALLOC(mac_external, mac_length, mac);
2868     status = psa_driver_wrapper_mac_verify_finish(operation,
2869                                                   mac, mac_length);
2870 
2871 exit:
2872     abort_status = psa_mac_abort(operation);
2873     LOCAL_INPUT_FREE(mac_external, mac);
2874 
2875     return status == PSA_SUCCESS ? abort_status : status;
2876 }
2877 
2878 static psa_status_t psa_mac_compute_internal(mbedtls_svc_key_id_t key,
2879                                              psa_algorithm_t alg,
2880                                              const uint8_t *input,
2881                                              size_t input_length,
2882                                              uint8_t *mac,
2883                                              size_t mac_size,
2884                                              size_t *mac_length,
2885                                              int is_sign)
2886 {
2887     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2888     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
2889     psa_key_slot_t *slot;
2890     uint8_t operation_mac_size = 0;
2891 
2892     status = psa_get_and_lock_key_slot_with_policy(
2893         key,
2894         &slot,
2895         is_sign ? PSA_KEY_USAGE_SIGN_MESSAGE : PSA_KEY_USAGE_VERIFY_MESSAGE,
2896         alg);
2897     if (status != PSA_SUCCESS) {
2898         goto exit;
2899     }
2900 
2901     status = psa_mac_finalize_alg_and_key_validation(alg, &slot->attr,
2902                                                      &operation_mac_size);
2903     if (status != PSA_SUCCESS) {
2904         goto exit;
2905     }
2906 
2907     if (mac_size < operation_mac_size) {
2908         status = PSA_ERROR_BUFFER_TOO_SMALL;
2909         goto exit;
2910     }
2911 
2912     status = psa_driver_wrapper_mac_compute(
2913         &slot->attr,
2914         slot->key.data, slot->key.bytes,
2915         alg,
2916         input, input_length,
2917         mac, operation_mac_size, mac_length);
2918 
2919 exit:
2920     /* In case of success, set the potential excess room in the output buffer
2921      * to an invalid value, to avoid potentially leaking a longer MAC.
2922      * In case of error, set the output length and content to a safe default,
2923      * such that in case the caller misses an error check, the output would be
2924      * an unachievable MAC.
2925      */
2926     if (status != PSA_SUCCESS) {
2927         *mac_length = mac_size;
2928         operation_mac_size = 0;
2929     }
2930 
2931     psa_wipe_tag_output_buffer(mac, status, mac_size, *mac_length);
2932 
2933     unlock_status = psa_unregister_read_under_mutex(slot);
2934 
2935     return (status == PSA_SUCCESS) ? unlock_status : status;
2936 }
2937 
2938 psa_status_t psa_mac_compute(mbedtls_svc_key_id_t key,
2939                              psa_algorithm_t alg,
2940                              const uint8_t *input_external,
2941                              size_t input_length,
2942                              uint8_t *mac_external,
2943                              size_t mac_size,
2944                              size_t *mac_length)
2945 {
2946     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2947     LOCAL_INPUT_DECLARE(input_external, input);
2948     LOCAL_OUTPUT_DECLARE(mac_external, mac);
2949 
2950     LOCAL_INPUT_ALLOC(input_external, input_length, input);
2951     LOCAL_OUTPUT_ALLOC(mac_external, mac_size, mac);
2952     status = psa_mac_compute_internal(key, alg,
2953                                       input, input_length,
2954                                       mac, mac_size, mac_length, 1);
2955 
2956 #if !defined(MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS)
2957 exit:
2958 #endif
2959     LOCAL_INPUT_FREE(input_external, input);
2960     LOCAL_OUTPUT_FREE(mac_external, mac);
2961 
2962     return status;
2963 }
2964 
2965 psa_status_t psa_mac_verify(mbedtls_svc_key_id_t key,
2966                             psa_algorithm_t alg,
2967                             const uint8_t *input_external,
2968                             size_t input_length,
2969                             const uint8_t *mac_external,
2970                             size_t mac_length)
2971 {
2972     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2973     uint8_t actual_mac[PSA_MAC_MAX_SIZE];
2974     size_t actual_mac_length;
2975     LOCAL_INPUT_DECLARE(input_external, input);
2976     LOCAL_INPUT_DECLARE(mac_external, mac);
2977 
2978     LOCAL_INPUT_ALLOC(input_external, input_length, input);
2979     status = psa_mac_compute_internal(key, alg,
2980                                       input, input_length,
2981                                       actual_mac, sizeof(actual_mac),
2982                                       &actual_mac_length, 0);
2983     if (status != PSA_SUCCESS) {
2984         goto exit;
2985     }
2986 
2987     if (mac_length != actual_mac_length) {
2988         status = PSA_ERROR_INVALID_SIGNATURE;
2989         goto exit;
2990     }
2991 
2992     LOCAL_INPUT_ALLOC(mac_external, mac_length, mac);
2993     if (mbedtls_ct_memcmp(mac, actual_mac, actual_mac_length) != 0) {
2994         status = PSA_ERROR_INVALID_SIGNATURE;
2995         goto exit;
2996     }
2997 
2998 exit:
2999     mbedtls_platform_zeroize(actual_mac, sizeof(actual_mac));
3000     LOCAL_INPUT_FREE(input_external, input);
3001     LOCAL_INPUT_FREE(mac_external, mac);
3002 
3003     return status;
3004 }
3005 
3006 /****************************************************************/
3007 /* Asymmetric cryptography */
3008 /****************************************************************/
3009 
3010 static psa_status_t psa_sign_verify_check_alg(int input_is_message,
3011                                               psa_algorithm_t alg)
3012 {
3013     if (input_is_message) {
3014         if (!PSA_ALG_IS_SIGN_MESSAGE(alg)) {
3015             return PSA_ERROR_INVALID_ARGUMENT;
3016         }
3017     }
3018 
3019     psa_algorithm_t hash_alg = 0;
3020     if (PSA_ALG_IS_SIGN_HASH(alg)) {
3021         hash_alg = PSA_ALG_SIGN_GET_HASH(alg);
3022     }
3023 
3024     /* Now hash_alg==0 if alg by itself doesn't need a hash.
3025      * This is good enough for sign-hash, but a guaranteed failure for
3026      * sign-message which needs to hash first for all algorithms
3027      * supported at the moment. */
3028 
3029     if (hash_alg == 0 && input_is_message) {
3030         return PSA_ERROR_INVALID_ARGUMENT;
3031     }
3032     if (hash_alg == PSA_ALG_ANY_HASH) {
3033         return PSA_ERROR_INVALID_ARGUMENT;
3034     }
3035     /* Give up immediately if the hash is not supported. This has
3036      * several advantages:
3037      * - For mechanisms that don't use the hash at all (e.g.
3038      *   ECDSA verification, randomized ECDSA signature), without
3039      *   this check, the operation would succeed even though it has
3040      *   been given an invalid argument. This would not be insecure
3041      *   since the hash was not necessary, but it would be weird.
3042      * - For mechanisms that do use the hash, we avoid an error
3043      *   deep inside the execution. In principle this doesn't matter,
3044      *   but there is a little more risk of a bug in error handling
3045      *   deep inside than in this preliminary check.
3046      * - When calling a driver, the driver might be capable of using
3047      *   a hash that the core doesn't support. This could potentially
3048      *   result in a buffer overflow if the hash is larger than the
3049      *   maximum hash size assumed by the core.
3050      * - Returning a consistent error makes it possible to test
3051      *   not-supported hashes in a consistent way.
3052      */
3053     if (hash_alg != 0 && !is_hash_supported(hash_alg)) {
3054         return PSA_ERROR_NOT_SUPPORTED;
3055     }
3056 
3057     return PSA_SUCCESS;
3058 }
3059 
3060 static psa_status_t psa_sign_internal(mbedtls_svc_key_id_t key,
3061                                       int input_is_message,
3062                                       psa_algorithm_t alg,
3063                                       const uint8_t *input,
3064                                       size_t input_length,
3065                                       uint8_t *signature,
3066                                       size_t signature_size,
3067                                       size_t *signature_length)
3068 {
3069     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3070     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
3071     psa_key_slot_t *slot;
3072 
3073     *signature_length = 0;
3074 
3075     status = psa_sign_verify_check_alg(input_is_message, alg);
3076     if (status != PSA_SUCCESS) {
3077         return status;
3078     }
3079 
3080     /* Immediately reject a zero-length signature buffer. This guarantees
3081      * that signature must be a valid pointer. (On the other hand, the input
3082      * buffer can in principle be empty since it doesn't actually have
3083      * to be a hash.) */
3084     if (signature_size == 0) {
3085         return PSA_ERROR_BUFFER_TOO_SMALL;
3086     }
3087 
3088     status = psa_get_and_lock_key_slot_with_policy(
3089         key, &slot,
3090         input_is_message ? PSA_KEY_USAGE_SIGN_MESSAGE :
3091         PSA_KEY_USAGE_SIGN_HASH,
3092         alg);
3093 
3094     if (status != PSA_SUCCESS) {
3095         goto exit;
3096     }
3097 
3098     if (!PSA_KEY_TYPE_IS_KEY_PAIR(slot->attr.type)) {
3099         status = PSA_ERROR_INVALID_ARGUMENT;
3100         goto exit;
3101     }
3102 
3103     if (input_is_message) {
3104         status = psa_driver_wrapper_sign_message(
3105             &slot->attr, slot->key.data, slot->key.bytes,
3106             alg, input, input_length,
3107             signature, signature_size, signature_length);
3108     } else {
3109 
3110         status = psa_driver_wrapper_sign_hash(
3111             &slot->attr, slot->key.data, slot->key.bytes,
3112             alg, input, input_length,
3113             signature, signature_size, signature_length);
3114     }
3115 
3116 
3117 exit:
3118     psa_wipe_tag_output_buffer(signature, status, signature_size,
3119                                *signature_length);
3120 
3121     unlock_status = psa_unregister_read_under_mutex(slot);
3122 
3123     return (status == PSA_SUCCESS) ? unlock_status : status;
3124 }
3125 
3126 static psa_status_t psa_verify_internal(mbedtls_svc_key_id_t key,
3127                                         int input_is_message,
3128                                         psa_algorithm_t alg,
3129                                         const uint8_t *input,
3130                                         size_t input_length,
3131                                         const uint8_t *signature,
3132                                         size_t signature_length)
3133 {
3134     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3135     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
3136     psa_key_slot_t *slot;
3137 
3138     status = psa_sign_verify_check_alg(input_is_message, alg);
3139     if (status != PSA_SUCCESS) {
3140         return status;
3141     }
3142 
3143     status = psa_get_and_lock_key_slot_with_policy(
3144         key, &slot,
3145         input_is_message ? PSA_KEY_USAGE_VERIFY_MESSAGE :
3146         PSA_KEY_USAGE_VERIFY_HASH,
3147         alg);
3148 
3149     if (status != PSA_SUCCESS) {
3150         return status;
3151     }
3152 
3153     if (input_is_message) {
3154         status = psa_driver_wrapper_verify_message(
3155             &slot->attr, slot->key.data, slot->key.bytes,
3156             alg, input, input_length,
3157             signature, signature_length);
3158     } else {
3159         status = psa_driver_wrapper_verify_hash(
3160             &slot->attr, slot->key.data, slot->key.bytes,
3161             alg, input, input_length,
3162             signature, signature_length);
3163     }
3164 
3165     unlock_status = psa_unregister_read_under_mutex(slot);
3166 
3167     return (status == PSA_SUCCESS) ? unlock_status : status;
3168 
3169 }
3170 
3171 psa_status_t psa_sign_message_builtin(
3172     const psa_key_attributes_t *attributes,
3173     const uint8_t *key_buffer,
3174     size_t key_buffer_size,
3175     psa_algorithm_t alg,
3176     const uint8_t *input,
3177     size_t input_length,
3178     uint8_t *signature,
3179     size_t signature_size,
3180     size_t *signature_length)
3181 {
3182     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3183 
3184     if (PSA_ALG_IS_SIGN_HASH(alg)) {
3185         size_t hash_length;
3186         uint8_t hash[PSA_HASH_MAX_SIZE];
3187 
3188         status = psa_driver_wrapper_hash_compute(
3189             PSA_ALG_SIGN_GET_HASH(alg),
3190             input, input_length,
3191             hash, sizeof(hash), &hash_length);
3192 
3193         if (status != PSA_SUCCESS) {
3194             return status;
3195         }
3196 
3197         return psa_driver_wrapper_sign_hash(
3198             attributes, key_buffer, key_buffer_size,
3199             alg, hash, hash_length,
3200             signature, signature_size, signature_length);
3201     }
3202 
3203     return PSA_ERROR_NOT_SUPPORTED;
3204 }
3205 
3206 psa_status_t psa_sign_message(mbedtls_svc_key_id_t key,
3207                               psa_algorithm_t alg,
3208                               const uint8_t *input_external,
3209                               size_t input_length,
3210                               uint8_t *signature_external,
3211                               size_t signature_size,
3212                               size_t *signature_length)
3213 {
3214     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3215     LOCAL_INPUT_DECLARE(input_external, input);
3216     LOCAL_OUTPUT_DECLARE(signature_external, signature);
3217 
3218     LOCAL_INPUT_ALLOC(input_external, input_length, input);
3219     LOCAL_OUTPUT_ALLOC(signature_external, signature_size, signature);
3220     status = psa_sign_internal(key, 1, alg, input, input_length, signature,
3221                                signature_size, signature_length);
3222 
3223 #if !defined(MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS)
3224 exit:
3225 #endif
3226     LOCAL_INPUT_FREE(input_external, input);
3227     LOCAL_OUTPUT_FREE(signature_external, signature);
3228     return status;
3229 }
3230 
3231 psa_status_t psa_verify_message_builtin(
3232     const psa_key_attributes_t *attributes,
3233     const uint8_t *key_buffer,
3234     size_t key_buffer_size,
3235     psa_algorithm_t alg,
3236     const uint8_t *input,
3237     size_t input_length,
3238     const uint8_t *signature,
3239     size_t signature_length)
3240 {
3241     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3242 
3243     if (PSA_ALG_IS_SIGN_HASH(alg)) {
3244         size_t hash_length;
3245         uint8_t hash[PSA_HASH_MAX_SIZE];
3246 
3247         status = psa_driver_wrapper_hash_compute(
3248             PSA_ALG_SIGN_GET_HASH(alg),
3249             input, input_length,
3250             hash, sizeof(hash), &hash_length);
3251 
3252         if (status != PSA_SUCCESS) {
3253             return status;
3254         }
3255 
3256         return psa_driver_wrapper_verify_hash(
3257             attributes, key_buffer, key_buffer_size,
3258             alg, hash, hash_length,
3259             signature, signature_length);
3260     }
3261 
3262     return PSA_ERROR_NOT_SUPPORTED;
3263 }
3264 
3265 psa_status_t psa_verify_message(mbedtls_svc_key_id_t key,
3266                                 psa_algorithm_t alg,
3267                                 const uint8_t *input_external,
3268                                 size_t input_length,
3269                                 const uint8_t *signature_external,
3270                                 size_t signature_length)
3271 {
3272     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3273     LOCAL_INPUT_DECLARE(input_external, input);
3274     LOCAL_INPUT_DECLARE(signature_external, signature);
3275 
3276     LOCAL_INPUT_ALLOC(input_external, input_length, input);
3277     LOCAL_INPUT_ALLOC(signature_external, signature_length, signature);
3278     status = psa_verify_internal(key, 1, alg, input, input_length, signature,
3279                                  signature_length);
3280 
3281 #if !defined(MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS)
3282 exit:
3283 #endif
3284     LOCAL_INPUT_FREE(input_external, input);
3285     LOCAL_INPUT_FREE(signature_external, signature);
3286 
3287     return status;
3288 }
3289 
3290 psa_status_t psa_sign_hash_builtin(
3291     const psa_key_attributes_t *attributes,
3292     const uint8_t *key_buffer, size_t key_buffer_size,
3293     psa_algorithm_t alg, const uint8_t *hash, size_t hash_length,
3294     uint8_t *signature, size_t signature_size, size_t *signature_length)
3295 {
3296     if (attributes->type == PSA_KEY_TYPE_RSA_KEY_PAIR) {
3297         if (PSA_ALG_IS_RSA_PKCS1V15_SIGN(alg) ||
3298             PSA_ALG_IS_RSA_PSS(alg)) {
3299 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) || \
3300             defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS)
3301             return mbedtls_psa_rsa_sign_hash(
3302                 attributes,
3303                 key_buffer, key_buffer_size,
3304                 alg, hash, hash_length,
3305                 signature, signature_size, signature_length);
3306 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) ||
3307         * defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS) */
3308         } else {
3309             return PSA_ERROR_INVALID_ARGUMENT;
3310         }
3311     } else if (PSA_KEY_TYPE_IS_ECC(attributes->type)) {
3312         if (PSA_ALG_IS_ECDSA(alg)) {
3313 #if defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
3314             defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)
3315             return mbedtls_psa_ecdsa_sign_hash(
3316                 attributes,
3317                 key_buffer, key_buffer_size,
3318                 alg, hash, hash_length,
3319                 signature, signature_size, signature_length);
3320 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
3321         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) */
3322         } else {
3323             return PSA_ERROR_INVALID_ARGUMENT;
3324         }
3325     }
3326 
3327     (void) key_buffer;
3328     (void) key_buffer_size;
3329     (void) hash;
3330     (void) hash_length;
3331     (void) signature;
3332     (void) signature_size;
3333     (void) signature_length;
3334 
3335     return PSA_ERROR_NOT_SUPPORTED;
3336 }
3337 
3338 psa_status_t psa_sign_hash(mbedtls_svc_key_id_t key,
3339                            psa_algorithm_t alg,
3340                            const uint8_t *hash_external,
3341                            size_t hash_length,
3342                            uint8_t *signature_external,
3343                            size_t signature_size,
3344                            size_t *signature_length)
3345 {
3346     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3347     LOCAL_INPUT_DECLARE(hash_external, hash);
3348     LOCAL_OUTPUT_DECLARE(signature_external, signature);
3349 
3350     LOCAL_INPUT_ALLOC(hash_external, hash_length, hash);
3351     LOCAL_OUTPUT_ALLOC(signature_external, signature_size, signature);
3352     status = psa_sign_internal(key, 0, alg, hash, hash_length, signature,
3353                                signature_size, signature_length);
3354 
3355 #if !defined(MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS)
3356 exit:
3357 #endif
3358     LOCAL_INPUT_FREE(hash_external, hash);
3359     LOCAL_OUTPUT_FREE(signature_external, signature);
3360 
3361     return status;
3362 }
3363 
3364 psa_status_t psa_verify_hash_builtin(
3365     const psa_key_attributes_t *attributes,
3366     const uint8_t *key_buffer, size_t key_buffer_size,
3367     psa_algorithm_t alg, const uint8_t *hash, size_t hash_length,
3368     const uint8_t *signature, size_t signature_length)
3369 {
3370     if (PSA_KEY_TYPE_IS_RSA(attributes->type)) {
3371         if (PSA_ALG_IS_RSA_PKCS1V15_SIGN(alg) ||
3372             PSA_ALG_IS_RSA_PSS(alg)) {
3373 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) || \
3374             defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS)
3375             return mbedtls_psa_rsa_verify_hash(
3376                 attributes,
3377                 key_buffer, key_buffer_size,
3378                 alg, hash, hash_length,
3379                 signature, signature_length);
3380 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) ||
3381         * defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS) */
3382         } else {
3383             return PSA_ERROR_INVALID_ARGUMENT;
3384         }
3385     } else if (PSA_KEY_TYPE_IS_ECC(attributes->type)) {
3386         if (PSA_ALG_IS_ECDSA(alg)) {
3387 #if defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
3388             defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)
3389             return mbedtls_psa_ecdsa_verify_hash(
3390                 attributes,
3391                 key_buffer, key_buffer_size,
3392                 alg, hash, hash_length,
3393                 signature, signature_length);
3394 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
3395         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) */
3396         } else {
3397             return PSA_ERROR_INVALID_ARGUMENT;
3398         }
3399     }
3400 
3401     (void) key_buffer;
3402     (void) key_buffer_size;
3403     (void) hash;
3404     (void) hash_length;
3405     (void) signature;
3406     (void) signature_length;
3407 
3408     return PSA_ERROR_NOT_SUPPORTED;
3409 }
3410 
3411 psa_status_t psa_verify_hash(mbedtls_svc_key_id_t key,
3412                              psa_algorithm_t alg,
3413                              const uint8_t *hash_external,
3414                              size_t hash_length,
3415                              const uint8_t *signature_external,
3416                              size_t signature_length)
3417 {
3418     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3419     LOCAL_INPUT_DECLARE(hash_external, hash);
3420     LOCAL_INPUT_DECLARE(signature_external, signature);
3421 
3422     LOCAL_INPUT_ALLOC(hash_external, hash_length, hash);
3423     LOCAL_INPUT_ALLOC(signature_external, signature_length, signature);
3424     status = psa_verify_internal(key, 0, alg, hash, hash_length, signature,
3425                                  signature_length);
3426 
3427 #if !defined(MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS)
3428 exit:
3429 #endif
3430     LOCAL_INPUT_FREE(hash_external, hash);
3431     LOCAL_INPUT_FREE(signature_external, signature);
3432 
3433     return status;
3434 }
3435 
3436 psa_status_t psa_asymmetric_encrypt(mbedtls_svc_key_id_t key,
3437                                     psa_algorithm_t alg,
3438                                     const uint8_t *input_external,
3439                                     size_t input_length,
3440                                     const uint8_t *salt_external,
3441                                     size_t salt_length,
3442                                     uint8_t *output_external,
3443                                     size_t output_size,
3444                                     size_t *output_length)
3445 {
3446     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3447     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
3448     psa_key_slot_t *slot;
3449 
3450     LOCAL_INPUT_DECLARE(input_external, input);
3451     LOCAL_INPUT_DECLARE(salt_external, salt);
3452     LOCAL_OUTPUT_DECLARE(output_external, output);
3453 
3454     (void) input;
3455     (void) input_length;
3456     (void) salt;
3457     (void) output;
3458     (void) output_size;
3459 
3460     *output_length = 0;
3461 
3462     if (!PSA_ALG_IS_RSA_OAEP(alg) && salt_length != 0) {
3463         return PSA_ERROR_INVALID_ARGUMENT;
3464     }
3465 
3466     status = psa_get_and_lock_key_slot_with_policy(
3467         key, &slot, PSA_KEY_USAGE_ENCRYPT, alg);
3468     if (status != PSA_SUCCESS) {
3469         return status;
3470     }
3471     if (!(PSA_KEY_TYPE_IS_PUBLIC_KEY(slot->attr.type) ||
3472           PSA_KEY_TYPE_IS_KEY_PAIR(slot->attr.type))) {
3473         status = PSA_ERROR_INVALID_ARGUMENT;
3474         goto exit;
3475     }
3476 
3477     LOCAL_INPUT_ALLOC(input_external, input_length, input);
3478     LOCAL_INPUT_ALLOC(salt_external, salt_length, salt);
3479     LOCAL_OUTPUT_ALLOC(output_external, output_size, output);
3480 
3481     status = psa_driver_wrapper_asymmetric_encrypt(
3482         &slot->attr, slot->key.data, slot->key.bytes,
3483         alg, input, input_length, salt, salt_length,
3484         output, output_size, output_length);
3485 exit:
3486     unlock_status = psa_unregister_read_under_mutex(slot);
3487 
3488     LOCAL_INPUT_FREE(input_external, input);
3489     LOCAL_INPUT_FREE(salt_external, salt);
3490     LOCAL_OUTPUT_FREE(output_external, output);
3491 
3492     return (status == PSA_SUCCESS) ? unlock_status : status;
3493 }
3494 
3495 psa_status_t psa_asymmetric_decrypt(mbedtls_svc_key_id_t key,
3496                                     psa_algorithm_t alg,
3497                                     const uint8_t *input_external,
3498                                     size_t input_length,
3499                                     const uint8_t *salt_external,
3500                                     size_t salt_length,
3501                                     uint8_t *output_external,
3502                                     size_t output_size,
3503                                     size_t *output_length)
3504 {
3505     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3506     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
3507     psa_key_slot_t *slot;
3508 
3509     LOCAL_INPUT_DECLARE(input_external, input);
3510     LOCAL_INPUT_DECLARE(salt_external, salt);
3511     LOCAL_OUTPUT_DECLARE(output_external, output);
3512 
3513     (void) input;
3514     (void) input_length;
3515     (void) salt;
3516     (void) output;
3517     (void) output_size;
3518 
3519     *output_length = 0;
3520 
3521     if (!PSA_ALG_IS_RSA_OAEP(alg) && salt_length != 0) {
3522         return PSA_ERROR_INVALID_ARGUMENT;
3523     }
3524 
3525     status = psa_get_and_lock_key_slot_with_policy(
3526         key, &slot, PSA_KEY_USAGE_DECRYPT, alg);
3527     if (status != PSA_SUCCESS) {
3528         return status;
3529     }
3530     if (!PSA_KEY_TYPE_IS_KEY_PAIR(slot->attr.type)) {
3531         status = PSA_ERROR_INVALID_ARGUMENT;
3532         goto exit;
3533     }
3534 
3535     LOCAL_INPUT_ALLOC(input_external, input_length, input);
3536     LOCAL_INPUT_ALLOC(salt_external, salt_length, salt);
3537     LOCAL_OUTPUT_ALLOC(output_external, output_size, output);
3538 
3539     status = psa_driver_wrapper_asymmetric_decrypt(
3540         &slot->attr, slot->key.data, slot->key.bytes,
3541         alg, input, input_length, salt, salt_length,
3542         output, output_size, output_length);
3543 
3544 exit:
3545     unlock_status = psa_unregister_read_under_mutex(slot);
3546 
3547     LOCAL_INPUT_FREE(input_external, input);
3548     LOCAL_INPUT_FREE(salt_external, salt);
3549     LOCAL_OUTPUT_FREE(output_external, output);
3550 
3551     return (status == PSA_SUCCESS) ? unlock_status : status;
3552 }
3553 
3554 /****************************************************************/
3555 /* Asymmetric interruptible cryptography                        */
3556 /****************************************************************/
3557 
3558 static uint32_t psa_interruptible_max_ops = PSA_INTERRUPTIBLE_MAX_OPS_UNLIMITED;
3559 
3560 void psa_interruptible_set_max_ops(uint32_t max_ops)
3561 {
3562     psa_interruptible_max_ops = max_ops;
3563 }
3564 
3565 uint32_t psa_interruptible_get_max_ops(void)
3566 {
3567     return psa_interruptible_max_ops;
3568 }
3569 
3570 uint32_t psa_sign_hash_get_num_ops(
3571     const psa_sign_hash_interruptible_operation_t *operation)
3572 {
3573     return operation->num_ops;
3574 }
3575 
3576 uint32_t psa_verify_hash_get_num_ops(
3577     const psa_verify_hash_interruptible_operation_t *operation)
3578 {
3579     return operation->num_ops;
3580 }
3581 
3582 static psa_status_t psa_sign_hash_abort_internal(
3583     psa_sign_hash_interruptible_operation_t *operation)
3584 {
3585     if (operation->id == 0) {
3586         /* The object has (apparently) been initialized but it is not (yet)
3587          * in use. It's ok to call abort on such an object, and there's
3588          * nothing to do. */
3589         return PSA_SUCCESS;
3590     }
3591 
3592     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3593 
3594     status = psa_driver_wrapper_sign_hash_abort(operation);
3595 
3596     operation->id = 0;
3597 
3598     /* Do not clear either the error_occurred or num_ops elements here as they
3599      * only want to be cleared by the application calling abort, not by abort
3600      * being called at completion of an operation. */
3601 
3602     return status;
3603 }
3604 
3605 psa_status_t psa_sign_hash_start(
3606     psa_sign_hash_interruptible_operation_t *operation,
3607     mbedtls_svc_key_id_t key, psa_algorithm_t alg,
3608     const uint8_t *hash_external, size_t hash_length)
3609 {
3610     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3611     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
3612     psa_key_slot_t *slot;
3613 
3614     LOCAL_INPUT_DECLARE(hash_external, hash);
3615 
3616     /* Check that start has not been previously called, or operation has not
3617      * previously errored. */
3618     if (operation->id != 0 || operation->error_occurred) {
3619         return PSA_ERROR_BAD_STATE;
3620     }
3621 
3622     status = psa_sign_verify_check_alg(0, alg);
3623     if (status != PSA_SUCCESS) {
3624         operation->error_occurred = 1;
3625         return status;
3626     }
3627 
3628     status = psa_get_and_lock_key_slot_with_policy(key, &slot,
3629                                                    PSA_KEY_USAGE_SIGN_HASH,
3630                                                    alg);
3631 
3632     if (status != PSA_SUCCESS) {
3633         goto exit;
3634     }
3635 
3636     if (!PSA_KEY_TYPE_IS_KEY_PAIR(slot->attr.type)) {
3637         status = PSA_ERROR_INVALID_ARGUMENT;
3638         goto exit;
3639     }
3640 
3641     LOCAL_INPUT_ALLOC(hash_external, hash_length, hash);
3642 
3643     /* Ensure ops count gets reset, in case of operation re-use. */
3644     operation->num_ops = 0;
3645 
3646     status = psa_driver_wrapper_sign_hash_start(operation, &slot->attr,
3647                                                 slot->key.data,
3648                                                 slot->key.bytes, alg,
3649                                                 hash, hash_length);
3650 exit:
3651 
3652     if (status != PSA_SUCCESS) {
3653         operation->error_occurred = 1;
3654         psa_sign_hash_abort_internal(operation);
3655     }
3656 
3657     unlock_status = psa_unregister_read_under_mutex(slot);
3658 
3659     if (unlock_status != PSA_SUCCESS) {
3660         operation->error_occurred = 1;
3661     }
3662 
3663     LOCAL_INPUT_FREE(hash_external, hash);
3664 
3665     return (status == PSA_SUCCESS) ? unlock_status : status;
3666 }
3667 
3668 
3669 psa_status_t psa_sign_hash_complete(
3670     psa_sign_hash_interruptible_operation_t *operation,
3671     uint8_t *signature_external, size_t signature_size,
3672     size_t *signature_length)
3673 {
3674     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3675 
3676     LOCAL_OUTPUT_DECLARE(signature_external, signature);
3677 
3678     *signature_length = 0;
3679 
3680     /* Check that start has been called first, and that operation has not
3681      * previously errored. */
3682     if (operation->id == 0 || operation->error_occurred) {
3683         status = PSA_ERROR_BAD_STATE;
3684         goto exit;
3685     }
3686 
3687     /* Immediately reject a zero-length signature buffer. This guarantees that
3688      * signature must be a valid pointer. */
3689     if (signature_size == 0) {
3690         status = PSA_ERROR_BUFFER_TOO_SMALL;
3691         goto exit;
3692     }
3693 
3694     LOCAL_OUTPUT_ALLOC(signature_external, signature_size, signature);
3695 
3696     status = psa_driver_wrapper_sign_hash_complete(operation, signature,
3697                                                    signature_size,
3698                                                    signature_length);
3699 
3700     /* Update ops count with work done. */
3701     operation->num_ops = psa_driver_wrapper_sign_hash_get_num_ops(operation);
3702 
3703 exit:
3704 
3705     if (signature != NULL) {
3706         psa_wipe_tag_output_buffer(signature, status, signature_size,
3707                                    *signature_length);
3708     }
3709 
3710     if (status != PSA_OPERATION_INCOMPLETE) {
3711         if (status != PSA_SUCCESS) {
3712             operation->error_occurred = 1;
3713         }
3714 
3715         psa_sign_hash_abort_internal(operation);
3716     }
3717 
3718     LOCAL_OUTPUT_FREE(signature_external, signature);
3719 
3720     return status;
3721 }
3722 
3723 psa_status_t psa_sign_hash_abort(
3724     psa_sign_hash_interruptible_operation_t *operation)
3725 {
3726     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3727 
3728     status = psa_sign_hash_abort_internal(operation);
3729 
3730     /* We clear the number of ops done here, so that it is not cleared when
3731      * the operation fails or succeeds, only on manual abort. */
3732     operation->num_ops = 0;
3733 
3734     /* Likewise, failure state. */
3735     operation->error_occurred = 0;
3736 
3737     return status;
3738 }
3739 
3740 static psa_status_t psa_verify_hash_abort_internal(
3741     psa_verify_hash_interruptible_operation_t *operation)
3742 {
3743     if (operation->id == 0) {
3744         /* The object has (apparently) been initialized but it is not (yet)
3745          * in use. It's ok to call abort on such an object, and there's
3746          * nothing to do. */
3747         return PSA_SUCCESS;
3748     }
3749 
3750     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3751 
3752     status = psa_driver_wrapper_verify_hash_abort(operation);
3753 
3754     operation->id = 0;
3755 
3756     /* Do not clear either the error_occurred or num_ops elements here as they
3757      * only want to be cleared by the application calling abort, not by abort
3758      * being called at completion of an operation. */
3759 
3760     return status;
3761 }
3762 
3763 psa_status_t psa_verify_hash_start(
3764     psa_verify_hash_interruptible_operation_t *operation,
3765     mbedtls_svc_key_id_t key, psa_algorithm_t alg,
3766     const uint8_t *hash_external, size_t hash_length,
3767     const uint8_t *signature_external, size_t signature_length)
3768 {
3769     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3770     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
3771     psa_key_slot_t *slot;
3772 
3773     LOCAL_INPUT_DECLARE(hash_external, hash);
3774     LOCAL_INPUT_DECLARE(signature_external, signature);
3775 
3776     /* Check that start has not been previously called, or operation has not
3777      * previously errored. */
3778     if (operation->id != 0 || operation->error_occurred) {
3779         return PSA_ERROR_BAD_STATE;
3780     }
3781 
3782     status = psa_sign_verify_check_alg(0, alg);
3783     if (status != PSA_SUCCESS) {
3784         operation->error_occurred = 1;
3785         return status;
3786     }
3787 
3788     status = psa_get_and_lock_key_slot_with_policy(key, &slot,
3789                                                    PSA_KEY_USAGE_VERIFY_HASH,
3790                                                    alg);
3791 
3792     if (status != PSA_SUCCESS) {
3793         operation->error_occurred = 1;
3794         return status;
3795     }
3796 
3797     LOCAL_INPUT_ALLOC(hash_external, hash_length, hash);
3798     LOCAL_INPUT_ALLOC(signature_external, signature_length, signature);
3799 
3800     /* Ensure ops count gets reset, in case of operation re-use. */
3801     operation->num_ops = 0;
3802 
3803     status = psa_driver_wrapper_verify_hash_start(operation, &slot->attr,
3804                                                   slot->key.data,
3805                                                   slot->key.bytes,
3806                                                   alg, hash, hash_length,
3807                                                   signature, signature_length);
3808 #if !defined(MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS)
3809 exit:
3810 #endif
3811 
3812     if (status != PSA_SUCCESS) {
3813         operation->error_occurred = 1;
3814         psa_verify_hash_abort_internal(operation);
3815     }
3816 
3817     unlock_status = psa_unregister_read_under_mutex(slot);
3818 
3819     if (unlock_status != PSA_SUCCESS) {
3820         operation->error_occurred = 1;
3821     }
3822 
3823     LOCAL_INPUT_FREE(hash_external, hash);
3824     LOCAL_INPUT_FREE(signature_external, signature);
3825 
3826     return (status == PSA_SUCCESS) ? unlock_status : status;
3827 }
3828 
3829 psa_status_t psa_verify_hash_complete(
3830     psa_verify_hash_interruptible_operation_t *operation)
3831 {
3832     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3833 
3834     /* Check that start has been called first, and that operation has not
3835      * previously errored. */
3836     if (operation->id == 0 || operation->error_occurred) {
3837         status = PSA_ERROR_BAD_STATE;
3838         goto exit;
3839     }
3840 
3841     status = psa_driver_wrapper_verify_hash_complete(operation);
3842 
3843     /* Update ops count with work done. */
3844     operation->num_ops = psa_driver_wrapper_verify_hash_get_num_ops(
3845         operation);
3846 
3847 exit:
3848 
3849     if (status != PSA_OPERATION_INCOMPLETE) {
3850         if (status != PSA_SUCCESS) {
3851             operation->error_occurred = 1;
3852         }
3853 
3854         psa_verify_hash_abort_internal(operation);
3855     }
3856 
3857     return status;
3858 }
3859 
3860 psa_status_t psa_verify_hash_abort(
3861     psa_verify_hash_interruptible_operation_t *operation)
3862 {
3863     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3864 
3865     status = psa_verify_hash_abort_internal(operation);
3866 
3867     /* We clear the number of ops done here, so that it is not cleared when
3868      * the operation fails or succeeds, only on manual abort. */
3869     operation->num_ops = 0;
3870 
3871     /* Likewise, failure state. */
3872     operation->error_occurred = 0;
3873 
3874     return status;
3875 }
3876 
3877 /****************************************************************/
3878 /* Asymmetric interruptible cryptography internal               */
3879 /* implementations                                              */
3880 /****************************************************************/
3881 
3882 void mbedtls_psa_interruptible_set_max_ops(uint32_t max_ops)
3883 {
3884 
3885 #if (defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
3886     defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)) && \
3887     defined(MBEDTLS_ECP_RESTARTABLE)
3888 
3889     /* Internal implementation uses zero to indicate infinite number max ops,
3890      * therefore avoid this value, and set to minimum possible. */
3891     if (max_ops == 0) {
3892         max_ops = 1;
3893     }
3894 
3895     mbedtls_ecp_set_max_ops(max_ops);
3896 #else
3897     (void) max_ops;
3898 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
3899         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) &&
3900         * defined( MBEDTLS_ECP_RESTARTABLE ) */
3901 }
3902 
3903 uint32_t mbedtls_psa_sign_hash_get_num_ops(
3904     const mbedtls_psa_sign_hash_interruptible_operation_t *operation)
3905 {
3906 #if (defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
3907     defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)) && \
3908     defined(MBEDTLS_ECP_RESTARTABLE)
3909 
3910     return operation->num_ops;
3911 #else
3912     (void) operation;
3913     return 0;
3914 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
3915         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) &&
3916         * defined( MBEDTLS_ECP_RESTARTABLE ) */
3917 }
3918 
3919 uint32_t mbedtls_psa_verify_hash_get_num_ops(
3920     const mbedtls_psa_verify_hash_interruptible_operation_t *operation)
3921 {
3922     #if (defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
3923     defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)) && \
3924     defined(MBEDTLS_ECP_RESTARTABLE)
3925 
3926     return operation->num_ops;
3927 #else
3928     (void) operation;
3929     return 0;
3930 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
3931         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) &&
3932         * defined( MBEDTLS_ECP_RESTARTABLE ) */
3933 }
3934 
3935 /* Detect supported interruptible sign/verify mechanisms precisely.
3936  * This is not strictly needed: we could accept everything, and let the
3937  * code fail later during complete() if the mechanism is unsupported
3938  * (e.g. attempting deterministic ECDSA when only the randomized variant
3939  * is available). But it's easier for applications and especially for our
3940  * test code to detect all not-supported errors during start().
3941  *
3942  * Note that this function ignores the hash component. The core code
3943  * is supposed to check the hash part by calling is_hash_supported().
3944  */
3945 static inline int can_do_interruptible_sign_verify(psa_algorithm_t alg)
3946 {
3947 #if defined(MBEDTLS_ECP_RESTARTABLE)
3948 #if defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)
3949     if (PSA_ALG_IS_DETERMINISTIC_ECDSA(alg)) {
3950         return 1;
3951     }
3952 #endif
3953 #if defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA)
3954     if (PSA_ALG_IS_RANDOMIZED_ECDSA(alg)) {
3955         return 1;
3956     }
3957 #endif
3958 #endif /* defined(MBEDTLS_ECP_RESTARTABLE) */
3959     (void) alg;
3960     return 0;
3961 }
3962 
3963 psa_status_t mbedtls_psa_sign_hash_start(
3964     mbedtls_psa_sign_hash_interruptible_operation_t *operation,
3965     const psa_key_attributes_t *attributes, const uint8_t *key_buffer,
3966     size_t key_buffer_size, psa_algorithm_t alg,
3967     const uint8_t *hash, size_t hash_length)
3968 {
3969     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3970     size_t required_hash_length;
3971 
3972     if (!PSA_KEY_TYPE_IS_ECC_KEY_PAIR(attributes->type)) {
3973         return PSA_ERROR_NOT_SUPPORTED;
3974     }
3975     psa_ecc_family_t curve = PSA_KEY_TYPE_ECC_GET_FAMILY(attributes->type);
3976     if (!PSA_ECC_FAMILY_IS_WEIERSTRASS(curve)) {
3977         return PSA_ERROR_INVALID_ARGUMENT;
3978     }
3979 
3980     if (!can_do_interruptible_sign_verify(alg)) {
3981         return PSA_ERROR_NOT_SUPPORTED;
3982     }
3983 
3984 #if (defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
3985     defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)) && \
3986     defined(MBEDTLS_ECP_RESTARTABLE)
3987 
3988     mbedtls_ecdsa_restart_init(&operation->restart_ctx);
3989 
3990     /* Ensure num_ops is zero'ed in case of context re-use. */
3991     operation->num_ops = 0;
3992 
3993     status = mbedtls_psa_ecp_load_representation(attributes->type,
3994                                                  attributes->bits,
3995                                                  key_buffer,
3996                                                  key_buffer_size,
3997                                                  &operation->ctx);
3998 
3999     if (status != PSA_SUCCESS) {
4000         return status;
4001     }
4002 
4003     operation->coordinate_bytes = PSA_BITS_TO_BYTES(
4004         operation->ctx->grp.nbits);
4005 
4006     psa_algorithm_t hash_alg = PSA_ALG_SIGN_GET_HASH(alg);
4007     operation->md_alg = mbedtls_md_type_from_psa_alg(hash_alg);
4008     operation->alg = alg;
4009 
4010     /* We only need to store the same length of hash as the private key size
4011      * here, it would be truncated by the internal implementation anyway. */
4012     required_hash_length = (hash_length < operation->coordinate_bytes ?
4013                             hash_length : operation->coordinate_bytes);
4014 
4015     if (required_hash_length > sizeof(operation->hash)) {
4016         /* Shouldn't happen, but better safe than sorry. */
4017         return PSA_ERROR_CORRUPTION_DETECTED;
4018     }
4019 
4020     memcpy(operation->hash, hash, required_hash_length);
4021     operation->hash_length = required_hash_length;
4022 
4023     return PSA_SUCCESS;
4024 
4025 #else
4026     (void) operation;
4027     (void) key_buffer;
4028     (void) key_buffer_size;
4029     (void) alg;
4030     (void) hash;
4031     (void) hash_length;
4032     (void) status;
4033     (void) required_hash_length;
4034 
4035     return PSA_ERROR_NOT_SUPPORTED;
4036 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
4037         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) &&
4038         * defined( MBEDTLS_ECP_RESTARTABLE ) */
4039 }
4040 
4041 psa_status_t mbedtls_psa_sign_hash_complete(
4042     mbedtls_psa_sign_hash_interruptible_operation_t *operation,
4043     uint8_t *signature, size_t signature_size,
4044     size_t *signature_length)
4045 {
4046 #if (defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
4047     defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)) && \
4048     defined(MBEDTLS_ECP_RESTARTABLE)
4049 
4050     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4051     mbedtls_mpi r;
4052     mbedtls_mpi s;
4053 
4054     mbedtls_mpi_init(&r);
4055     mbedtls_mpi_init(&s);
4056 
4057     /* Ensure max_ops is set to the current value (or default). */
4058     mbedtls_psa_interruptible_set_max_ops(psa_interruptible_get_max_ops());
4059 
4060     if (signature_size < 2 * operation->coordinate_bytes) {
4061         status = PSA_ERROR_BUFFER_TOO_SMALL;
4062         goto exit;
4063     }
4064 
4065     if (PSA_ALG_ECDSA_IS_DETERMINISTIC(operation->alg)) {
4066 
4067 #if defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)
4068         status = mbedtls_to_psa_error(
4069             mbedtls_ecdsa_sign_det_restartable(&operation->ctx->grp,
4070                                                &r,
4071                                                &s,
4072                                                &operation->ctx->d,
4073                                                operation->hash,
4074                                                operation->hash_length,
4075                                                operation->md_alg,
4076                                                mbedtls_psa_get_random,
4077                                                MBEDTLS_PSA_RANDOM_STATE,
4078                                                &operation->restart_ctx));
4079 #else /* defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) */
4080         status = PSA_ERROR_NOT_SUPPORTED;
4081         goto exit;
4082 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) */
4083     } else {
4084         status = mbedtls_to_psa_error(
4085             mbedtls_ecdsa_sign_restartable(&operation->ctx->grp,
4086                                            &r,
4087                                            &s,
4088                                            &operation->ctx->d,
4089                                            operation->hash,
4090                                            operation->hash_length,
4091                                            mbedtls_psa_get_random,
4092                                            MBEDTLS_PSA_RANDOM_STATE,
4093                                            mbedtls_psa_get_random,
4094                                            MBEDTLS_PSA_RANDOM_STATE,
4095                                            &operation->restart_ctx));
4096     }
4097 
4098     /* Hide the fact that the restart context only holds a delta of number of
4099      * ops done during the last operation, not an absolute value. */
4100     operation->num_ops += operation->restart_ctx.ecp.ops_done;
4101 
4102     if (status == PSA_SUCCESS) {
4103         status =  mbedtls_to_psa_error(
4104             mbedtls_mpi_write_binary(&r,
4105                                      signature,
4106                                      operation->coordinate_bytes)
4107             );
4108 
4109         if (status != PSA_SUCCESS) {
4110             goto exit;
4111         }
4112 
4113         status =  mbedtls_to_psa_error(
4114             mbedtls_mpi_write_binary(&s,
4115                                      signature +
4116                                      operation->coordinate_bytes,
4117                                      operation->coordinate_bytes)
4118             );
4119 
4120         if (status != PSA_SUCCESS) {
4121             goto exit;
4122         }
4123 
4124         *signature_length = operation->coordinate_bytes * 2;
4125 
4126         status = PSA_SUCCESS;
4127     }
4128 
4129 exit:
4130 
4131     mbedtls_mpi_free(&r);
4132     mbedtls_mpi_free(&s);
4133     return status;
4134 
4135  #else
4136 
4137     (void) operation;
4138     (void) signature;
4139     (void) signature_size;
4140     (void) signature_length;
4141 
4142     return PSA_ERROR_NOT_SUPPORTED;
4143 
4144 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
4145         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) &&
4146         * defined( MBEDTLS_ECP_RESTARTABLE ) */
4147 }
4148 
4149 psa_status_t mbedtls_psa_sign_hash_abort(
4150     mbedtls_psa_sign_hash_interruptible_operation_t *operation)
4151 {
4152 
4153 #if (defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
4154     defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)) && \
4155     defined(MBEDTLS_ECP_RESTARTABLE)
4156 
4157     if (operation->ctx) {
4158         mbedtls_ecdsa_free(operation->ctx);
4159         mbedtls_free(operation->ctx);
4160         operation->ctx = NULL;
4161     }
4162 
4163     mbedtls_ecdsa_restart_free(&operation->restart_ctx);
4164 
4165     operation->num_ops = 0;
4166 
4167     return PSA_SUCCESS;
4168 
4169 #else
4170 
4171     (void) operation;
4172 
4173     return PSA_ERROR_NOT_SUPPORTED;
4174 
4175 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
4176         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) &&
4177         * defined( MBEDTLS_ECP_RESTARTABLE ) */
4178 }
4179 
4180 psa_status_t mbedtls_psa_verify_hash_start(
4181     mbedtls_psa_verify_hash_interruptible_operation_t *operation,
4182     const psa_key_attributes_t *attributes,
4183     const uint8_t *key_buffer, size_t key_buffer_size,
4184     psa_algorithm_t alg,
4185     const uint8_t *hash, size_t hash_length,
4186     const uint8_t *signature, size_t signature_length)
4187 {
4188     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4189     size_t coordinate_bytes = 0;
4190     size_t required_hash_length = 0;
4191 
4192     if (!PSA_KEY_TYPE_IS_ECC(attributes->type)) {
4193         return PSA_ERROR_NOT_SUPPORTED;
4194     }
4195     psa_ecc_family_t curve = PSA_KEY_TYPE_ECC_GET_FAMILY(attributes->type);
4196     if (!PSA_ECC_FAMILY_IS_WEIERSTRASS(curve)) {
4197         return PSA_ERROR_INVALID_ARGUMENT;
4198     }
4199 
4200     if (!can_do_interruptible_sign_verify(alg)) {
4201         return PSA_ERROR_NOT_SUPPORTED;
4202     }
4203 
4204 #if (defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
4205     defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)) && \
4206     defined(MBEDTLS_ECP_RESTARTABLE)
4207 
4208     mbedtls_ecdsa_restart_init(&operation->restart_ctx);
4209     mbedtls_mpi_init(&operation->r);
4210     mbedtls_mpi_init(&operation->s);
4211 
4212     /* Ensure num_ops is zero'ed in case of context re-use. */
4213     operation->num_ops = 0;
4214 
4215     status = mbedtls_psa_ecp_load_representation(attributes->type,
4216                                                  attributes->bits,
4217                                                  key_buffer,
4218                                                  key_buffer_size,
4219                                                  &operation->ctx);
4220 
4221     if (status != PSA_SUCCESS) {
4222         return status;
4223     }
4224 
4225     coordinate_bytes = PSA_BITS_TO_BYTES(operation->ctx->grp.nbits);
4226 
4227     if (signature_length != 2 * coordinate_bytes) {
4228         return PSA_ERROR_INVALID_SIGNATURE;
4229     }
4230 
4231     status = mbedtls_to_psa_error(
4232         mbedtls_mpi_read_binary(&operation->r,
4233                                 signature,
4234                                 coordinate_bytes));
4235 
4236     if (status != PSA_SUCCESS) {
4237         return status;
4238     }
4239 
4240     status = mbedtls_to_psa_error(
4241         mbedtls_mpi_read_binary(&operation->s,
4242                                 signature +
4243                                 coordinate_bytes,
4244                                 coordinate_bytes));
4245 
4246     if (status != PSA_SUCCESS) {
4247         return status;
4248     }
4249 
4250     status = mbedtls_psa_ecp_load_public_part(operation->ctx);
4251 
4252     if (status != PSA_SUCCESS) {
4253         return status;
4254     }
4255 
4256     /* We only need to store the same length of hash as the private key size
4257      * here, it would be truncated by the internal implementation anyway. */
4258     required_hash_length = (hash_length < coordinate_bytes ? hash_length :
4259                             coordinate_bytes);
4260 
4261     if (required_hash_length > sizeof(operation->hash)) {
4262         /* Shouldn't happen, but better safe than sorry. */
4263         return PSA_ERROR_CORRUPTION_DETECTED;
4264     }
4265 
4266     memcpy(operation->hash, hash, required_hash_length);
4267     operation->hash_length = required_hash_length;
4268 
4269     return PSA_SUCCESS;
4270 #else
4271     (void) operation;
4272     (void) key_buffer;
4273     (void) key_buffer_size;
4274     (void) alg;
4275     (void) hash;
4276     (void) hash_length;
4277     (void) signature;
4278     (void) signature_length;
4279     (void) status;
4280     (void) coordinate_bytes;
4281     (void) required_hash_length;
4282 
4283     return PSA_ERROR_NOT_SUPPORTED;
4284 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
4285         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) &&
4286         * defined( MBEDTLS_ECP_RESTARTABLE ) */
4287 }
4288 
4289 psa_status_t mbedtls_psa_verify_hash_complete(
4290     mbedtls_psa_verify_hash_interruptible_operation_t *operation)
4291 {
4292 
4293 #if (defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
4294     defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)) && \
4295     defined(MBEDTLS_ECP_RESTARTABLE)
4296 
4297     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4298 
4299     /* Ensure max_ops is set to the current value (or default). */
4300     mbedtls_psa_interruptible_set_max_ops(psa_interruptible_get_max_ops());
4301 
4302     status = mbedtls_to_psa_error(
4303         mbedtls_ecdsa_verify_restartable(&operation->ctx->grp,
4304                                          operation->hash,
4305                                          operation->hash_length,
4306                                          &operation->ctx->Q,
4307                                          &operation->r,
4308                                          &operation->s,
4309                                          &operation->restart_ctx));
4310 
4311     /* Hide the fact that the restart context only holds a delta of number of
4312      * ops done during the last operation, not an absolute value. */
4313     operation->num_ops += operation->restart_ctx.ecp.ops_done;
4314 
4315     return status;
4316 #else
4317     (void) operation;
4318 
4319     return PSA_ERROR_NOT_SUPPORTED;
4320 
4321 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
4322         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) &&
4323         * defined( MBEDTLS_ECP_RESTARTABLE ) */
4324 }
4325 
4326 psa_status_t mbedtls_psa_verify_hash_abort(
4327     mbedtls_psa_verify_hash_interruptible_operation_t *operation)
4328 {
4329 
4330 #if (defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
4331     defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)) && \
4332     defined(MBEDTLS_ECP_RESTARTABLE)
4333 
4334     if (operation->ctx) {
4335         mbedtls_ecdsa_free(operation->ctx);
4336         mbedtls_free(operation->ctx);
4337         operation->ctx = NULL;
4338     }
4339 
4340     mbedtls_ecdsa_restart_free(&operation->restart_ctx);
4341 
4342     operation->num_ops = 0;
4343 
4344     mbedtls_mpi_free(&operation->r);
4345     mbedtls_mpi_free(&operation->s);
4346 
4347     return PSA_SUCCESS;
4348 
4349 #else
4350     (void) operation;
4351 
4352     return PSA_ERROR_NOT_SUPPORTED;
4353 
4354 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
4355         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) &&
4356         * defined( MBEDTLS_ECP_RESTARTABLE ) */
4357 }
4358 
4359 static psa_status_t psa_generate_random_internal(uint8_t *output,
4360                                                  size_t output_size)
4361 {
4362     GUARD_MODULE_INITIALIZED;
4363 
4364 #if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
4365 
4366     psa_status_t status;
4367     size_t output_length = 0;
4368     status = mbedtls_psa_external_get_random(&global_data.rng,
4369                                              output, output_size,
4370                                              &output_length);
4371     if (status != PSA_SUCCESS) {
4372         return status;
4373     }
4374     /* Breaking up a request into smaller chunks is currently not supported
4375      * for the external RNG interface. */
4376     if (output_length != output_size) {
4377         return PSA_ERROR_INSUFFICIENT_ENTROPY;
4378     }
4379     return PSA_SUCCESS;
4380 
4381 #else /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
4382 
4383     while (output_size > 0) {
4384         int ret = MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED;
4385         size_t request_size =
4386             (output_size > MBEDTLS_PSA_RANDOM_MAX_REQUEST ?
4387              MBEDTLS_PSA_RANDOM_MAX_REQUEST :
4388              output_size);
4389 #if defined(MBEDTLS_CTR_DRBG_C)
4390         ret = mbedtls_ctr_drbg_random(&global_data.rng.drbg, output, request_size);
4391 #elif defined(MBEDTLS_HMAC_DRBG_C)
4392         ret = mbedtls_hmac_drbg_random(&global_data.rng.drbg, output, request_size);
4393 #endif /* !MBEDTLS_CTR_DRBG_C && !MBEDTLS_HMAC_DRBG_C */
4394         if (ret != 0) {
4395             return mbedtls_to_psa_error(ret);
4396         }
4397         output_size -= request_size;
4398         output += request_size;
4399     }
4400     return PSA_SUCCESS;
4401 #endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
4402 }
4403 
4404 
4405 /****************************************************************/
4406 /* Symmetric cryptography */
4407 /****************************************************************/
4408 
4409 static psa_status_t psa_cipher_setup(psa_cipher_operation_t *operation,
4410                                      mbedtls_svc_key_id_t key,
4411                                      psa_algorithm_t alg,
4412                                      mbedtls_operation_t cipher_operation)
4413 {
4414     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4415     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
4416     psa_key_slot_t *slot = NULL;
4417     psa_key_usage_t usage = (cipher_operation == MBEDTLS_ENCRYPT ?
4418                              PSA_KEY_USAGE_ENCRYPT :
4419                              PSA_KEY_USAGE_DECRYPT);
4420 
4421     /* A context must be freshly initialized before it can be set up. */
4422     if (operation->id != 0) {
4423         status = PSA_ERROR_BAD_STATE;
4424         goto exit;
4425     }
4426 
4427     if (!PSA_ALG_IS_CIPHER(alg)) {
4428         status = PSA_ERROR_INVALID_ARGUMENT;
4429         goto exit;
4430     }
4431 
4432     status = psa_get_and_lock_key_slot_with_policy(key, &slot, usage, alg);
4433     if (status != PSA_SUCCESS) {
4434         goto exit;
4435     }
4436 
4437     /* Initialize the operation struct members, except for id. The id member
4438      * is used to indicate to psa_cipher_abort that there are resources to free,
4439      * so we only set it (in the driver wrapper) after resources have been
4440      * allocated/initialized. */
4441     operation->iv_set = 0;
4442     if (alg == PSA_ALG_ECB_NO_PADDING) {
4443         operation->iv_required = 0;
4444     } else {
4445         operation->iv_required = 1;
4446     }
4447     operation->default_iv_length = PSA_CIPHER_IV_LENGTH(slot->attr.type, alg);
4448 
4449     /* Try doing the operation through a driver before using software fallback. */
4450     if (cipher_operation == MBEDTLS_ENCRYPT) {
4451         status = psa_driver_wrapper_cipher_encrypt_setup(operation,
4452                                                          &slot->attr,
4453                                                          slot->key.data,
4454                                                          slot->key.bytes,
4455                                                          alg);
4456     } else {
4457         status = psa_driver_wrapper_cipher_decrypt_setup(operation,
4458                                                          &slot->attr,
4459                                                          slot->key.data,
4460                                                          slot->key.bytes,
4461                                                          alg);
4462     }
4463 
4464 exit:
4465     if (status != PSA_SUCCESS) {
4466         psa_cipher_abort(operation);
4467     }
4468 
4469     unlock_status = psa_unregister_read_under_mutex(slot);
4470 
4471     return (status == PSA_SUCCESS) ? unlock_status : status;
4472 }
4473 
4474 psa_status_t psa_cipher_encrypt_setup(psa_cipher_operation_t *operation,
4475                                       mbedtls_svc_key_id_t key,
4476                                       psa_algorithm_t alg)
4477 {
4478     return psa_cipher_setup(operation, key, alg, MBEDTLS_ENCRYPT);
4479 }
4480 
4481 psa_status_t psa_cipher_decrypt_setup(psa_cipher_operation_t *operation,
4482                                       mbedtls_svc_key_id_t key,
4483                                       psa_algorithm_t alg)
4484 {
4485     return psa_cipher_setup(operation, key, alg, MBEDTLS_DECRYPT);
4486 }
4487 
4488 psa_status_t psa_cipher_generate_iv(psa_cipher_operation_t *operation,
4489                                     uint8_t *iv_external,
4490                                     size_t iv_size,
4491                                     size_t *iv_length)
4492 {
4493     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4494     size_t default_iv_length = 0;
4495 
4496     LOCAL_OUTPUT_DECLARE(iv_external, iv);
4497 
4498     if (operation->id == 0) {
4499         status = PSA_ERROR_BAD_STATE;
4500         goto exit;
4501     }
4502 
4503     if (operation->iv_set || !operation->iv_required) {
4504         status = PSA_ERROR_BAD_STATE;
4505         goto exit;
4506     }
4507 
4508     default_iv_length = operation->default_iv_length;
4509     if (iv_size < default_iv_length) {
4510         status = PSA_ERROR_BUFFER_TOO_SMALL;
4511         goto exit;
4512     }
4513 
4514     if (default_iv_length > PSA_CIPHER_IV_MAX_SIZE) {
4515         status = PSA_ERROR_GENERIC_ERROR;
4516         goto exit;
4517     }
4518 
4519     LOCAL_OUTPUT_ALLOC(iv_external, default_iv_length, iv);
4520 
4521     status = psa_generate_random_internal(iv, default_iv_length);
4522     if (status != PSA_SUCCESS) {
4523         goto exit;
4524     }
4525 
4526     status = psa_driver_wrapper_cipher_set_iv(operation,
4527                                               iv, default_iv_length);
4528 
4529 exit:
4530     if (status == PSA_SUCCESS) {
4531         *iv_length = default_iv_length;
4532         operation->iv_set = 1;
4533     } else {
4534         *iv_length = 0;
4535         psa_cipher_abort(operation);
4536         if (iv != NULL) {
4537             mbedtls_platform_zeroize(iv, default_iv_length);
4538         }
4539     }
4540 
4541     LOCAL_OUTPUT_FREE(iv_external, iv);
4542     return status;
4543 }
4544 
4545 psa_status_t psa_cipher_set_iv(psa_cipher_operation_t *operation,
4546                                const uint8_t *iv_external,
4547                                size_t iv_length)
4548 {
4549     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4550 
4551     LOCAL_INPUT_DECLARE(iv_external, iv);
4552 
4553     if (operation->id == 0) {
4554         status = PSA_ERROR_BAD_STATE;
4555         goto exit;
4556     }
4557 
4558     if (operation->iv_set || !operation->iv_required) {
4559         status = PSA_ERROR_BAD_STATE;
4560         goto exit;
4561     }
4562 
4563     if (iv_length > PSA_CIPHER_IV_MAX_SIZE) {
4564         status = PSA_ERROR_INVALID_ARGUMENT;
4565         goto exit;
4566     }
4567 
4568     LOCAL_INPUT_ALLOC(iv_external, iv_length, iv);
4569 
4570     status = psa_driver_wrapper_cipher_set_iv(operation,
4571                                               iv,
4572                                               iv_length);
4573 
4574 exit:
4575     if (status == PSA_SUCCESS) {
4576         operation->iv_set = 1;
4577     } else {
4578         psa_cipher_abort(operation);
4579     }
4580 
4581     LOCAL_INPUT_FREE(iv_external, iv);
4582 
4583     return status;
4584 }
4585 
4586 psa_status_t psa_cipher_update(psa_cipher_operation_t *operation,
4587                                const uint8_t *input_external,
4588                                size_t input_length,
4589                                uint8_t *output_external,
4590                                size_t output_size,
4591                                size_t *output_length)
4592 {
4593     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4594 
4595     LOCAL_INPUT_DECLARE(input_external, input);
4596     LOCAL_OUTPUT_DECLARE(output_external, output);
4597 
4598     if (operation->id == 0) {
4599         status = PSA_ERROR_BAD_STATE;
4600         goto exit;
4601     }
4602 
4603     if (operation->iv_required && !operation->iv_set) {
4604         status = PSA_ERROR_BAD_STATE;
4605         goto exit;
4606     }
4607 
4608     LOCAL_INPUT_ALLOC(input_external, input_length, input);
4609     LOCAL_OUTPUT_ALLOC(output_external, output_size, output);
4610 
4611     status = psa_driver_wrapper_cipher_update(operation,
4612                                               input,
4613                                               input_length,
4614                                               output,
4615                                               output_size,
4616                                               output_length);
4617 
4618 exit:
4619     if (status != PSA_SUCCESS) {
4620         psa_cipher_abort(operation);
4621     }
4622 
4623     LOCAL_INPUT_FREE(input_external, input);
4624     LOCAL_OUTPUT_FREE(output_external, output);
4625 
4626     return status;
4627 }
4628 
4629 psa_status_t psa_cipher_finish(psa_cipher_operation_t *operation,
4630                                uint8_t *output_external,
4631                                size_t output_size,
4632                                size_t *output_length)
4633 {
4634     psa_status_t status = PSA_ERROR_GENERIC_ERROR;
4635 
4636     LOCAL_OUTPUT_DECLARE(output_external, output);
4637 
4638     if (operation->id == 0) {
4639         status = PSA_ERROR_BAD_STATE;
4640         goto exit;
4641     }
4642 
4643     if (operation->iv_required && !operation->iv_set) {
4644         status = PSA_ERROR_BAD_STATE;
4645         goto exit;
4646     }
4647 
4648     LOCAL_OUTPUT_ALLOC(output_external, output_size, output);
4649 
4650     status = psa_driver_wrapper_cipher_finish(operation,
4651                                               output,
4652                                               output_size,
4653                                               output_length);
4654 
4655 exit:
4656     if (status == PSA_SUCCESS) {
4657         status = psa_cipher_abort(operation);
4658     } else {
4659         *output_length = 0;
4660         (void) psa_cipher_abort(operation);
4661     }
4662 
4663     LOCAL_OUTPUT_FREE(output_external, output);
4664 
4665     return status;
4666 }
4667 
4668 psa_status_t psa_cipher_abort(psa_cipher_operation_t *operation)
4669 {
4670     if (operation->id == 0) {
4671         /* The object has (apparently) been initialized but it is not (yet)
4672          * in use. It's ok to call abort on such an object, and there's
4673          * nothing to do. */
4674         return PSA_SUCCESS;
4675     }
4676 
4677     psa_driver_wrapper_cipher_abort(operation);
4678 
4679     operation->id = 0;
4680     operation->iv_set = 0;
4681     operation->iv_required = 0;
4682 
4683     return PSA_SUCCESS;
4684 }
4685 
4686 psa_status_t psa_cipher_encrypt(mbedtls_svc_key_id_t key,
4687                                 psa_algorithm_t alg,
4688                                 const uint8_t *input_external,
4689                                 size_t input_length,
4690                                 uint8_t *output_external,
4691                                 size_t output_size,
4692                                 size_t *output_length)
4693 {
4694     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4695     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
4696     psa_key_slot_t *slot = NULL;
4697     uint8_t local_iv[PSA_CIPHER_IV_MAX_SIZE];
4698     size_t default_iv_length = 0;
4699 
4700     LOCAL_INPUT_DECLARE(input_external, input);
4701     LOCAL_OUTPUT_DECLARE(output_external, output);
4702 
4703     if (!PSA_ALG_IS_CIPHER(alg)) {
4704         status = PSA_ERROR_INVALID_ARGUMENT;
4705         goto exit;
4706     }
4707 
4708     status = psa_get_and_lock_key_slot_with_policy(key, &slot,
4709                                                    PSA_KEY_USAGE_ENCRYPT,
4710                                                    alg);
4711     if (status != PSA_SUCCESS) {
4712         goto exit;
4713     }
4714 
4715     default_iv_length = PSA_CIPHER_IV_LENGTH(slot->attr.type, alg);
4716     if (default_iv_length > PSA_CIPHER_IV_MAX_SIZE) {
4717         status = PSA_ERROR_GENERIC_ERROR;
4718         goto exit;
4719     }
4720 
4721     if (default_iv_length > 0) {
4722         if (output_size < default_iv_length) {
4723             status = PSA_ERROR_BUFFER_TOO_SMALL;
4724             goto exit;
4725         }
4726 
4727         status = psa_generate_random_internal(local_iv, default_iv_length);
4728         if (status != PSA_SUCCESS) {
4729             goto exit;
4730         }
4731     }
4732 
4733     LOCAL_INPUT_ALLOC(input_external, input_length, input);
4734     LOCAL_OUTPUT_ALLOC(output_external, output_size, output);
4735 
4736     status = psa_driver_wrapper_cipher_encrypt(
4737         &slot->attr, slot->key.data, slot->key.bytes,
4738         alg, local_iv, default_iv_length, input, input_length,
4739         psa_crypto_buffer_offset(output, default_iv_length),
4740         output_size - default_iv_length, output_length);
4741 
4742 exit:
4743     unlock_status = psa_unregister_read_under_mutex(slot);
4744     if (status == PSA_SUCCESS) {
4745         status = unlock_status;
4746     }
4747 
4748     if (status == PSA_SUCCESS) {
4749         if (default_iv_length > 0) {
4750             memcpy(output, local_iv, default_iv_length);
4751         }
4752         *output_length += default_iv_length;
4753     } else {
4754         *output_length = 0;
4755     }
4756 
4757     LOCAL_INPUT_FREE(input_external, input);
4758     LOCAL_OUTPUT_FREE(output_external, output);
4759 
4760     return status;
4761 }
4762 
4763 psa_status_t psa_cipher_decrypt(mbedtls_svc_key_id_t key,
4764                                 psa_algorithm_t alg,
4765                                 const uint8_t *input_external,
4766                                 size_t input_length,
4767                                 uint8_t *output_external,
4768                                 size_t output_size,
4769                                 size_t *output_length)
4770 {
4771     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4772     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
4773     psa_key_slot_t *slot = NULL;
4774 
4775     LOCAL_INPUT_DECLARE(input_external, input);
4776     LOCAL_OUTPUT_DECLARE(output_external, output);
4777 
4778     if (!PSA_ALG_IS_CIPHER(alg)) {
4779         status = PSA_ERROR_INVALID_ARGUMENT;
4780         goto exit;
4781     }
4782 
4783     status = psa_get_and_lock_key_slot_with_policy(key, &slot,
4784                                                    PSA_KEY_USAGE_DECRYPT,
4785                                                    alg);
4786     if (status != PSA_SUCCESS) {
4787         goto exit;
4788     }
4789 
4790     if (input_length < PSA_CIPHER_IV_LENGTH(slot->attr.type, alg)) {
4791         status = PSA_ERROR_INVALID_ARGUMENT;
4792         goto exit;
4793     }
4794 
4795     LOCAL_INPUT_ALLOC(input_external, input_length, input);
4796     LOCAL_OUTPUT_ALLOC(output_external, output_size, output);
4797 
4798     status = psa_driver_wrapper_cipher_decrypt(
4799         &slot->attr, slot->key.data, slot->key.bytes,
4800         alg, input, input_length,
4801         output, output_size, output_length);
4802 
4803 exit:
4804     unlock_status = psa_unregister_read_under_mutex(slot);
4805     if (status == PSA_SUCCESS) {
4806         status = unlock_status;
4807     }
4808 
4809     if (status != PSA_SUCCESS) {
4810         *output_length = 0;
4811     }
4812 
4813     LOCAL_INPUT_FREE(input_external, input);
4814     LOCAL_OUTPUT_FREE(output_external, output);
4815 
4816     return status;
4817 }
4818 
4819 
4820 /****************************************************************/
4821 /* AEAD */
4822 /****************************************************************/
4823 
4824 /* Helper function to get the base algorithm from its variants. */
4825 static psa_algorithm_t psa_aead_get_base_algorithm(psa_algorithm_t alg)
4826 {
4827     return PSA_ALG_AEAD_WITH_DEFAULT_LENGTH_TAG(alg);
4828 }
4829 
4830 /* Helper function to perform common nonce length checks. */
4831 static psa_status_t psa_aead_check_nonce_length(psa_algorithm_t alg,
4832                                                 size_t nonce_length)
4833 {
4834     psa_algorithm_t base_alg = psa_aead_get_base_algorithm(alg);
4835 
4836     switch (base_alg) {
4837 #if defined(PSA_WANT_ALG_GCM)
4838         case PSA_ALG_GCM:
4839             /* Not checking max nonce size here as GCM spec allows almost
4840              * arbitrarily large nonces. Please note that we do not generally
4841              * recommend the usage of nonces of greater length than
4842              * PSA_AEAD_NONCE_MAX_SIZE, as large nonces are hashed to a shorter
4843              * size, which can then lead to collisions if you encrypt a very
4844              * large number of messages.*/
4845             if (nonce_length != 0) {
4846                 return PSA_SUCCESS;
4847             }
4848             break;
4849 #endif /* PSA_WANT_ALG_GCM */
4850 #if defined(PSA_WANT_ALG_CCM)
4851         case PSA_ALG_CCM:
4852             if (nonce_length >= 7 && nonce_length <= 13) {
4853                 return PSA_SUCCESS;
4854             }
4855             break;
4856 #endif /* PSA_WANT_ALG_CCM */
4857 #if defined(PSA_WANT_ALG_CHACHA20_POLY1305)
4858         case PSA_ALG_CHACHA20_POLY1305:
4859             if (nonce_length == 12) {
4860                 return PSA_SUCCESS;
4861             } else if (nonce_length == 8) {
4862                 return PSA_ERROR_NOT_SUPPORTED;
4863             }
4864             break;
4865 #endif /* PSA_WANT_ALG_CHACHA20_POLY1305 */
4866         default:
4867             (void) nonce_length;
4868             return PSA_ERROR_NOT_SUPPORTED;
4869     }
4870 
4871     return PSA_ERROR_INVALID_ARGUMENT;
4872 }
4873 
4874 static psa_status_t psa_aead_check_algorithm(psa_algorithm_t alg)
4875 {
4876     if (!PSA_ALG_IS_AEAD(alg) || PSA_ALG_IS_WILDCARD(alg)) {
4877         return PSA_ERROR_INVALID_ARGUMENT;
4878     }
4879 
4880     return PSA_SUCCESS;
4881 }
4882 
4883 psa_status_t psa_aead_encrypt(mbedtls_svc_key_id_t key,
4884                               psa_algorithm_t alg,
4885                               const uint8_t *nonce_external,
4886                               size_t nonce_length,
4887                               const uint8_t *additional_data_external,
4888                               size_t additional_data_length,
4889                               const uint8_t *plaintext_external,
4890                               size_t plaintext_length,
4891                               uint8_t *ciphertext_external,
4892                               size_t ciphertext_size,
4893                               size_t *ciphertext_length)
4894 {
4895     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4896     psa_key_slot_t *slot;
4897 
4898     LOCAL_INPUT_DECLARE(nonce_external, nonce);
4899     LOCAL_INPUT_DECLARE(additional_data_external, additional_data);
4900     LOCAL_INPUT_DECLARE(plaintext_external, plaintext);
4901     LOCAL_OUTPUT_DECLARE(ciphertext_external, ciphertext);
4902 
4903     *ciphertext_length = 0;
4904 
4905     status = psa_aead_check_algorithm(alg);
4906     if (status != PSA_SUCCESS) {
4907         return status;
4908     }
4909 
4910     status = psa_get_and_lock_key_slot_with_policy(
4911         key, &slot, PSA_KEY_USAGE_ENCRYPT, alg);
4912     if (status != PSA_SUCCESS) {
4913         return status;
4914     }
4915 
4916     LOCAL_INPUT_ALLOC(nonce_external, nonce_length, nonce);
4917     LOCAL_INPUT_ALLOC(additional_data_external, additional_data_length, additional_data);
4918     LOCAL_INPUT_ALLOC(plaintext_external, plaintext_length, plaintext);
4919     LOCAL_OUTPUT_ALLOC(ciphertext_external, ciphertext_size, ciphertext);
4920 
4921     status = psa_aead_check_nonce_length(alg, nonce_length);
4922     if (status != PSA_SUCCESS) {
4923         goto exit;
4924     }
4925 
4926     status = psa_driver_wrapper_aead_encrypt(
4927         &slot->attr, slot->key.data, slot->key.bytes,
4928         alg,
4929         nonce, nonce_length,
4930         additional_data, additional_data_length,
4931         plaintext, plaintext_length,
4932         ciphertext, ciphertext_size, ciphertext_length);
4933 
4934     if (status != PSA_SUCCESS && ciphertext_size != 0) {
4935         memset(ciphertext, 0, ciphertext_size);
4936     }
4937 
4938 exit:
4939     LOCAL_INPUT_FREE(nonce_external, nonce);
4940     LOCAL_INPUT_FREE(additional_data_external, additional_data);
4941     LOCAL_INPUT_FREE(plaintext_external, plaintext);
4942     LOCAL_OUTPUT_FREE(ciphertext_external, ciphertext);
4943 
4944     psa_unregister_read_under_mutex(slot);
4945 
4946     return status;
4947 }
4948 
4949 psa_status_t psa_aead_decrypt(mbedtls_svc_key_id_t key,
4950                               psa_algorithm_t alg,
4951                               const uint8_t *nonce_external,
4952                               size_t nonce_length,
4953                               const uint8_t *additional_data_external,
4954                               size_t additional_data_length,
4955                               const uint8_t *ciphertext_external,
4956                               size_t ciphertext_length,
4957                               uint8_t *plaintext_external,
4958                               size_t plaintext_size,
4959                               size_t *plaintext_length)
4960 {
4961     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4962     psa_key_slot_t *slot;
4963 
4964     LOCAL_INPUT_DECLARE(nonce_external, nonce);
4965     LOCAL_INPUT_DECLARE(additional_data_external, additional_data);
4966     LOCAL_INPUT_DECLARE(ciphertext_external, ciphertext);
4967     LOCAL_OUTPUT_DECLARE(plaintext_external, plaintext);
4968 
4969     *plaintext_length = 0;
4970 
4971     status = psa_aead_check_algorithm(alg);
4972     if (status != PSA_SUCCESS) {
4973         return status;
4974     }
4975 
4976     status = psa_get_and_lock_key_slot_with_policy(
4977         key, &slot, PSA_KEY_USAGE_DECRYPT, alg);
4978     if (status != PSA_SUCCESS) {
4979         return status;
4980     }
4981 
4982     LOCAL_INPUT_ALLOC(nonce_external, nonce_length, nonce);
4983     LOCAL_INPUT_ALLOC(additional_data_external, additional_data_length,
4984                       additional_data);
4985     LOCAL_INPUT_ALLOC(ciphertext_external, ciphertext_length, ciphertext);
4986     LOCAL_OUTPUT_ALLOC(plaintext_external, plaintext_size, plaintext);
4987 
4988     status = psa_aead_check_nonce_length(alg, nonce_length);
4989     if (status != PSA_SUCCESS) {
4990         goto exit;
4991     }
4992 
4993     status = psa_driver_wrapper_aead_decrypt(
4994         &slot->attr, slot->key.data, slot->key.bytes,
4995         alg,
4996         nonce, nonce_length,
4997         additional_data, additional_data_length,
4998         ciphertext, ciphertext_length,
4999         plaintext, plaintext_size, plaintext_length);
5000 
5001     if (status != PSA_SUCCESS && plaintext_size != 0) {
5002         memset(plaintext, 0, plaintext_size);
5003     }
5004 
5005 exit:
5006     LOCAL_INPUT_FREE(nonce_external, nonce);
5007     LOCAL_INPUT_FREE(additional_data_external, additional_data);
5008     LOCAL_INPUT_FREE(ciphertext_external, ciphertext);
5009     LOCAL_OUTPUT_FREE(plaintext_external, plaintext);
5010 
5011     psa_unregister_read_under_mutex(slot);
5012 
5013     return status;
5014 }
5015 
5016 static psa_status_t psa_validate_tag_length(psa_algorithm_t alg)
5017 {
5018     const uint8_t tag_len = PSA_ALG_AEAD_GET_TAG_LENGTH(alg);
5019 
5020     switch (PSA_ALG_AEAD_WITH_SHORTENED_TAG(alg, 0)) {
5021 #if defined(PSA_WANT_ALG_CCM)
5022         case PSA_ALG_AEAD_WITH_SHORTENED_TAG(PSA_ALG_CCM, 0):
5023             /* CCM allows the following tag lengths: 4, 6, 8, 10, 12, 14, 16.*/
5024             if (tag_len < 4 || tag_len > 16 || tag_len % 2) {
5025                 return PSA_ERROR_INVALID_ARGUMENT;
5026             }
5027             break;
5028 #endif /* PSA_WANT_ALG_CCM */
5029 
5030 #if defined(PSA_WANT_ALG_GCM)
5031         case PSA_ALG_AEAD_WITH_SHORTENED_TAG(PSA_ALG_GCM, 0):
5032             /* GCM allows the following tag lengths: 4, 8, 12, 13, 14, 15, 16. */
5033             if (tag_len != 4 && tag_len != 8 && (tag_len < 12 || tag_len > 16)) {
5034                 return PSA_ERROR_INVALID_ARGUMENT;
5035             }
5036             break;
5037 #endif /* PSA_WANT_ALG_GCM */
5038 
5039 #if defined(PSA_WANT_ALG_CHACHA20_POLY1305)
5040         case PSA_ALG_AEAD_WITH_SHORTENED_TAG(PSA_ALG_CHACHA20_POLY1305, 0):
5041             /* We only support the default tag length. */
5042             if (tag_len != 16) {
5043                 return PSA_ERROR_INVALID_ARGUMENT;
5044             }
5045             break;
5046 #endif /* PSA_WANT_ALG_CHACHA20_POLY1305 */
5047 
5048         default:
5049             (void) tag_len;
5050             return PSA_ERROR_NOT_SUPPORTED;
5051     }
5052     return PSA_SUCCESS;
5053 }
5054 
5055 /* Set the key for a multipart authenticated operation. */
5056 static psa_status_t psa_aead_setup(psa_aead_operation_t *operation,
5057                                    int is_encrypt,
5058                                    mbedtls_svc_key_id_t key,
5059                                    psa_algorithm_t alg)
5060 {
5061     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
5062     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
5063     psa_key_slot_t *slot = NULL;
5064     psa_key_usage_t key_usage = 0;
5065 
5066     status = psa_aead_check_algorithm(alg);
5067     if (status != PSA_SUCCESS) {
5068         goto exit;
5069     }
5070 
5071     if (operation->id != 0) {
5072         status = PSA_ERROR_BAD_STATE;
5073         goto exit;
5074     }
5075 
5076     if (operation->nonce_set || operation->lengths_set ||
5077         operation->ad_started || operation->body_started) {
5078         status = PSA_ERROR_BAD_STATE;
5079         goto exit;
5080     }
5081 
5082     if (is_encrypt) {
5083         key_usage = PSA_KEY_USAGE_ENCRYPT;
5084     } else {
5085         key_usage = PSA_KEY_USAGE_DECRYPT;
5086     }
5087 
5088     status = psa_get_and_lock_key_slot_with_policy(key, &slot, key_usage,
5089                                                    alg);
5090     if (status != PSA_SUCCESS) {
5091         goto exit;
5092     }
5093 
5094     if ((status = psa_validate_tag_length(alg)) != PSA_SUCCESS) {
5095         goto exit;
5096     }
5097 
5098     if (is_encrypt) {
5099         status = psa_driver_wrapper_aead_encrypt_setup(operation,
5100                                                        &slot->attr,
5101                                                        slot->key.data,
5102                                                        slot->key.bytes,
5103                                                        alg);
5104     } else {
5105         status = psa_driver_wrapper_aead_decrypt_setup(operation,
5106                                                        &slot->attr,
5107                                                        slot->key.data,
5108                                                        slot->key.bytes,
5109                                                        alg);
5110     }
5111     if (status != PSA_SUCCESS) {
5112         goto exit;
5113     }
5114 
5115     operation->key_type = psa_get_key_type(&slot->attr);
5116 
5117 exit:
5118     unlock_status = psa_unregister_read_under_mutex(slot);
5119 
5120     if (status == PSA_SUCCESS) {
5121         status = unlock_status;
5122         operation->alg = psa_aead_get_base_algorithm(alg);
5123         operation->is_encrypt = is_encrypt;
5124     } else {
5125         psa_aead_abort(operation);
5126     }
5127 
5128     return status;
5129 }
5130 
5131 /* Set the key for a multipart authenticated encryption operation. */
5132 psa_status_t psa_aead_encrypt_setup(psa_aead_operation_t *operation,
5133                                     mbedtls_svc_key_id_t key,
5134                                     psa_algorithm_t alg)
5135 {
5136     return psa_aead_setup(operation, 1, key, alg);
5137 }
5138 
5139 /* Set the key for a multipart authenticated decryption operation. */
5140 psa_status_t psa_aead_decrypt_setup(psa_aead_operation_t *operation,
5141                                     mbedtls_svc_key_id_t key,
5142                                     psa_algorithm_t alg)
5143 {
5144     return psa_aead_setup(operation, 0, key, alg);
5145 }
5146 
5147 static psa_status_t psa_aead_set_nonce_internal(psa_aead_operation_t *operation,
5148                                                 const uint8_t *nonce,
5149                                                 size_t nonce_length)
5150 {
5151     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
5152 
5153     if (operation->id == 0) {
5154         status = PSA_ERROR_BAD_STATE;
5155         goto exit;
5156     }
5157 
5158     if (operation->nonce_set) {
5159         status = PSA_ERROR_BAD_STATE;
5160         goto exit;
5161     }
5162 
5163     status = psa_aead_check_nonce_length(operation->alg, nonce_length);
5164     if (status != PSA_SUCCESS) {
5165         status = PSA_ERROR_INVALID_ARGUMENT;
5166         goto exit;
5167     }
5168 
5169     status = psa_driver_wrapper_aead_set_nonce(operation, nonce,
5170                                                nonce_length);
5171 
5172 exit:
5173     if (status == PSA_SUCCESS) {
5174         operation->nonce_set = 1;
5175     } else {
5176         psa_aead_abort(operation);
5177     }
5178 
5179     return status;
5180 }
5181 
5182 /* Generate a random nonce / IV for multipart AEAD operation */
5183 psa_status_t psa_aead_generate_nonce(psa_aead_operation_t *operation,
5184                                      uint8_t *nonce_external,
5185                                      size_t nonce_size,
5186                                      size_t *nonce_length)
5187 {
5188     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
5189     uint8_t local_nonce[PSA_AEAD_NONCE_MAX_SIZE];
5190     size_t required_nonce_size = 0;
5191 
5192     LOCAL_OUTPUT_DECLARE(nonce_external, nonce);
5193     LOCAL_OUTPUT_ALLOC(nonce_external, nonce_size, nonce);
5194 
5195     *nonce_length = 0;
5196 
5197     if (operation->id == 0) {
5198         status = PSA_ERROR_BAD_STATE;
5199         goto exit;
5200     }
5201 
5202     if (operation->nonce_set || !operation->is_encrypt) {
5203         status = PSA_ERROR_BAD_STATE;
5204         goto exit;
5205     }
5206 
5207     /* For CCM, this size may not be correct according to the PSA
5208      * specification. The PSA Crypto 1.0.1 specification states:
5209      *
5210      * CCM encodes the plaintext length pLen in L octets, with L the smallest
5211      * integer >= 2 where pLen < 2^(8L). The nonce length is then 15 - L bytes.
5212      *
5213      * However this restriction that L has to be the smallest integer is not
5214      * applied in practice, and it is not implementable here since the
5215      * plaintext length may or may not be known at this time. */
5216     required_nonce_size = PSA_AEAD_NONCE_LENGTH(operation->key_type,
5217                                                 operation->alg);
5218     if (nonce_size < required_nonce_size) {
5219         status = PSA_ERROR_BUFFER_TOO_SMALL;
5220         goto exit;
5221     }
5222 
5223     status = psa_generate_random_internal(local_nonce, required_nonce_size);
5224     if (status != PSA_SUCCESS) {
5225         goto exit;
5226     }
5227 
5228     status = psa_aead_set_nonce_internal(operation, local_nonce,
5229                                          required_nonce_size);
5230 
5231 exit:
5232     if (status == PSA_SUCCESS) {
5233         memcpy(nonce, local_nonce, required_nonce_size);
5234         *nonce_length = required_nonce_size;
5235     } else {
5236         psa_aead_abort(operation);
5237     }
5238 
5239     LOCAL_OUTPUT_FREE(nonce_external, nonce);
5240 
5241     return status;
5242 }
5243 
5244 /* Set the nonce for a multipart authenticated encryption or decryption
5245    operation.*/
5246 psa_status_t psa_aead_set_nonce(psa_aead_operation_t *operation,
5247                                 const uint8_t *nonce_external,
5248                                 size_t nonce_length)
5249 {
5250     psa_status_t status;
5251 
5252     LOCAL_INPUT_DECLARE(nonce_external, nonce);
5253     LOCAL_INPUT_ALLOC(nonce_external, nonce_length, nonce);
5254 
5255     status = psa_aead_set_nonce_internal(operation, nonce, nonce_length);
5256 
5257 /* Exit label is only needed for buffer copying, prevent unused warnings. */
5258 #if !defined(MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS)
5259 exit:
5260 #endif
5261 
5262     LOCAL_INPUT_FREE(nonce_external, nonce);
5263 
5264     return status;
5265 }
5266 
5267 /* Declare the lengths of the message and additional data for multipart AEAD. */
5268 psa_status_t psa_aead_set_lengths(psa_aead_operation_t *operation,
5269                                   size_t ad_length,
5270                                   size_t plaintext_length)
5271 {
5272     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
5273 
5274     if (operation->id == 0) {
5275         status = PSA_ERROR_BAD_STATE;
5276         goto exit;
5277     }
5278 
5279     if (operation->lengths_set || operation->ad_started ||
5280         operation->body_started) {
5281         status = PSA_ERROR_BAD_STATE;
5282         goto exit;
5283     }
5284 
5285     switch (operation->alg) {
5286 #if defined(PSA_WANT_ALG_GCM)
5287         case PSA_ALG_GCM:
5288             /* Lengths can only be too large for GCM if size_t is bigger than 32
5289              * bits. Without the guard this code will generate warnings on 32bit
5290              * builds. */
5291 #if SIZE_MAX > UINT32_MAX
5292             if (((uint64_t) ad_length) >> 61 != 0 ||
5293                 ((uint64_t) plaintext_length) > 0xFFFFFFFE0ull) {
5294                 status = PSA_ERROR_INVALID_ARGUMENT;
5295                 goto exit;
5296             }
5297 #endif
5298             break;
5299 #endif /* PSA_WANT_ALG_GCM */
5300 #if defined(PSA_WANT_ALG_CCM)
5301         case PSA_ALG_CCM:
5302             if (ad_length > 0xFF00) {
5303                 status = PSA_ERROR_INVALID_ARGUMENT;
5304                 goto exit;
5305             }
5306             break;
5307 #endif /* PSA_WANT_ALG_CCM */
5308 #if defined(PSA_WANT_ALG_CHACHA20_POLY1305)
5309         case PSA_ALG_CHACHA20_POLY1305:
5310             /* No length restrictions for ChaChaPoly. */
5311             break;
5312 #endif /* PSA_WANT_ALG_CHACHA20_POLY1305 */
5313         default:
5314             break;
5315     }
5316 
5317     status = psa_driver_wrapper_aead_set_lengths(operation, ad_length,
5318                                                  plaintext_length);
5319 
5320 exit:
5321     if (status == PSA_SUCCESS) {
5322         operation->ad_remaining = ad_length;
5323         operation->body_remaining = plaintext_length;
5324         operation->lengths_set = 1;
5325     } else {
5326         psa_aead_abort(operation);
5327     }
5328 
5329     return status;
5330 }
5331 
5332 /* Pass additional data to an active multipart AEAD operation. */
5333 psa_status_t psa_aead_update_ad(psa_aead_operation_t *operation,
5334                                 const uint8_t *input_external,
5335                                 size_t input_length)
5336 {
5337     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
5338 
5339     LOCAL_INPUT_DECLARE(input_external, input);
5340     LOCAL_INPUT_ALLOC(input_external, input_length, input);
5341 
5342     if (operation->id == 0) {
5343         status = PSA_ERROR_BAD_STATE;
5344         goto exit;
5345     }
5346 
5347     if (!operation->nonce_set || operation->body_started) {
5348         status = PSA_ERROR_BAD_STATE;
5349         goto exit;
5350     }
5351 
5352     /* No input to add (zero length), nothing to do. */
5353     if (input_length == 0) {
5354         status = PSA_SUCCESS;
5355         goto exit;
5356     }
5357 
5358     if (operation->lengths_set) {
5359         if (operation->ad_remaining < input_length) {
5360             status = PSA_ERROR_INVALID_ARGUMENT;
5361             goto exit;
5362         }
5363 
5364         operation->ad_remaining -= input_length;
5365     }
5366 #if defined(PSA_WANT_ALG_CCM)
5367     else if (operation->alg == PSA_ALG_CCM) {
5368         status = PSA_ERROR_BAD_STATE;
5369         goto exit;
5370     }
5371 #endif /* PSA_WANT_ALG_CCM */
5372 
5373     status = psa_driver_wrapper_aead_update_ad(operation, input,
5374                                                input_length);
5375 
5376 exit:
5377     if (status == PSA_SUCCESS) {
5378         operation->ad_started = 1;
5379     } else {
5380         psa_aead_abort(operation);
5381     }
5382 
5383     LOCAL_INPUT_FREE(input_external, input);
5384 
5385     return status;
5386 }
5387 
5388 /* Encrypt or decrypt a message fragment in an active multipart AEAD
5389    operation.*/
5390 psa_status_t psa_aead_update(psa_aead_operation_t *operation,
5391                              const uint8_t *input_external,
5392                              size_t input_length,
5393                              uint8_t *output_external,
5394                              size_t output_size,
5395                              size_t *output_length)
5396 {
5397     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
5398 
5399 
5400     LOCAL_INPUT_DECLARE(input_external, input);
5401     LOCAL_OUTPUT_DECLARE(output_external, output);
5402 
5403     LOCAL_INPUT_ALLOC(input_external, input_length, input);
5404     LOCAL_OUTPUT_ALLOC(output_external, output_size, output);
5405 
5406     *output_length = 0;
5407 
5408     if (operation->id == 0) {
5409         status = PSA_ERROR_BAD_STATE;
5410         goto exit;
5411     }
5412 
5413     if (!operation->nonce_set) {
5414         status = PSA_ERROR_BAD_STATE;
5415         goto exit;
5416     }
5417 
5418     if (operation->lengths_set) {
5419         /* Additional data length was supplied, but not all the additional
5420            data was supplied.*/
5421         if (operation->ad_remaining != 0) {
5422             status = PSA_ERROR_INVALID_ARGUMENT;
5423             goto exit;
5424         }
5425 
5426         /* Too much data provided. */
5427         if (operation->body_remaining < input_length) {
5428             status = PSA_ERROR_INVALID_ARGUMENT;
5429             goto exit;
5430         }
5431 
5432         operation->body_remaining -= input_length;
5433     }
5434 #if defined(PSA_WANT_ALG_CCM)
5435     else if (operation->alg == PSA_ALG_CCM) {
5436         status = PSA_ERROR_BAD_STATE;
5437         goto exit;
5438     }
5439 #endif /* PSA_WANT_ALG_CCM */
5440 
5441     status = psa_driver_wrapper_aead_update(operation, input, input_length,
5442                                             output, output_size,
5443                                             output_length);
5444 
5445 exit:
5446     if (status == PSA_SUCCESS) {
5447         operation->body_started = 1;
5448     } else {
5449         psa_aead_abort(operation);
5450     }
5451 
5452     LOCAL_INPUT_FREE(input_external, input);
5453     LOCAL_OUTPUT_FREE(output_external, output);
5454 
5455     return status;
5456 }
5457 
5458 static psa_status_t psa_aead_final_checks(const psa_aead_operation_t *operation)
5459 {
5460     if (operation->id == 0 || !operation->nonce_set) {
5461         return PSA_ERROR_BAD_STATE;
5462     }
5463 
5464     if (operation->lengths_set && (operation->ad_remaining != 0 ||
5465                                    operation->body_remaining != 0)) {
5466         return PSA_ERROR_INVALID_ARGUMENT;
5467     }
5468 
5469     return PSA_SUCCESS;
5470 }
5471 
5472 /* Finish encrypting a message in a multipart AEAD operation. */
5473 psa_status_t psa_aead_finish(psa_aead_operation_t *operation,
5474                              uint8_t *ciphertext_external,
5475                              size_t ciphertext_size,
5476                              size_t *ciphertext_length,
5477                              uint8_t *tag_external,
5478                              size_t tag_size,
5479                              size_t *tag_length)
5480 {
5481     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
5482 
5483     LOCAL_OUTPUT_DECLARE(ciphertext_external, ciphertext);
5484     LOCAL_OUTPUT_DECLARE(tag_external, tag);
5485 
5486     LOCAL_OUTPUT_ALLOC(ciphertext_external, ciphertext_size, ciphertext);
5487     LOCAL_OUTPUT_ALLOC(tag_external, tag_size, tag);
5488 
5489     *ciphertext_length = 0;
5490     *tag_length = tag_size;
5491 
5492     status = psa_aead_final_checks(operation);
5493     if (status != PSA_SUCCESS) {
5494         goto exit;
5495     }
5496 
5497     if (!operation->is_encrypt) {
5498         status = PSA_ERROR_BAD_STATE;
5499         goto exit;
5500     }
5501 
5502     status = psa_driver_wrapper_aead_finish(operation, ciphertext,
5503                                             ciphertext_size,
5504                                             ciphertext_length,
5505                                             tag, tag_size, tag_length);
5506 
5507 exit:
5508 
5509 
5510     /* In case the operation fails and the user fails to check for failure or
5511      * the zero tag size, make sure the tag is set to something implausible.
5512      * Even if the operation succeeds, make sure we clear the rest of the
5513      * buffer to prevent potential leakage of anything previously placed in
5514      * the same buffer.*/
5515     psa_wipe_tag_output_buffer(tag, status, tag_size, *tag_length);
5516 
5517     psa_aead_abort(operation);
5518 
5519     LOCAL_OUTPUT_FREE(ciphertext_external, ciphertext);
5520     LOCAL_OUTPUT_FREE(tag_external, tag);
5521 
5522     return status;
5523 }
5524 
5525 /* Finish authenticating and decrypting a message in a multipart AEAD
5526    operation.*/
5527 psa_status_t psa_aead_verify(psa_aead_operation_t *operation,
5528                              uint8_t *plaintext_external,
5529                              size_t plaintext_size,
5530                              size_t *plaintext_length,
5531                              const uint8_t *tag_external,
5532                              size_t tag_length)
5533 {
5534     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
5535 
5536     LOCAL_OUTPUT_DECLARE(plaintext_external, plaintext);
5537     LOCAL_INPUT_DECLARE(tag_external, tag);
5538 
5539     LOCAL_OUTPUT_ALLOC(plaintext_external, plaintext_size, plaintext);
5540     LOCAL_INPUT_ALLOC(tag_external, tag_length, tag);
5541 
5542     *plaintext_length = 0;
5543 
5544     status = psa_aead_final_checks(operation);
5545     if (status != PSA_SUCCESS) {
5546         goto exit;
5547     }
5548 
5549     if (operation->is_encrypt) {
5550         status = PSA_ERROR_BAD_STATE;
5551         goto exit;
5552     }
5553 
5554     status = psa_driver_wrapper_aead_verify(operation, plaintext,
5555                                             plaintext_size,
5556                                             plaintext_length,
5557                                             tag, tag_length);
5558 
5559 exit:
5560     psa_aead_abort(operation);
5561 
5562     LOCAL_OUTPUT_FREE(plaintext_external, plaintext);
5563     LOCAL_INPUT_FREE(tag_external, tag);
5564 
5565     return status;
5566 }
5567 
5568 /* Abort an AEAD operation. */
5569 psa_status_t psa_aead_abort(psa_aead_operation_t *operation)
5570 {
5571     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
5572 
5573     if (operation->id == 0) {
5574         /* The object has (apparently) been initialized but it is not (yet)
5575          * in use. It's ok to call abort on such an object, and there's
5576          * nothing to do. */
5577         return PSA_SUCCESS;
5578     }
5579 
5580     status = psa_driver_wrapper_aead_abort(operation);
5581 
5582     memset(operation, 0, sizeof(*operation));
5583 
5584     return status;
5585 }
5586 
5587 /****************************************************************/
5588 /* Generators */
5589 /****************************************************************/
5590 
5591 #if defined(BUILTIN_ALG_ANY_HKDF) || \
5592     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
5593     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS) || \
5594     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS) || \
5595     defined(PSA_HAVE_SOFT_PBKDF2)
5596 #define AT_LEAST_ONE_BUILTIN_KDF
5597 #endif /* At least one builtin KDF */
5598 
5599 #if defined(BUILTIN_ALG_ANY_HKDF) || \
5600     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
5601     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
5602 static psa_status_t psa_key_derivation_start_hmac(
5603     psa_mac_operation_t *operation,
5604     psa_algorithm_t hash_alg,
5605     const uint8_t *hmac_key,
5606     size_t hmac_key_length)
5607 {
5608     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
5609     psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
5610     psa_set_key_type(&attributes, PSA_KEY_TYPE_HMAC);
5611     psa_set_key_bits(&attributes, PSA_BYTES_TO_BITS(hmac_key_length));
5612     psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_HASH);
5613 
5614     operation->is_sign = 1;
5615     operation->mac_size = PSA_HASH_LENGTH(hash_alg);
5616 
5617     status = psa_driver_wrapper_mac_sign_setup(operation,
5618                                                &attributes,
5619                                                hmac_key, hmac_key_length,
5620                                                PSA_ALG_HMAC(hash_alg));
5621 
5622     psa_reset_key_attributes(&attributes);
5623     return status;
5624 }
5625 #endif /* KDF algorithms reliant on HMAC */
5626 
5627 #define HKDF_STATE_INIT 0 /* no input yet */
5628 #define HKDF_STATE_STARTED 1 /* got salt */
5629 #define HKDF_STATE_KEYED 2 /* got key */
5630 #define HKDF_STATE_OUTPUT 3 /* output started */
5631 
5632 static psa_algorithm_t psa_key_derivation_get_kdf_alg(
5633     const psa_key_derivation_operation_t *operation)
5634 {
5635     if (PSA_ALG_IS_KEY_AGREEMENT(operation->alg)) {
5636         return PSA_ALG_KEY_AGREEMENT_GET_KDF(operation->alg);
5637     } else {
5638         return operation->alg;
5639     }
5640 }
5641 
5642 psa_status_t psa_key_derivation_abort(psa_key_derivation_operation_t *operation)
5643 {
5644     psa_status_t status = PSA_SUCCESS;
5645     psa_algorithm_t kdf_alg = psa_key_derivation_get_kdf_alg(operation);
5646     if (kdf_alg == 0) {
5647         /* The object has (apparently) been initialized but it is not
5648          * in use. It's ok to call abort on such an object, and there's
5649          * nothing to do. */
5650     } else
5651 #if defined(BUILTIN_ALG_ANY_HKDF)
5652     if (PSA_ALG_IS_ANY_HKDF(kdf_alg)) {
5653         mbedtls_free(operation->ctx.hkdf.info);
5654         status = psa_mac_abort(&operation->ctx.hkdf.hmac);
5655     } else
5656 #endif /* BUILTIN_ALG_ANY_HKDF */
5657 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
5658     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
5659     if (PSA_ALG_IS_TLS12_PRF(kdf_alg) ||
5660         /* TLS-1.2 PSK-to-MS KDF uses the same core as TLS-1.2 PRF */
5661         PSA_ALG_IS_TLS12_PSK_TO_MS(kdf_alg)) {
5662         if (operation->ctx.tls12_prf.secret != NULL) {
5663             mbedtls_zeroize_and_free(operation->ctx.tls12_prf.secret,
5664                                      operation->ctx.tls12_prf.secret_length);
5665         }
5666 
5667         if (operation->ctx.tls12_prf.seed != NULL) {
5668             mbedtls_zeroize_and_free(operation->ctx.tls12_prf.seed,
5669                                      operation->ctx.tls12_prf.seed_length);
5670         }
5671 
5672         if (operation->ctx.tls12_prf.label != NULL) {
5673             mbedtls_zeroize_and_free(operation->ctx.tls12_prf.label,
5674                                      operation->ctx.tls12_prf.label_length);
5675         }
5676 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
5677         if (operation->ctx.tls12_prf.other_secret != NULL) {
5678             mbedtls_zeroize_and_free(operation->ctx.tls12_prf.other_secret,
5679                                      operation->ctx.tls12_prf.other_secret_length);
5680         }
5681 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
5682         status = PSA_SUCCESS;
5683 
5684         /* We leave the fields Ai and output_block to be erased safely by the
5685          * mbedtls_platform_zeroize() in the end of this function. */
5686     } else
5687 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) ||
5688         * defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS) */
5689 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS)
5690     if (kdf_alg == PSA_ALG_TLS12_ECJPAKE_TO_PMS) {
5691         mbedtls_platform_zeroize(operation->ctx.tls12_ecjpake_to_pms.data,
5692                                  sizeof(operation->ctx.tls12_ecjpake_to_pms.data));
5693     } else
5694 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS) */
5695 #if defined(PSA_HAVE_SOFT_PBKDF2)
5696     if (PSA_ALG_IS_PBKDF2(kdf_alg)) {
5697         if (operation->ctx.pbkdf2.salt != NULL) {
5698             mbedtls_zeroize_and_free(operation->ctx.pbkdf2.salt,
5699                                      operation->ctx.pbkdf2.salt_length);
5700         }
5701 
5702         status = PSA_SUCCESS;
5703     } else
5704 #endif /* defined(PSA_HAVE_SOFT_PBKDF2) */
5705     {
5706         status = PSA_ERROR_BAD_STATE;
5707     }
5708     mbedtls_platform_zeroize(operation, sizeof(*operation));
5709     return status;
5710 }
5711 
5712 psa_status_t psa_key_derivation_get_capacity(const psa_key_derivation_operation_t *operation,
5713                                              size_t *capacity)
5714 {
5715     if (operation->alg == 0) {
5716         /* This is a blank key derivation operation. */
5717         return PSA_ERROR_BAD_STATE;
5718     }
5719 
5720     *capacity = operation->capacity;
5721     return PSA_SUCCESS;
5722 }
5723 
5724 psa_status_t psa_key_derivation_set_capacity(psa_key_derivation_operation_t *operation,
5725                                              size_t capacity)
5726 {
5727     if (operation->alg == 0) {
5728         return PSA_ERROR_BAD_STATE;
5729     }
5730     if (capacity > operation->capacity) {
5731         return PSA_ERROR_INVALID_ARGUMENT;
5732     }
5733     operation->capacity = capacity;
5734     return PSA_SUCCESS;
5735 }
5736 
5737 #if defined(BUILTIN_ALG_ANY_HKDF)
5738 /* Read some bytes from an HKDF-based operation. */
5739 static psa_status_t psa_key_derivation_hkdf_read(psa_hkdf_key_derivation_t *hkdf,
5740                                                  psa_algorithm_t kdf_alg,
5741                                                  uint8_t *output,
5742                                                  size_t output_length)
5743 {
5744     psa_algorithm_t hash_alg = PSA_ALG_HKDF_GET_HASH(kdf_alg);
5745     uint8_t hash_length = PSA_HASH_LENGTH(hash_alg);
5746     size_t hmac_output_length;
5747     psa_status_t status;
5748 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT)
5749     const uint8_t last_block = PSA_ALG_IS_HKDF_EXTRACT(kdf_alg) ? 0 : 0xff;
5750 #else
5751     const uint8_t last_block = 0xff;
5752 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT */
5753 
5754     if (hkdf->state < HKDF_STATE_KEYED ||
5755         (!hkdf->info_set
5756 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT)
5757          && !PSA_ALG_IS_HKDF_EXTRACT(kdf_alg)
5758 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT */
5759         )) {
5760         return PSA_ERROR_BAD_STATE;
5761     }
5762     hkdf->state = HKDF_STATE_OUTPUT;
5763 
5764     while (output_length != 0) {
5765         /* Copy what remains of the current block */
5766         uint8_t n = hash_length - hkdf->offset_in_block;
5767         if (n > output_length) {
5768             n = (uint8_t) output_length;
5769         }
5770         memcpy(output, hkdf->output_block + hkdf->offset_in_block, n);
5771         output += n;
5772         output_length -= n;
5773         hkdf->offset_in_block += n;
5774         if (output_length == 0) {
5775             break;
5776         }
5777         /* We can't be wanting more output after the last block, otherwise
5778          * the capacity check in psa_key_derivation_output_bytes() would have
5779          * prevented this call. It could happen only if the operation
5780          * object was corrupted or if this function is called directly
5781          * inside the library. */
5782         if (hkdf->block_number == last_block) {
5783             return PSA_ERROR_BAD_STATE;
5784         }
5785 
5786         /* We need a new block */
5787         ++hkdf->block_number;
5788         hkdf->offset_in_block = 0;
5789 
5790         status = psa_key_derivation_start_hmac(&hkdf->hmac,
5791                                                hash_alg,
5792                                                hkdf->prk,
5793                                                hash_length);
5794         if (status != PSA_SUCCESS) {
5795             return status;
5796         }
5797 
5798         if (hkdf->block_number != 1) {
5799             status = psa_mac_update(&hkdf->hmac,
5800                                     hkdf->output_block,
5801                                     hash_length);
5802             if (status != PSA_SUCCESS) {
5803                 return status;
5804             }
5805         }
5806         status = psa_mac_update(&hkdf->hmac,
5807                                 hkdf->info,
5808                                 hkdf->info_length);
5809         if (status != PSA_SUCCESS) {
5810             return status;
5811         }
5812         status = psa_mac_update(&hkdf->hmac,
5813                                 &hkdf->block_number, 1);
5814         if (status != PSA_SUCCESS) {
5815             return status;
5816         }
5817         status = psa_mac_sign_finish(&hkdf->hmac,
5818                                      hkdf->output_block,
5819                                      sizeof(hkdf->output_block),
5820                                      &hmac_output_length);
5821         if (status != PSA_SUCCESS) {
5822             return status;
5823         }
5824     }
5825 
5826     return PSA_SUCCESS;
5827 }
5828 #endif /* BUILTIN_ALG_ANY_HKDF */
5829 
5830 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
5831     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
5832 static psa_status_t psa_key_derivation_tls12_prf_generate_next_block(
5833     psa_tls12_prf_key_derivation_t *tls12_prf,
5834     psa_algorithm_t alg)
5835 {
5836     psa_algorithm_t hash_alg = PSA_ALG_HKDF_GET_HASH(alg);
5837     uint8_t hash_length = PSA_HASH_LENGTH(hash_alg);
5838     psa_mac_operation_t hmac = PSA_MAC_OPERATION_INIT;
5839     size_t hmac_output_length;
5840     psa_status_t status, cleanup_status;
5841 
5842     /* We can't be wanting more output after block 0xff, 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 (tls12_prf->block_number == 0xff) {
5848         return PSA_ERROR_CORRUPTION_DETECTED;
5849     }
5850 
5851     /* We need a new block */
5852     ++tls12_prf->block_number;
5853     tls12_prf->left_in_block = hash_length;
5854 
5855     /* Recall the definition of the TLS-1.2-PRF from RFC 5246:
5856      *
5857      * PRF(secret, label, seed) = P_<hash>(secret, label + seed)
5858      *
5859      * P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
5860      *                        HMAC_hash(secret, A(2) + seed) +
5861      *                        HMAC_hash(secret, A(3) + seed) + ...
5862      *
5863      * A(0) = seed
5864      * A(i) = HMAC_hash(secret, A(i-1))
5865      *
5866      * The `psa_tls12_prf_key_derivation` structure saves the block
5867      * `HMAC_hash(secret, A(i) + seed)` from which the output
5868      * is currently extracted as `output_block` and where i is
5869      * `block_number`.
5870      */
5871 
5872     status = psa_key_derivation_start_hmac(&hmac,
5873                                            hash_alg,
5874                                            tls12_prf->secret,
5875                                            tls12_prf->secret_length);
5876     if (status != PSA_SUCCESS) {
5877         goto cleanup;
5878     }
5879 
5880     /* Calculate A(i) where i = tls12_prf->block_number. */
5881     if (tls12_prf->block_number == 1) {
5882         /* A(1) = HMAC_hash(secret, A(0)), where A(0) = seed. (The RFC overloads
5883          * the variable seed and in this instance means it in the context of the
5884          * P_hash function, where seed = label + seed.) */
5885         status = psa_mac_update(&hmac,
5886                                 tls12_prf->label,
5887                                 tls12_prf->label_length);
5888         if (status != PSA_SUCCESS) {
5889             goto cleanup;
5890         }
5891         status = psa_mac_update(&hmac,
5892                                 tls12_prf->seed,
5893                                 tls12_prf->seed_length);
5894         if (status != PSA_SUCCESS) {
5895             goto cleanup;
5896         }
5897     } else {
5898         /* A(i) = HMAC_hash(secret, A(i-1)) */
5899         status = psa_mac_update(&hmac, tls12_prf->Ai, hash_length);
5900         if (status != PSA_SUCCESS) {
5901             goto cleanup;
5902         }
5903     }
5904 
5905     status = psa_mac_sign_finish(&hmac,
5906                                  tls12_prf->Ai, hash_length,
5907                                  &hmac_output_length);
5908     if (hmac_output_length != hash_length) {
5909         status = PSA_ERROR_CORRUPTION_DETECTED;
5910     }
5911     if (status != PSA_SUCCESS) {
5912         goto cleanup;
5913     }
5914 
5915     /* Calculate HMAC_hash(secret, A(i) + label + seed). */
5916     status = psa_key_derivation_start_hmac(&hmac,
5917                                            hash_alg,
5918                                            tls12_prf->secret,
5919                                            tls12_prf->secret_length);
5920     if (status != PSA_SUCCESS) {
5921         goto cleanup;
5922     }
5923     status = psa_mac_update(&hmac, tls12_prf->Ai, hash_length);
5924     if (status != PSA_SUCCESS) {
5925         goto cleanup;
5926     }
5927     status = psa_mac_update(&hmac, tls12_prf->label, tls12_prf->label_length);
5928     if (status != PSA_SUCCESS) {
5929         goto cleanup;
5930     }
5931     status = psa_mac_update(&hmac, tls12_prf->seed, tls12_prf->seed_length);
5932     if (status != PSA_SUCCESS) {
5933         goto cleanup;
5934     }
5935     status = psa_mac_sign_finish(&hmac,
5936                                  tls12_prf->output_block, hash_length,
5937                                  &hmac_output_length);
5938     if (status != PSA_SUCCESS) {
5939         goto cleanup;
5940     }
5941 
5942 
5943 cleanup:
5944     cleanup_status = psa_mac_abort(&hmac);
5945     if (status == PSA_SUCCESS && cleanup_status != PSA_SUCCESS) {
5946         status = cleanup_status;
5947     }
5948 
5949     return status;
5950 }
5951 
5952 static psa_status_t psa_key_derivation_tls12_prf_read(
5953     psa_tls12_prf_key_derivation_t *tls12_prf,
5954     psa_algorithm_t alg,
5955     uint8_t *output,
5956     size_t output_length)
5957 {
5958     psa_algorithm_t hash_alg = PSA_ALG_TLS12_PRF_GET_HASH(alg);
5959     uint8_t hash_length = PSA_HASH_LENGTH(hash_alg);
5960     psa_status_t status;
5961     uint8_t offset, length;
5962 
5963     switch (tls12_prf->state) {
5964         case PSA_TLS12_PRF_STATE_LABEL_SET:
5965             tls12_prf->state = PSA_TLS12_PRF_STATE_OUTPUT;
5966             break;
5967         case PSA_TLS12_PRF_STATE_OUTPUT:
5968             break;
5969         default:
5970             return PSA_ERROR_BAD_STATE;
5971     }
5972 
5973     while (output_length != 0) {
5974         /* Check if we have fully processed the current block. */
5975         if (tls12_prf->left_in_block == 0) {
5976             status = psa_key_derivation_tls12_prf_generate_next_block(tls12_prf,
5977                                                                       alg);
5978             if (status != PSA_SUCCESS) {
5979                 return status;
5980             }
5981 
5982             continue;
5983         }
5984 
5985         if (tls12_prf->left_in_block > output_length) {
5986             length = (uint8_t) output_length;
5987         } else {
5988             length = tls12_prf->left_in_block;
5989         }
5990 
5991         offset = hash_length - tls12_prf->left_in_block;
5992         memcpy(output, tls12_prf->output_block + offset, length);
5993         output += length;
5994         output_length -= length;
5995         tls12_prf->left_in_block -= length;
5996     }
5997 
5998     return PSA_SUCCESS;
5999 }
6000 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF ||
6001         * MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
6002 
6003 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS)
6004 static psa_status_t psa_key_derivation_tls12_ecjpake_to_pms_read(
6005     psa_tls12_ecjpake_to_pms_t *ecjpake,
6006     uint8_t *output,
6007     size_t output_length)
6008 {
6009     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
6010     size_t output_size = 0;
6011 
6012     if (output_length != 32) {
6013         return PSA_ERROR_INVALID_ARGUMENT;
6014     }
6015 
6016     status = psa_hash_compute(PSA_ALG_SHA_256, ecjpake->data,
6017                               PSA_TLS12_ECJPAKE_TO_PMS_DATA_SIZE, output, output_length,
6018                               &output_size);
6019     if (status != PSA_SUCCESS) {
6020         return status;
6021     }
6022 
6023     if (output_size != output_length) {
6024         return PSA_ERROR_GENERIC_ERROR;
6025     }
6026 
6027     return PSA_SUCCESS;
6028 }
6029 #endif
6030 
6031 #if defined(PSA_HAVE_SOFT_PBKDF2)
6032 static psa_status_t psa_key_derivation_pbkdf2_generate_block(
6033     psa_pbkdf2_key_derivation_t *pbkdf2,
6034     psa_algorithm_t prf_alg,
6035     uint8_t prf_output_length,
6036     psa_key_attributes_t *attributes)
6037 {
6038     psa_status_t status;
6039     psa_mac_operation_t mac_operation = PSA_MAC_OPERATION_INIT;
6040     size_t mac_output_length;
6041     uint8_t U_i[PSA_MAC_MAX_SIZE];
6042     uint8_t *U_accumulator = pbkdf2->output_block;
6043     uint64_t i;
6044     uint8_t block_counter[4];
6045 
6046     mac_operation.is_sign = 1;
6047     mac_operation.mac_size = prf_output_length;
6048     MBEDTLS_PUT_UINT32_BE(pbkdf2->block_number, block_counter, 0);
6049 
6050     status = psa_driver_wrapper_mac_sign_setup(&mac_operation,
6051                                                attributes,
6052                                                pbkdf2->password,
6053                                                pbkdf2->password_length,
6054                                                prf_alg);
6055     if (status != PSA_SUCCESS) {
6056         goto cleanup;
6057     }
6058     status = psa_mac_update(&mac_operation, pbkdf2->salt, pbkdf2->salt_length);
6059     if (status != PSA_SUCCESS) {
6060         goto cleanup;
6061     }
6062     status = psa_mac_update(&mac_operation, block_counter, sizeof(block_counter));
6063     if (status != PSA_SUCCESS) {
6064         goto cleanup;
6065     }
6066     status = psa_mac_sign_finish(&mac_operation, U_i, sizeof(U_i),
6067                                  &mac_output_length);
6068     if (status != PSA_SUCCESS) {
6069         goto cleanup;
6070     }
6071 
6072     if (mac_output_length != prf_output_length) {
6073         status = PSA_ERROR_CORRUPTION_DETECTED;
6074         goto cleanup;
6075     }
6076 
6077     memcpy(U_accumulator, U_i, prf_output_length);
6078 
6079     for (i = 1; i < pbkdf2->input_cost; i++) {
6080         /* We are passing prf_output_length as mac_size because the driver
6081          * function directly sets mac_output_length as mac_size upon success.
6082          * See https://github.com/Mbed-TLS/mbedtls/issues/7801 */
6083         status = psa_driver_wrapper_mac_compute(attributes,
6084                                                 pbkdf2->password,
6085                                                 pbkdf2->password_length,
6086                                                 prf_alg, U_i, prf_output_length,
6087                                                 U_i, prf_output_length,
6088                                                 &mac_output_length);
6089         if (status != PSA_SUCCESS) {
6090             goto cleanup;
6091         }
6092 
6093         mbedtls_xor(U_accumulator, U_accumulator, U_i, prf_output_length);
6094     }
6095 
6096 cleanup:
6097     /* Zeroise buffers to clear sensitive data from memory. */
6098     mbedtls_platform_zeroize(U_i, PSA_MAC_MAX_SIZE);
6099     return status;
6100 }
6101 
6102 static psa_status_t psa_key_derivation_pbkdf2_read(
6103     psa_pbkdf2_key_derivation_t *pbkdf2,
6104     psa_algorithm_t kdf_alg,
6105     uint8_t *output,
6106     size_t output_length)
6107 {
6108     psa_status_t status;
6109     psa_algorithm_t prf_alg;
6110     uint8_t prf_output_length;
6111     psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
6112     psa_set_key_bits(&attributes, PSA_BYTES_TO_BITS(pbkdf2->password_length));
6113     psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_MESSAGE);
6114 
6115     if (PSA_ALG_IS_PBKDF2_HMAC(kdf_alg)) {
6116         prf_alg = PSA_ALG_HMAC(PSA_ALG_PBKDF2_HMAC_GET_HASH(kdf_alg));
6117         prf_output_length = PSA_HASH_LENGTH(prf_alg);
6118         psa_set_key_type(&attributes, PSA_KEY_TYPE_HMAC);
6119     } else if (kdf_alg == PSA_ALG_PBKDF2_AES_CMAC_PRF_128) {
6120         prf_alg = PSA_ALG_CMAC;
6121         prf_output_length = PSA_MAC_LENGTH(PSA_KEY_TYPE_AES, 128U, PSA_ALG_CMAC);
6122         psa_set_key_type(&attributes, PSA_KEY_TYPE_AES);
6123     } else {
6124         return PSA_ERROR_INVALID_ARGUMENT;
6125     }
6126 
6127     switch (pbkdf2->state) {
6128         case PSA_PBKDF2_STATE_PASSWORD_SET:
6129             /* Initially we need a new block so bytes_used is equal to block size*/
6130             pbkdf2->bytes_used = prf_output_length;
6131             pbkdf2->state = PSA_PBKDF2_STATE_OUTPUT;
6132             break;
6133         case PSA_PBKDF2_STATE_OUTPUT:
6134             break;
6135         default:
6136             return PSA_ERROR_BAD_STATE;
6137     }
6138 
6139     while (output_length != 0) {
6140         uint8_t n = prf_output_length - pbkdf2->bytes_used;
6141         if (n > output_length) {
6142             n = (uint8_t) output_length;
6143         }
6144         memcpy(output, pbkdf2->output_block + pbkdf2->bytes_used, n);
6145         output += n;
6146         output_length -= n;
6147         pbkdf2->bytes_used += n;
6148 
6149         if (output_length == 0) {
6150             break;
6151         }
6152 
6153         /* We need a new block */
6154         pbkdf2->bytes_used = 0;
6155         pbkdf2->block_number++;
6156 
6157         status = psa_key_derivation_pbkdf2_generate_block(pbkdf2, prf_alg,
6158                                                           prf_output_length,
6159                                                           &attributes);
6160         if (status != PSA_SUCCESS) {
6161             return status;
6162         }
6163     }
6164 
6165     return PSA_SUCCESS;
6166 }
6167 #endif /* PSA_HAVE_SOFT_PBKDF2 */
6168 
6169 psa_status_t psa_key_derivation_output_bytes(
6170     psa_key_derivation_operation_t *operation,
6171     uint8_t *output_external,
6172     size_t output_length)
6173 {
6174     psa_status_t status;
6175     LOCAL_OUTPUT_DECLARE(output_external, output);
6176 
6177     psa_algorithm_t kdf_alg = psa_key_derivation_get_kdf_alg(operation);
6178 
6179     if (operation->alg == 0) {
6180         /* This is a blank operation. */
6181         return PSA_ERROR_BAD_STATE;
6182     }
6183 
6184     if (output_length == 0 && operation->capacity == 0) {
6185         /* Edge case: this is a finished operation, and 0 bytes
6186          * were requested. The right error in this case could
6187          * be either INSUFFICIENT_CAPACITY or BAD_STATE. Return
6188          * INSUFFICIENT_CAPACITY, which is right for a finished
6189          * operation, for consistency with the case when
6190          * output_length > 0. */
6191         return PSA_ERROR_INSUFFICIENT_DATA;
6192     }
6193 
6194     LOCAL_OUTPUT_ALLOC(output_external, output_length, output);
6195     if (output_length > operation->capacity) {
6196         operation->capacity = 0;
6197         /* Go through the error path to wipe all confidential data now
6198          * that the operation object is useless. */
6199         status = PSA_ERROR_INSUFFICIENT_DATA;
6200         goto exit;
6201     }
6202 
6203     operation->capacity -= output_length;
6204 
6205 #if defined(BUILTIN_ALG_ANY_HKDF)
6206     if (PSA_ALG_IS_ANY_HKDF(kdf_alg)) {
6207         status = psa_key_derivation_hkdf_read(&operation->ctx.hkdf, kdf_alg,
6208                                               output, output_length);
6209     } else
6210 #endif /* BUILTIN_ALG_ANY_HKDF */
6211 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
6212     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
6213     if (PSA_ALG_IS_TLS12_PRF(kdf_alg) ||
6214         PSA_ALG_IS_TLS12_PSK_TO_MS(kdf_alg)) {
6215         status = psa_key_derivation_tls12_prf_read(&operation->ctx.tls12_prf,
6216                                                    kdf_alg, output,
6217                                                    output_length);
6218     } else
6219 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF ||
6220         * MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
6221 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS)
6222     if (kdf_alg == PSA_ALG_TLS12_ECJPAKE_TO_PMS) {
6223         status = psa_key_derivation_tls12_ecjpake_to_pms_read(
6224             &operation->ctx.tls12_ecjpake_to_pms, output, output_length);
6225     } else
6226 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS */
6227 #if defined(PSA_HAVE_SOFT_PBKDF2)
6228     if (PSA_ALG_IS_PBKDF2(kdf_alg)) {
6229         status = psa_key_derivation_pbkdf2_read(&operation->ctx.pbkdf2, kdf_alg,
6230                                                 output, output_length);
6231     } else
6232 #endif /* PSA_HAVE_SOFT_PBKDF2 */
6233 
6234     {
6235         (void) kdf_alg;
6236         status = PSA_ERROR_BAD_STATE;
6237         LOCAL_OUTPUT_FREE(output_external, output);
6238 
6239         return status;
6240     }
6241 
6242 exit:
6243     if (status != PSA_SUCCESS) {
6244         /* Preserve the algorithm upon errors, but clear all sensitive state.
6245          * This allows us to differentiate between exhausted operations and
6246          * blank operations, so we can return PSA_ERROR_BAD_STATE on blank
6247          * operations. */
6248         psa_algorithm_t alg = operation->alg;
6249         psa_key_derivation_abort(operation);
6250         operation->alg = alg;
6251         if (output != NULL) {
6252             memset(output, '!', output_length);
6253         }
6254     }
6255 
6256     LOCAL_OUTPUT_FREE(output_external, output);
6257     return status;
6258 }
6259 
6260 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES)
6261 static void psa_des_set_key_parity(uint8_t *data, size_t data_size)
6262 {
6263     if (data_size >= 8) {
6264         mbedtls_des_key_set_parity(data);
6265     }
6266     if (data_size >= 16) {
6267         mbedtls_des_key_set_parity(data + 8);
6268     }
6269     if (data_size >= 24) {
6270         mbedtls_des_key_set_parity(data + 16);
6271     }
6272 }
6273 #endif /* MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES */
6274 
6275 /*
6276  * ECC keys on a Weierstrass elliptic curve require the generation
6277  * of a private key which is an integer
6278  * in the range [1, N - 1], where N is the boundary of the private key domain:
6279  * N is the prime p for Diffie-Hellman, or the order of the
6280  * curve’s base point for ECC.
6281  *
6282  * Let m be the bit size of N, such that 2^m > N >= 2^(m-1).
6283  * This function generates the private key using the following process:
6284  *
6285  * 1. Draw a byte string of length ceiling(m/8) bytes.
6286  * 2. If m is not a multiple of 8, set the most significant
6287  *    (8 * ceiling(m/8) - m) bits of the first byte in the string to zero.
6288  * 3. Convert the string to integer k by decoding it as a big-endian byte string.
6289  * 4. If k > N - 2, discard the result and return to step 1.
6290  * 5. Output k + 1 as the private key.
6291  *
6292  * This method allows compliance to NIST standards, specifically the methods titled
6293  * Key-Pair Generation by Testing Candidates in the following publications:
6294  * - NIST Special Publication 800-56A: Recommendation for Pair-Wise Key-Establishment
6295  *   Schemes Using Discrete Logarithm Cryptography [SP800-56A] §5.6.1.1.4 for
6296  *   Diffie-Hellman keys.
6297  *
6298  * - [SP800-56A] §5.6.1.2.2 or FIPS Publication 186-4: Digital Signature
6299  *   Standard (DSS) [FIPS186-4] §B.4.2 for elliptic curve keys.
6300  *
6301  * Note: Function allocates memory for *data buffer, so given *data should be
6302  *       always NULL.
6303  */
6304 #if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE)
6305 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_DERIVE)
6306 static psa_status_t psa_generate_derived_ecc_key_weierstrass_helper(
6307     psa_key_slot_t *slot,
6308     size_t bits,
6309     psa_key_derivation_operation_t *operation,
6310     uint8_t **data
6311     )
6312 {
6313     unsigned key_out_of_range = 1;
6314     mbedtls_mpi k;
6315     mbedtls_mpi diff_N_2;
6316     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
6317     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
6318     size_t m;
6319     size_t m_bytes = 0;
6320 
6321     mbedtls_mpi_init(&k);
6322     mbedtls_mpi_init(&diff_N_2);
6323 
6324     psa_ecc_family_t curve = PSA_KEY_TYPE_ECC_GET_FAMILY(
6325         slot->attr.type);
6326     mbedtls_ecp_group_id grp_id =
6327         mbedtls_ecc_group_from_psa(curve, bits);
6328 
6329     if (grp_id == MBEDTLS_ECP_DP_NONE) {
6330         ret = MBEDTLS_ERR_ASN1_INVALID_DATA;
6331         goto cleanup;
6332     }
6333 
6334     mbedtls_ecp_group ecp_group;
6335     mbedtls_ecp_group_init(&ecp_group);
6336 
6337     MBEDTLS_MPI_CHK(mbedtls_ecp_group_load(&ecp_group, grp_id));
6338 
6339     /* N is the boundary of the private key domain (ecp_group.N). */
6340     /* Let m be the bit size of N. */
6341     m = ecp_group.nbits;
6342 
6343     m_bytes = PSA_BITS_TO_BYTES(m);
6344 
6345     /* Calculate N - 2 - it will be needed later. */
6346     MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&diff_N_2, &ecp_group.N, 2));
6347 
6348     /* Note: This function is always called with *data == NULL and it
6349      * allocates memory for the data buffer. */
6350     *data = mbedtls_calloc(1, m_bytes);
6351     if (*data == NULL) {
6352         ret = MBEDTLS_ERR_ASN1_ALLOC_FAILED;
6353         goto cleanup;
6354     }
6355 
6356     while (key_out_of_range) {
6357         /* 1. Draw a byte string of length ceiling(m/8) bytes. */
6358         if ((status = psa_key_derivation_output_bytes(operation, *data, m_bytes)) != 0) {
6359             goto cleanup;
6360         }
6361 
6362         /* 2. If m is not a multiple of 8 */
6363         if (m % 8 != 0) {
6364             /* Set the most significant
6365              * (8 * ceiling(m/8) - m) bits of the first byte in
6366              * the string to zero.
6367              */
6368             uint8_t clear_bit_mask = (1 << (m % 8)) - 1;
6369             (*data)[0] &= clear_bit_mask;
6370         }
6371 
6372         /* 3. Convert the string to integer k by decoding it as a
6373          *    big-endian byte string.
6374          */
6375         MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&k, *data, m_bytes));
6376 
6377         /* 4. If k > N - 2, discard the result and return to step 1.
6378          *    Result of comparison is returned. When it indicates error
6379          *    then this function is called again.
6380          */
6381         MBEDTLS_MPI_CHK(mbedtls_mpi_lt_mpi_ct(&diff_N_2, &k, &key_out_of_range));
6382     }
6383 
6384     /* 5. Output k + 1 as the private key. */
6385     MBEDTLS_MPI_CHK(mbedtls_mpi_add_int(&k, &k, 1));
6386     MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&k, *data, m_bytes));
6387 cleanup:
6388     if (ret != 0) {
6389         status = mbedtls_to_psa_error(ret);
6390     }
6391     if (status != PSA_SUCCESS) {
6392         mbedtls_zeroize_and_free(*data, m_bytes);
6393         *data = NULL;
6394     }
6395     mbedtls_mpi_free(&k);
6396     mbedtls_mpi_free(&diff_N_2);
6397     return status;
6398 }
6399 
6400 /* ECC keys on a Montgomery elliptic curve draws a byte string whose length
6401  * is determined by the curve, and sets the mandatory bits accordingly. That is:
6402  *
6403  * - Curve25519 (PSA_ECC_FAMILY_MONTGOMERY, 255 bits):
6404  *   draw a 32-byte string and process it as specified in
6405  *   Elliptic Curves for Security [RFC7748] §5.
6406  *
6407  * - Curve448 (PSA_ECC_FAMILY_MONTGOMERY, 448 bits):
6408  *   draw a 56-byte string and process it as specified in [RFC7748] §5.
6409  *
6410  * Note: Function allocates memory for *data buffer, so given *data should be
6411  *       always NULL.
6412  */
6413 
6414 static psa_status_t psa_generate_derived_ecc_key_montgomery_helper(
6415     size_t bits,
6416     psa_key_derivation_operation_t *operation,
6417     uint8_t **data
6418     )
6419 {
6420     size_t output_length;
6421     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
6422 
6423     switch (bits) {
6424         case 255:
6425             output_length = 32;
6426             break;
6427         case 448:
6428             output_length = 56;
6429             break;
6430         default:
6431             return PSA_ERROR_INVALID_ARGUMENT;
6432             break;
6433     }
6434 
6435     *data = mbedtls_calloc(1, output_length);
6436 
6437     if (*data == NULL) {
6438         return PSA_ERROR_INSUFFICIENT_MEMORY;
6439     }
6440 
6441     status = psa_key_derivation_output_bytes(operation, *data, output_length);
6442 
6443     if (status != PSA_SUCCESS) {
6444         return status;
6445     }
6446 
6447     switch (bits) {
6448         case 255:
6449             (*data)[0] &= 248;
6450             (*data)[31] &= 127;
6451             (*data)[31] |= 64;
6452             break;
6453         case 448:
6454             (*data)[0] &= 252;
6455             (*data)[55] |= 128;
6456             break;
6457         default:
6458             return PSA_ERROR_CORRUPTION_DETECTED;
6459             break;
6460     }
6461 
6462     return status;
6463 }
6464 #else /* MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_DERIVE */
6465 static psa_status_t psa_generate_derived_ecc_key_weierstrass_helper(
6466     psa_key_slot_t *slot, size_t bits,
6467     psa_key_derivation_operation_t *operation, uint8_t **data)
6468 {
6469     (void) slot;
6470     (void) bits;
6471     (void) operation;
6472     (void) data;
6473     return PSA_ERROR_NOT_SUPPORTED;
6474 }
6475 
6476 static psa_status_t psa_generate_derived_ecc_key_montgomery_helper(
6477     size_t bits, psa_key_derivation_operation_t *operation, uint8_t **data)
6478 {
6479     (void) bits;
6480     (void) operation;
6481     (void) data;
6482     return PSA_ERROR_NOT_SUPPORTED;
6483 }
6484 #endif /* MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_DERIVE */
6485 #endif /* PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE */
6486 
6487 static psa_status_t psa_generate_derived_key_internal(
6488     psa_key_slot_t *slot,
6489     size_t bits,
6490     psa_key_derivation_operation_t *operation)
6491 {
6492     uint8_t *data = NULL;
6493     size_t bytes = PSA_BITS_TO_BYTES(bits);
6494     size_t storage_size = bytes;
6495     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
6496 
6497     if (PSA_KEY_TYPE_IS_PUBLIC_KEY(slot->attr.type)) {
6498         return PSA_ERROR_INVALID_ARGUMENT;
6499     }
6500 
6501 #if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE) || \
6502     defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_DERIVE)
6503     if (PSA_KEY_TYPE_IS_ECC(slot->attr.type)) {
6504         psa_ecc_family_t curve = PSA_KEY_TYPE_ECC_GET_FAMILY(slot->attr.type);
6505         if (PSA_ECC_FAMILY_IS_WEIERSTRASS(curve)) {
6506             /* Weierstrass elliptic curve */
6507             status = psa_generate_derived_ecc_key_weierstrass_helper(slot, bits, operation, &data);
6508             if (status != PSA_SUCCESS) {
6509                 goto exit;
6510             }
6511         } else {
6512             /* Montgomery elliptic curve */
6513             status = psa_generate_derived_ecc_key_montgomery_helper(bits, operation, &data);
6514             if (status != PSA_SUCCESS) {
6515                 goto exit;
6516             }
6517         }
6518     } else
6519 #endif /* defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE) ||
6520           defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_DERIVE) */
6521     if (key_type_is_raw_bytes(slot->attr.type)) {
6522         if (bits % 8 != 0) {
6523             return PSA_ERROR_INVALID_ARGUMENT;
6524         }
6525         data = mbedtls_calloc(1, bytes);
6526         if (data == NULL) {
6527             return PSA_ERROR_INSUFFICIENT_MEMORY;
6528         }
6529 
6530         status = psa_key_derivation_output_bytes(operation, data, bytes);
6531         if (status != PSA_SUCCESS) {
6532             goto exit;
6533         }
6534 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES)
6535         if (slot->attr.type == PSA_KEY_TYPE_DES) {
6536             psa_des_set_key_parity(data, bytes);
6537         }
6538 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES) */
6539     } else {
6540         return PSA_ERROR_NOT_SUPPORTED;
6541     }
6542 
6543     slot->attr.bits = (psa_key_bits_t) bits;
6544 
6545     if (psa_key_lifetime_is_external(slot->attr.lifetime)) {
6546         status = psa_driver_wrapper_get_key_buffer_size(&slot->attr,
6547                                                         &storage_size);
6548         if (status != PSA_SUCCESS) {
6549             goto exit;
6550         }
6551     }
6552     status = psa_allocate_buffer_to_slot(slot, storage_size);
6553     if (status != PSA_SUCCESS) {
6554         goto exit;
6555     }
6556 
6557     status = psa_driver_wrapper_import_key(&slot->attr,
6558                                            data, bytes,
6559                                            slot->key.data,
6560                                            slot->key.bytes,
6561                                            &slot->key.bytes, &bits);
6562     if (bits != slot->attr.bits) {
6563         status = PSA_ERROR_INVALID_ARGUMENT;
6564     }
6565 
6566 exit:
6567     mbedtls_zeroize_and_free(data, bytes);
6568     return status;
6569 }
6570 
6571 static const psa_custom_key_parameters_t default_custom_production =
6572     PSA_CUSTOM_KEY_PARAMETERS_INIT;
6573 
6574 int psa_custom_key_parameters_are_default(
6575     const psa_custom_key_parameters_t *custom,
6576     size_t custom_data_length)
6577 {
6578     if (custom->flags != 0) {
6579         return 0;
6580     }
6581     if (custom_data_length != 0) {
6582         return 0;
6583     }
6584     return 1;
6585 }
6586 
6587 psa_status_t psa_key_derivation_output_key_custom(
6588     const psa_key_attributes_t *attributes,
6589     psa_key_derivation_operation_t *operation,
6590     const psa_custom_key_parameters_t *custom,
6591     const uint8_t *custom_data,
6592     size_t custom_data_length,
6593     mbedtls_svc_key_id_t *key)
6594 {
6595     psa_status_t status;
6596     psa_key_slot_t *slot = NULL;
6597     psa_se_drv_table_entry_t *driver = NULL;
6598 
6599     *key = MBEDTLS_SVC_KEY_ID_INIT;
6600 
6601     /* Reject any attempt to create a zero-length key so that we don't
6602      * risk tripping up later, e.g. on a malloc(0) that returns NULL. */
6603     if (psa_get_key_bits(attributes) == 0) {
6604         return PSA_ERROR_INVALID_ARGUMENT;
6605     }
6606 
6607     (void) custom_data;         /* We only accept 0-length data */
6608     if (!psa_custom_key_parameters_are_default(custom, custom_data_length)) {
6609         return PSA_ERROR_INVALID_ARGUMENT;
6610     }
6611 
6612     if (operation->alg == PSA_ALG_NONE) {
6613         return PSA_ERROR_BAD_STATE;
6614     }
6615 
6616     if (!operation->can_output_key) {
6617         return PSA_ERROR_NOT_PERMITTED;
6618     }
6619 
6620     status = psa_start_key_creation(PSA_KEY_CREATION_DERIVE, attributes,
6621                                     &slot, &driver);
6622 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
6623     if (driver != NULL) {
6624         /* Deriving a key in a secure element is not implemented yet. */
6625         status = PSA_ERROR_NOT_SUPPORTED;
6626     }
6627 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
6628     if (status == PSA_SUCCESS) {
6629         status = psa_generate_derived_key_internal(slot,
6630                                                    attributes->bits,
6631                                                    operation);
6632     }
6633     if (status == PSA_SUCCESS) {
6634         status = psa_finish_key_creation(slot, driver, key);
6635     }
6636     if (status != PSA_SUCCESS) {
6637         psa_fail_key_creation(slot, driver);
6638     }
6639 
6640     return status;
6641 }
6642 
6643 psa_status_t psa_key_derivation_output_key_ext(
6644     const psa_key_attributes_t *attributes,
6645     psa_key_derivation_operation_t *operation,
6646     const psa_key_production_parameters_t *params,
6647     size_t params_data_length,
6648     mbedtls_svc_key_id_t *key)
6649 {
6650     return psa_key_derivation_output_key_custom(
6651         attributes, operation,
6652         (const psa_custom_key_parameters_t *) params,
6653         params->data, params_data_length,
6654         key);
6655 }
6656 
6657 psa_status_t psa_key_derivation_output_key(
6658     const psa_key_attributes_t *attributes,
6659     psa_key_derivation_operation_t *operation,
6660     mbedtls_svc_key_id_t *key)
6661 {
6662     return psa_key_derivation_output_key_custom(attributes, operation,
6663                                                 &default_custom_production,
6664                                                 NULL, 0,
6665                                                 key);
6666 }
6667 
6668 
6669 /****************************************************************/
6670 /* Key derivation */
6671 /****************************************************************/
6672 
6673 #if defined(AT_LEAST_ONE_BUILTIN_KDF)
6674 static int is_kdf_alg_supported(psa_algorithm_t kdf_alg)
6675 {
6676 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF)
6677     if (PSA_ALG_IS_HKDF(kdf_alg)) {
6678         return 1;
6679     }
6680 #endif
6681 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT)
6682     if (PSA_ALG_IS_HKDF_EXTRACT(kdf_alg)) {
6683         return 1;
6684     }
6685 #endif
6686 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXPAND)
6687     if (PSA_ALG_IS_HKDF_EXPAND(kdf_alg)) {
6688         return 1;
6689     }
6690 #endif
6691 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF)
6692     if (PSA_ALG_IS_TLS12_PRF(kdf_alg)) {
6693         return 1;
6694     }
6695 #endif
6696 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
6697     if (PSA_ALG_IS_TLS12_PSK_TO_MS(kdf_alg)) {
6698         return 1;
6699     }
6700 #endif
6701 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS)
6702     if (kdf_alg == PSA_ALG_TLS12_ECJPAKE_TO_PMS) {
6703         return 1;
6704     }
6705 #endif
6706 #if defined(MBEDTLS_PSA_BUILTIN_ALG_PBKDF2_HMAC)
6707     if (PSA_ALG_IS_PBKDF2_HMAC(kdf_alg)) {
6708         return 1;
6709     }
6710 #endif
6711 #if defined(MBEDTLS_PSA_BUILTIN_ALG_PBKDF2_AES_CMAC_PRF_128)
6712     if (kdf_alg == PSA_ALG_PBKDF2_AES_CMAC_PRF_128) {
6713         return 1;
6714     }
6715 #endif
6716     return 0;
6717 }
6718 
6719 static psa_status_t psa_hash_try_support(psa_algorithm_t alg)
6720 {
6721     psa_hash_operation_t operation = PSA_HASH_OPERATION_INIT;
6722     psa_status_t status = psa_hash_setup(&operation, alg);
6723     psa_hash_abort(&operation);
6724     return status;
6725 }
6726 
6727 static psa_status_t psa_key_derivation_set_maximum_capacity(
6728     psa_key_derivation_operation_t *operation,
6729     psa_algorithm_t kdf_alg)
6730 {
6731 #if defined(PSA_WANT_ALG_TLS12_ECJPAKE_TO_PMS)
6732     if (kdf_alg == PSA_ALG_TLS12_ECJPAKE_TO_PMS) {
6733         operation->capacity = PSA_HASH_LENGTH(PSA_ALG_SHA_256);
6734         return PSA_SUCCESS;
6735     }
6736 #endif
6737 #if defined(PSA_WANT_ALG_PBKDF2_AES_CMAC_PRF_128)
6738     if (kdf_alg == PSA_ALG_PBKDF2_AES_CMAC_PRF_128) {
6739 #if (SIZE_MAX > UINT32_MAX)
6740         operation->capacity = UINT32_MAX * (size_t) PSA_MAC_LENGTH(
6741             PSA_KEY_TYPE_AES,
6742             128U,
6743             PSA_ALG_CMAC);
6744 #else
6745         operation->capacity = SIZE_MAX;
6746 #endif
6747         return PSA_SUCCESS;
6748     }
6749 #endif /* PSA_WANT_ALG_PBKDF2_AES_CMAC_PRF_128 */
6750 
6751     /* After this point, if kdf_alg is not valid then value of hash_alg may be
6752      * invalid or meaningless but it does not affect this function */
6753     psa_algorithm_t hash_alg = PSA_ALG_GET_HASH(kdf_alg);
6754     size_t hash_size = PSA_HASH_LENGTH(hash_alg);
6755     if (hash_size == 0) {
6756         return PSA_ERROR_NOT_SUPPORTED;
6757     }
6758 
6759     /* Make sure that hash_alg is a supported hash algorithm. Otherwise
6760      * we might fail later, which is somewhat unfriendly and potentially
6761      * risk-prone. */
6762     psa_status_t status = psa_hash_try_support(hash_alg);
6763     if (status != PSA_SUCCESS) {
6764         return status;
6765     }
6766 
6767 #if defined(PSA_WANT_ALG_HKDF)
6768     if (PSA_ALG_IS_HKDF(kdf_alg)) {
6769         operation->capacity = 255 * hash_size;
6770     } else
6771 #endif
6772 #if defined(PSA_WANT_ALG_HKDF_EXTRACT)
6773     if (PSA_ALG_IS_HKDF_EXTRACT(kdf_alg)) {
6774         operation->capacity = hash_size;
6775     } else
6776 #endif
6777 #if defined(PSA_WANT_ALG_HKDF_EXPAND)
6778     if (PSA_ALG_IS_HKDF_EXPAND(kdf_alg)) {
6779         operation->capacity = 255 * hash_size;
6780     } else
6781 #endif
6782 #if defined(PSA_WANT_ALG_TLS12_PRF)
6783     if (PSA_ALG_IS_TLS12_PRF(kdf_alg) &&
6784         (hash_alg == PSA_ALG_SHA_256 || hash_alg == PSA_ALG_SHA_384)) {
6785         operation->capacity = SIZE_MAX;
6786     } else
6787 #endif
6788 #if defined(PSA_WANT_ALG_TLS12_PSK_TO_MS)
6789     if (PSA_ALG_IS_TLS12_PSK_TO_MS(kdf_alg) &&
6790         (hash_alg == PSA_ALG_SHA_256 || hash_alg == PSA_ALG_SHA_384)) {
6791         /* Master Secret is always 48 bytes
6792          * https://datatracker.ietf.org/doc/html/rfc5246.html#section-8.1 */
6793         operation->capacity = 48U;
6794     } else
6795 #endif
6796 #if defined(PSA_WANT_ALG_PBKDF2_HMAC)
6797     if (PSA_ALG_IS_PBKDF2_HMAC(kdf_alg)) {
6798 #if (SIZE_MAX > UINT32_MAX)
6799         operation->capacity = UINT32_MAX * hash_size;
6800 #else
6801         operation->capacity = SIZE_MAX;
6802 #endif
6803     } else
6804 #endif /* PSA_WANT_ALG_PBKDF2_HMAC */
6805     {
6806         (void) hash_size;
6807         status = PSA_ERROR_NOT_SUPPORTED;
6808     }
6809     return status;
6810 }
6811 
6812 static psa_status_t psa_key_derivation_setup_kdf(
6813     psa_key_derivation_operation_t *operation,
6814     psa_algorithm_t kdf_alg)
6815 {
6816     /* Make sure that operation->ctx is properly zero-initialised. (Macro
6817      * initialisers for this union leave some bytes unspecified.) */
6818     memset(&operation->ctx, 0, sizeof(operation->ctx));
6819 
6820     /* Make sure that kdf_alg is a supported key derivation algorithm. */
6821     if (!is_kdf_alg_supported(kdf_alg)) {
6822         return PSA_ERROR_NOT_SUPPORTED;
6823     }
6824 
6825     psa_status_t status = psa_key_derivation_set_maximum_capacity(operation,
6826                                                                   kdf_alg);
6827     return status;
6828 }
6829 
6830 static psa_status_t psa_key_agreement_try_support(psa_algorithm_t alg)
6831 {
6832 #if defined(PSA_WANT_ALG_ECDH)
6833     if (alg == PSA_ALG_ECDH) {
6834         return PSA_SUCCESS;
6835     }
6836 #endif
6837 #if defined(PSA_WANT_ALG_FFDH)
6838     if (alg == PSA_ALG_FFDH) {
6839         return PSA_SUCCESS;
6840     }
6841 #endif
6842     (void) alg;
6843     return PSA_ERROR_NOT_SUPPORTED;
6844 }
6845 
6846 static int psa_key_derivation_allows_free_form_secret_input(
6847     psa_algorithm_t kdf_alg)
6848 {
6849 #if defined(PSA_WANT_ALG_TLS12_ECJPAKE_TO_PMS)
6850     if (kdf_alg == PSA_ALG_TLS12_ECJPAKE_TO_PMS) {
6851         return 0;
6852     }
6853 #endif
6854     (void) kdf_alg;
6855     return 1;
6856 }
6857 #endif /* AT_LEAST_ONE_BUILTIN_KDF */
6858 
6859 psa_status_t psa_key_derivation_setup(psa_key_derivation_operation_t *operation,
6860                                       psa_algorithm_t alg)
6861 {
6862     psa_status_t status;
6863 
6864     if (operation->alg != 0) {
6865         return PSA_ERROR_BAD_STATE;
6866     }
6867 
6868     if (PSA_ALG_IS_RAW_KEY_AGREEMENT(alg)) {
6869         return PSA_ERROR_INVALID_ARGUMENT;
6870     } else if (PSA_ALG_IS_KEY_AGREEMENT(alg)) {
6871 #if defined(AT_LEAST_ONE_BUILTIN_KDF)
6872         psa_algorithm_t kdf_alg = PSA_ALG_KEY_AGREEMENT_GET_KDF(alg);
6873         psa_algorithm_t ka_alg = PSA_ALG_KEY_AGREEMENT_GET_BASE(alg);
6874         status = psa_key_agreement_try_support(ka_alg);
6875         if (status != PSA_SUCCESS) {
6876             return status;
6877         }
6878         if (!psa_key_derivation_allows_free_form_secret_input(kdf_alg)) {
6879             return PSA_ERROR_INVALID_ARGUMENT;
6880         }
6881         status = psa_key_derivation_setup_kdf(operation, kdf_alg);
6882 #else
6883         return PSA_ERROR_NOT_SUPPORTED;
6884 #endif /* AT_LEAST_ONE_BUILTIN_KDF */
6885     } else if (PSA_ALG_IS_KEY_DERIVATION(alg)) {
6886 #if defined(AT_LEAST_ONE_BUILTIN_KDF)
6887         status = psa_key_derivation_setup_kdf(operation, alg);
6888 #else
6889         return PSA_ERROR_NOT_SUPPORTED;
6890 #endif /* AT_LEAST_ONE_BUILTIN_KDF */
6891     } else {
6892         return PSA_ERROR_INVALID_ARGUMENT;
6893     }
6894 
6895     if (status == PSA_SUCCESS) {
6896         operation->alg = alg;
6897     }
6898     return status;
6899 }
6900 
6901 #if defined(BUILTIN_ALG_ANY_HKDF)
6902 static psa_status_t psa_hkdf_input(psa_hkdf_key_derivation_t *hkdf,
6903                                    psa_algorithm_t kdf_alg,
6904                                    psa_key_derivation_step_t step,
6905                                    const uint8_t *data,
6906                                    size_t data_length)
6907 {
6908     psa_algorithm_t hash_alg = PSA_ALG_HKDF_GET_HASH(kdf_alg);
6909     psa_status_t status;
6910     switch (step) {
6911         case PSA_KEY_DERIVATION_INPUT_SALT:
6912 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXPAND)
6913             if (PSA_ALG_IS_HKDF_EXPAND(kdf_alg)) {
6914                 return PSA_ERROR_INVALID_ARGUMENT;
6915             }
6916 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXPAND */
6917             if (hkdf->state != HKDF_STATE_INIT) {
6918                 return PSA_ERROR_BAD_STATE;
6919             } else {
6920                 status = psa_key_derivation_start_hmac(&hkdf->hmac,
6921                                                        hash_alg,
6922                                                        data, data_length);
6923                 if (status != PSA_SUCCESS) {
6924                     return status;
6925                 }
6926                 hkdf->state = HKDF_STATE_STARTED;
6927                 return PSA_SUCCESS;
6928             }
6929         case PSA_KEY_DERIVATION_INPUT_SECRET:
6930 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXPAND)
6931             if (PSA_ALG_IS_HKDF_EXPAND(kdf_alg)) {
6932                 /* We shouldn't be in different state as HKDF_EXPAND only allows
6933                  * two inputs: SECRET (this case) and INFO which does not modify
6934                  * the state. It could happen only if the hkdf
6935                  * object was corrupted. */
6936                 if (hkdf->state != HKDF_STATE_INIT) {
6937                     return PSA_ERROR_BAD_STATE;
6938                 }
6939 
6940                 /* Allow only input that fits expected prk size */
6941                 if (data_length != PSA_HASH_LENGTH(hash_alg)) {
6942                     return PSA_ERROR_INVALID_ARGUMENT;
6943                 }
6944 
6945                 memcpy(hkdf->prk, data, data_length);
6946             } else
6947 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXPAND */
6948             {
6949                 /* HKDF: If no salt was provided, use an empty salt.
6950                  * HKDF-EXTRACT: salt is mandatory. */
6951                 if (hkdf->state == HKDF_STATE_INIT) {
6952 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT)
6953                     if (PSA_ALG_IS_HKDF_EXTRACT(kdf_alg)) {
6954                         return PSA_ERROR_BAD_STATE;
6955                     }
6956 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT */
6957                     status = psa_key_derivation_start_hmac(&hkdf->hmac,
6958                                                            hash_alg,
6959                                                            NULL, 0);
6960                     if (status != PSA_SUCCESS) {
6961                         return status;
6962                     }
6963                     hkdf->state = HKDF_STATE_STARTED;
6964                 }
6965                 if (hkdf->state != HKDF_STATE_STARTED) {
6966                     return PSA_ERROR_BAD_STATE;
6967                 }
6968                 status = psa_mac_update(&hkdf->hmac,
6969                                         data, data_length);
6970                 if (status != PSA_SUCCESS) {
6971                     return status;
6972                 }
6973                 status = psa_mac_sign_finish(&hkdf->hmac,
6974                                              hkdf->prk,
6975                                              sizeof(hkdf->prk),
6976                                              &data_length);
6977                 if (status != PSA_SUCCESS) {
6978                     return status;
6979                 }
6980             }
6981 
6982             hkdf->state = HKDF_STATE_KEYED;
6983             hkdf->block_number = 0;
6984 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT)
6985             if (PSA_ALG_IS_HKDF_EXTRACT(kdf_alg)) {
6986                 /* The only block of output is the PRK. */
6987                 memcpy(hkdf->output_block, hkdf->prk, PSA_HASH_LENGTH(hash_alg));
6988                 hkdf->offset_in_block = 0;
6989             } else
6990 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT */
6991             {
6992                 /* Block 0 is empty, and the next block will be
6993                  * generated by psa_key_derivation_hkdf_read(). */
6994                 hkdf->offset_in_block = PSA_HASH_LENGTH(hash_alg);
6995             }
6996 
6997             return PSA_SUCCESS;
6998         case PSA_KEY_DERIVATION_INPUT_INFO:
6999 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT)
7000             if (PSA_ALG_IS_HKDF_EXTRACT(kdf_alg)) {
7001                 return PSA_ERROR_INVALID_ARGUMENT;
7002             }
7003 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT */
7004 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXPAND)
7005             if (PSA_ALG_IS_HKDF_EXPAND(kdf_alg) &&
7006                 hkdf->state == HKDF_STATE_INIT) {
7007                 return PSA_ERROR_BAD_STATE;
7008             }
7009 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT */
7010             if (hkdf->state == HKDF_STATE_OUTPUT) {
7011                 return PSA_ERROR_BAD_STATE;
7012             }
7013             if (hkdf->info_set) {
7014                 return PSA_ERROR_BAD_STATE;
7015             }
7016             hkdf->info_length = data_length;
7017             if (data_length != 0) {
7018                 hkdf->info = mbedtls_calloc(1, data_length);
7019                 if (hkdf->info == NULL) {
7020                     return PSA_ERROR_INSUFFICIENT_MEMORY;
7021                 }
7022                 memcpy(hkdf->info, data, data_length);
7023             }
7024             hkdf->info_set = 1;
7025             return PSA_SUCCESS;
7026         default:
7027             return PSA_ERROR_INVALID_ARGUMENT;
7028     }
7029 }
7030 #endif /* BUILTIN_ALG_ANY_HKDF */
7031 
7032 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
7033     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
7034 static psa_status_t psa_tls12_prf_set_seed(psa_tls12_prf_key_derivation_t *prf,
7035                                            const uint8_t *data,
7036                                            size_t data_length)
7037 {
7038     if (prf->state != PSA_TLS12_PRF_STATE_INIT) {
7039         return PSA_ERROR_BAD_STATE;
7040     }
7041 
7042     if (data_length != 0) {
7043         prf->seed = mbedtls_calloc(1, data_length);
7044         if (prf->seed == NULL) {
7045             return PSA_ERROR_INSUFFICIENT_MEMORY;
7046         }
7047 
7048         memcpy(prf->seed, data, data_length);
7049         prf->seed_length = data_length;
7050     }
7051 
7052     prf->state = PSA_TLS12_PRF_STATE_SEED_SET;
7053 
7054     return PSA_SUCCESS;
7055 }
7056 
7057 static psa_status_t psa_tls12_prf_set_key(psa_tls12_prf_key_derivation_t *prf,
7058                                           const uint8_t *data,
7059                                           size_t data_length)
7060 {
7061     if (prf->state != PSA_TLS12_PRF_STATE_SEED_SET &&
7062         prf->state != PSA_TLS12_PRF_STATE_OTHER_KEY_SET) {
7063         return PSA_ERROR_BAD_STATE;
7064     }
7065 
7066     if (data_length != 0) {
7067         prf->secret = mbedtls_calloc(1, data_length);
7068         if (prf->secret == NULL) {
7069             return PSA_ERROR_INSUFFICIENT_MEMORY;
7070         }
7071 
7072         memcpy(prf->secret, data, data_length);
7073         prf->secret_length = data_length;
7074     }
7075 
7076     prf->state = PSA_TLS12_PRF_STATE_KEY_SET;
7077 
7078     return PSA_SUCCESS;
7079 }
7080 
7081 static psa_status_t psa_tls12_prf_set_label(psa_tls12_prf_key_derivation_t *prf,
7082                                             const uint8_t *data,
7083                                             size_t data_length)
7084 {
7085     if (prf->state != PSA_TLS12_PRF_STATE_KEY_SET) {
7086         return PSA_ERROR_BAD_STATE;
7087     }
7088 
7089     if (data_length != 0) {
7090         prf->label = mbedtls_calloc(1, data_length);
7091         if (prf->label == NULL) {
7092             return PSA_ERROR_INSUFFICIENT_MEMORY;
7093         }
7094 
7095         memcpy(prf->label, data, data_length);
7096         prf->label_length = data_length;
7097     }
7098 
7099     prf->state = PSA_TLS12_PRF_STATE_LABEL_SET;
7100 
7101     return PSA_SUCCESS;
7102 }
7103 
7104 static psa_status_t psa_tls12_prf_input(psa_tls12_prf_key_derivation_t *prf,
7105                                         psa_key_derivation_step_t step,
7106                                         const uint8_t *data,
7107                                         size_t data_length)
7108 {
7109     switch (step) {
7110         case PSA_KEY_DERIVATION_INPUT_SEED:
7111             return psa_tls12_prf_set_seed(prf, data, data_length);
7112         case PSA_KEY_DERIVATION_INPUT_SECRET:
7113             return psa_tls12_prf_set_key(prf, data, data_length);
7114         case PSA_KEY_DERIVATION_INPUT_LABEL:
7115             return psa_tls12_prf_set_label(prf, data, data_length);
7116         default:
7117             return PSA_ERROR_INVALID_ARGUMENT;
7118     }
7119 }
7120 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) ||
7121         * MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
7122 
7123 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
7124 static psa_status_t psa_tls12_prf_psk_to_ms_set_key(
7125     psa_tls12_prf_key_derivation_t *prf,
7126     const uint8_t *data,
7127     size_t data_length)
7128 {
7129     psa_status_t status;
7130     const size_t pms_len = (prf->state == PSA_TLS12_PRF_STATE_OTHER_KEY_SET ?
7131                             4 + data_length + prf->other_secret_length :
7132                             4 + 2 * data_length);
7133 
7134     if (data_length > PSA_TLS12_PSK_TO_MS_PSK_MAX_SIZE) {
7135         return PSA_ERROR_INVALID_ARGUMENT;
7136     }
7137 
7138     uint8_t *pms = mbedtls_calloc(1, pms_len);
7139     if (pms == NULL) {
7140         return PSA_ERROR_INSUFFICIENT_MEMORY;
7141     }
7142     uint8_t *cur = pms;
7143 
7144     /* pure-PSK:
7145      * Quoting RFC 4279, Section 2:
7146      *
7147      * The premaster secret is formed as follows: if the PSK is N octets
7148      * long, concatenate a uint16 with the value N, N zero octets, a second
7149      * uint16 with the value N, and the PSK itself.
7150      *
7151      * mixed-PSK:
7152      * In a DHE-PSK, RSA-PSK, ECDHE-PSK the premaster secret is formed as
7153      * follows: concatenate a uint16 with the length of the other secret,
7154      * the other secret itself, uint16 with the length of PSK, and the
7155      * PSK itself.
7156      * For details please check:
7157      * - RFC 4279, Section 4 for the definition of RSA-PSK,
7158      * - RFC 4279, Section 3 for the definition of DHE-PSK,
7159      * - RFC 5489 for the definition of ECDHE-PSK.
7160      */
7161 
7162     if (prf->state == PSA_TLS12_PRF_STATE_OTHER_KEY_SET) {
7163         *cur++ = MBEDTLS_BYTE_1(prf->other_secret_length);
7164         *cur++ = MBEDTLS_BYTE_0(prf->other_secret_length);
7165         if (prf->other_secret_length != 0) {
7166             memcpy(cur, prf->other_secret, prf->other_secret_length);
7167             mbedtls_platform_zeroize(prf->other_secret, prf->other_secret_length);
7168             cur += prf->other_secret_length;
7169         }
7170     } else {
7171         *cur++ = MBEDTLS_BYTE_1(data_length);
7172         *cur++ = MBEDTLS_BYTE_0(data_length);
7173         memset(cur, 0, data_length);
7174         cur += data_length;
7175     }
7176 
7177     *cur++ = MBEDTLS_BYTE_1(data_length);
7178     *cur++ = MBEDTLS_BYTE_0(data_length);
7179     memcpy(cur, data, data_length);
7180     cur += data_length;
7181 
7182     status = psa_tls12_prf_set_key(prf, pms, (size_t) (cur - pms));
7183 
7184     mbedtls_zeroize_and_free(pms, pms_len);
7185     return status;
7186 }
7187 
7188 static psa_status_t psa_tls12_prf_psk_to_ms_set_other_key(
7189     psa_tls12_prf_key_derivation_t *prf,
7190     const uint8_t *data,
7191     size_t data_length)
7192 {
7193     if (prf->state != PSA_TLS12_PRF_STATE_SEED_SET) {
7194         return PSA_ERROR_BAD_STATE;
7195     }
7196 
7197     if (data_length != 0) {
7198         prf->other_secret = mbedtls_calloc(1, data_length);
7199         if (prf->other_secret == NULL) {
7200             return PSA_ERROR_INSUFFICIENT_MEMORY;
7201         }
7202 
7203         memcpy(prf->other_secret, data, data_length);
7204         prf->other_secret_length = data_length;
7205     } else {
7206         prf->other_secret_length = 0;
7207     }
7208 
7209     prf->state = PSA_TLS12_PRF_STATE_OTHER_KEY_SET;
7210 
7211     return PSA_SUCCESS;
7212 }
7213 
7214 static psa_status_t psa_tls12_prf_psk_to_ms_input(
7215     psa_tls12_prf_key_derivation_t *prf,
7216     psa_key_derivation_step_t step,
7217     const uint8_t *data,
7218     size_t data_length)
7219 {
7220     switch (step) {
7221         case PSA_KEY_DERIVATION_INPUT_SECRET:
7222             return psa_tls12_prf_psk_to_ms_set_key(prf,
7223                                                    data, data_length);
7224             break;
7225         case PSA_KEY_DERIVATION_INPUT_OTHER_SECRET:
7226             return psa_tls12_prf_psk_to_ms_set_other_key(prf,
7227                                                          data,
7228                                                          data_length);
7229             break;
7230         default:
7231             return psa_tls12_prf_input(prf, step, data, data_length);
7232             break;
7233 
7234     }
7235 }
7236 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
7237 
7238 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS)
7239 static psa_status_t psa_tls12_ecjpake_to_pms_input(
7240     psa_tls12_ecjpake_to_pms_t *ecjpake,
7241     psa_key_derivation_step_t step,
7242     const uint8_t *data,
7243     size_t data_length)
7244 {
7245     if (data_length != PSA_TLS12_ECJPAKE_TO_PMS_INPUT_SIZE ||
7246         step != PSA_KEY_DERIVATION_INPUT_SECRET) {
7247         return PSA_ERROR_INVALID_ARGUMENT;
7248     }
7249 
7250     /* Check if the passed point is in an uncompressed form */
7251     if (data[0] != 0x04) {
7252         return PSA_ERROR_INVALID_ARGUMENT;
7253     }
7254 
7255     /* Only K.X has to be extracted - bytes 1 to 32 inclusive. */
7256     memcpy(ecjpake->data, data + 1, PSA_TLS12_ECJPAKE_TO_PMS_DATA_SIZE);
7257 
7258     return PSA_SUCCESS;
7259 }
7260 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS */
7261 
7262 #if defined(PSA_HAVE_SOFT_PBKDF2)
7263 static psa_status_t psa_pbkdf2_set_input_cost(
7264     psa_pbkdf2_key_derivation_t *pbkdf2,
7265     psa_key_derivation_step_t step,
7266     uint64_t data)
7267 {
7268     if (step != PSA_KEY_DERIVATION_INPUT_COST) {
7269         return PSA_ERROR_INVALID_ARGUMENT;
7270     }
7271 
7272     if (pbkdf2->state != PSA_PBKDF2_STATE_INIT) {
7273         return PSA_ERROR_BAD_STATE;
7274     }
7275 
7276     if (data > PSA_VENDOR_PBKDF2_MAX_ITERATIONS) {
7277         return PSA_ERROR_NOT_SUPPORTED;
7278     }
7279 
7280     if (data == 0) {
7281         return PSA_ERROR_INVALID_ARGUMENT;
7282     }
7283 
7284     pbkdf2->input_cost = data;
7285     pbkdf2->state = PSA_PBKDF2_STATE_INPUT_COST_SET;
7286 
7287     return PSA_SUCCESS;
7288 }
7289 
7290 static psa_status_t psa_pbkdf2_set_salt(psa_pbkdf2_key_derivation_t *pbkdf2,
7291                                         const uint8_t *data,
7292                                         size_t data_length)
7293 {
7294     if (pbkdf2->state == PSA_PBKDF2_STATE_INPUT_COST_SET) {
7295         pbkdf2->state = PSA_PBKDF2_STATE_SALT_SET;
7296     } else if (pbkdf2->state == PSA_PBKDF2_STATE_SALT_SET) {
7297         /* Appending to existing salt. No state change. */
7298     } else {
7299         return PSA_ERROR_BAD_STATE;
7300     }
7301 
7302     if (data_length == 0) {
7303         /* Appending an empty string, nothing to do. */
7304     } else {
7305         uint8_t *next_salt;
7306 
7307         next_salt = mbedtls_calloc(1, data_length + pbkdf2->salt_length);
7308         if (next_salt == NULL) {
7309             return PSA_ERROR_INSUFFICIENT_MEMORY;
7310         }
7311 
7312         if (pbkdf2->salt_length != 0) {
7313             memcpy(next_salt, pbkdf2->salt, pbkdf2->salt_length);
7314         }
7315         memcpy(next_salt + pbkdf2->salt_length, data, data_length);
7316         pbkdf2->salt_length += data_length;
7317         mbedtls_free(pbkdf2->salt);
7318         pbkdf2->salt = next_salt;
7319     }
7320     return PSA_SUCCESS;
7321 }
7322 
7323 #if defined(MBEDTLS_PSA_BUILTIN_ALG_PBKDF2_HMAC)
7324 static psa_status_t psa_pbkdf2_hmac_set_password(psa_algorithm_t hash_alg,
7325                                                  const uint8_t *input,
7326                                                  size_t input_len,
7327                                                  uint8_t *output,
7328                                                  size_t *output_len)
7329 {
7330     psa_status_t status = PSA_SUCCESS;
7331     if (input_len > PSA_HASH_BLOCK_LENGTH(hash_alg)) {
7332         return psa_hash_compute(hash_alg, input, input_len, output,
7333                                 PSA_HMAC_MAX_HASH_BLOCK_SIZE, output_len);
7334     } else if (input_len > 0) {
7335         memcpy(output, input, input_len);
7336     }
7337     *output_len = PSA_HASH_BLOCK_LENGTH(hash_alg);
7338     return status;
7339 }
7340 #endif /* MBEDTLS_PSA_BUILTIN_ALG_PBKDF2_HMAC */
7341 
7342 #if defined(MBEDTLS_PSA_BUILTIN_ALG_PBKDF2_AES_CMAC_PRF_128)
7343 static psa_status_t psa_pbkdf2_cmac_set_password(const uint8_t *input,
7344                                                  size_t input_len,
7345                                                  uint8_t *output,
7346                                                  size_t *output_len)
7347 {
7348     psa_status_t status = PSA_SUCCESS;
7349     if (input_len != PSA_MAC_LENGTH(PSA_KEY_TYPE_AES, 128U, PSA_ALG_CMAC)) {
7350         psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
7351         uint8_t zeros[16] = { 0 };
7352         psa_set_key_type(&attributes, PSA_KEY_TYPE_AES);
7353         psa_set_key_bits(&attributes, PSA_BYTES_TO_BITS(sizeof(zeros)));
7354         psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_MESSAGE);
7355         /* Passing PSA_MAC_LENGTH(PSA_KEY_TYPE_AES, 128U, PSA_ALG_CMAC) as
7356          * mac_size as the driver function sets mac_output_length = mac_size
7357          * on success. See https://github.com/Mbed-TLS/mbedtls/issues/7801 */
7358         status = psa_driver_wrapper_mac_compute(&attributes,
7359                                                 zeros, sizeof(zeros),
7360                                                 PSA_ALG_CMAC, input, input_len,
7361                                                 output,
7362                                                 PSA_MAC_LENGTH(PSA_KEY_TYPE_AES,
7363                                                                128U,
7364                                                                PSA_ALG_CMAC),
7365                                                 output_len);
7366     } else {
7367         memcpy(output, input, input_len);
7368         *output_len = PSA_MAC_LENGTH(PSA_KEY_TYPE_AES, 128U, PSA_ALG_CMAC);
7369     }
7370     return status;
7371 }
7372 #endif /* MBEDTLS_PSA_BUILTIN_ALG_PBKDF2_AES_CMAC_PRF_128 */
7373 
7374 static psa_status_t psa_pbkdf2_set_password(psa_pbkdf2_key_derivation_t *pbkdf2,
7375                                             psa_algorithm_t kdf_alg,
7376                                             const uint8_t *data,
7377                                             size_t data_length)
7378 {
7379     psa_status_t status = PSA_SUCCESS;
7380     if (pbkdf2->state != PSA_PBKDF2_STATE_SALT_SET) {
7381         return PSA_ERROR_BAD_STATE;
7382     }
7383 
7384 #if defined(MBEDTLS_PSA_BUILTIN_ALG_PBKDF2_HMAC)
7385     if (PSA_ALG_IS_PBKDF2_HMAC(kdf_alg)) {
7386         psa_algorithm_t hash_alg = PSA_ALG_PBKDF2_HMAC_GET_HASH(kdf_alg);
7387         status = psa_pbkdf2_hmac_set_password(hash_alg, data, data_length,
7388                                               pbkdf2->password,
7389                                               &pbkdf2->password_length);
7390     } else
7391 #endif /* MBEDTLS_PSA_BUILTIN_ALG_PBKDF2_HMAC */
7392 #if defined(MBEDTLS_PSA_BUILTIN_ALG_PBKDF2_AES_CMAC_PRF_128)
7393     if (kdf_alg == PSA_ALG_PBKDF2_AES_CMAC_PRF_128) {
7394         status = psa_pbkdf2_cmac_set_password(data, data_length,
7395                                               pbkdf2->password,
7396                                               &pbkdf2->password_length);
7397     } else
7398 #endif /* MBEDTLS_PSA_BUILTIN_ALG_PBKDF2_AES_CMAC_PRF_128 */
7399     {
7400         return PSA_ERROR_INVALID_ARGUMENT;
7401     }
7402 
7403     pbkdf2->state = PSA_PBKDF2_STATE_PASSWORD_SET;
7404 
7405     return status;
7406 }
7407 
7408 static psa_status_t psa_pbkdf2_input(psa_pbkdf2_key_derivation_t *pbkdf2,
7409                                      psa_algorithm_t kdf_alg,
7410                                      psa_key_derivation_step_t step,
7411                                      const uint8_t *data,
7412                                      size_t data_length)
7413 {
7414     switch (step) {
7415         case PSA_KEY_DERIVATION_INPUT_SALT:
7416             return psa_pbkdf2_set_salt(pbkdf2, data, data_length);
7417         case PSA_KEY_DERIVATION_INPUT_PASSWORD:
7418             return psa_pbkdf2_set_password(pbkdf2, kdf_alg, data, data_length);
7419         default:
7420             return PSA_ERROR_INVALID_ARGUMENT;
7421     }
7422 }
7423 #endif /* PSA_HAVE_SOFT_PBKDF2 */
7424 
7425 /** Check whether the given key type is acceptable for the given
7426  * input step of a key derivation.
7427  *
7428  * Secret inputs must have the type #PSA_KEY_TYPE_DERIVE.
7429  * Non-secret inputs must have the type #PSA_KEY_TYPE_RAW_DATA.
7430  * Both secret and non-secret inputs can alternatively have the type
7431  * #PSA_KEY_TYPE_NONE, which is never the type of a key object, meaning
7432  * that the input was passed as a buffer rather than via a key object.
7433  */
7434 static int psa_key_derivation_check_input_type(
7435     psa_key_derivation_step_t step,
7436     psa_key_type_t key_type)
7437 {
7438     switch (step) {
7439         case PSA_KEY_DERIVATION_INPUT_SECRET:
7440             if (key_type == PSA_KEY_TYPE_DERIVE) {
7441                 return PSA_SUCCESS;
7442             }
7443             if (key_type == PSA_KEY_TYPE_NONE) {
7444                 return PSA_SUCCESS;
7445             }
7446             break;
7447         case PSA_KEY_DERIVATION_INPUT_OTHER_SECRET:
7448             if (key_type == PSA_KEY_TYPE_DERIVE) {
7449                 return PSA_SUCCESS;
7450             }
7451             if (key_type == PSA_KEY_TYPE_NONE) {
7452                 return PSA_SUCCESS;
7453             }
7454             break;
7455         case PSA_KEY_DERIVATION_INPUT_LABEL:
7456         case PSA_KEY_DERIVATION_INPUT_SALT:
7457         case PSA_KEY_DERIVATION_INPUT_INFO:
7458         case PSA_KEY_DERIVATION_INPUT_SEED:
7459             if (key_type == PSA_KEY_TYPE_RAW_DATA) {
7460                 return PSA_SUCCESS;
7461             }
7462             if (key_type == PSA_KEY_TYPE_NONE) {
7463                 return PSA_SUCCESS;
7464             }
7465             break;
7466         case PSA_KEY_DERIVATION_INPUT_PASSWORD:
7467             if (key_type == PSA_KEY_TYPE_PASSWORD) {
7468                 return PSA_SUCCESS;
7469             }
7470             if (key_type == PSA_KEY_TYPE_DERIVE) {
7471                 return PSA_SUCCESS;
7472             }
7473             if (key_type == PSA_KEY_TYPE_NONE) {
7474                 return PSA_SUCCESS;
7475             }
7476             break;
7477     }
7478     return PSA_ERROR_INVALID_ARGUMENT;
7479 }
7480 
7481 static psa_status_t psa_key_derivation_input_internal(
7482     psa_key_derivation_operation_t *operation,
7483     psa_key_derivation_step_t step,
7484     psa_key_type_t key_type,
7485     const uint8_t *data,
7486     size_t data_length)
7487 {
7488     psa_status_t status;
7489     psa_algorithm_t kdf_alg = psa_key_derivation_get_kdf_alg(operation);
7490 
7491     if (kdf_alg == PSA_ALG_NONE) {
7492         /* This is a blank or aborted operation. */
7493         status = PSA_ERROR_BAD_STATE;
7494         goto exit;
7495     }
7496 
7497     status = psa_key_derivation_check_input_type(step, key_type);
7498     if (status != PSA_SUCCESS) {
7499         goto exit;
7500     }
7501 
7502 #if defined(BUILTIN_ALG_ANY_HKDF)
7503     if (PSA_ALG_IS_ANY_HKDF(kdf_alg)) {
7504         status = psa_hkdf_input(&operation->ctx.hkdf, kdf_alg,
7505                                 step, data, data_length);
7506     } else
7507 #endif /* BUILTIN_ALG_ANY_HKDF */
7508 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF)
7509     if (PSA_ALG_IS_TLS12_PRF(kdf_alg)) {
7510         status = psa_tls12_prf_input(&operation->ctx.tls12_prf,
7511                                      step, data, data_length);
7512     } else
7513 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF */
7514 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
7515     if (PSA_ALG_IS_TLS12_PSK_TO_MS(kdf_alg)) {
7516         status = psa_tls12_prf_psk_to_ms_input(&operation->ctx.tls12_prf,
7517                                                step, data, data_length);
7518     } else
7519 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
7520 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS)
7521     if (kdf_alg == PSA_ALG_TLS12_ECJPAKE_TO_PMS) {
7522         status = psa_tls12_ecjpake_to_pms_input(
7523             &operation->ctx.tls12_ecjpake_to_pms, step, data, data_length);
7524     } else
7525 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS */
7526 #if defined(PSA_HAVE_SOFT_PBKDF2)
7527     if (PSA_ALG_IS_PBKDF2(kdf_alg)) {
7528         status = psa_pbkdf2_input(&operation->ctx.pbkdf2, kdf_alg,
7529                                   step, data, data_length);
7530     } else
7531 #endif /* PSA_HAVE_SOFT_PBKDF2 */
7532     {
7533         /* This can't happen unless the operation object was not initialized */
7534         (void) data;
7535         (void) data_length;
7536         (void) kdf_alg;
7537         return PSA_ERROR_BAD_STATE;
7538     }
7539 
7540 exit:
7541     if (status != PSA_SUCCESS) {
7542         psa_key_derivation_abort(operation);
7543     }
7544     return status;
7545 }
7546 
7547 static psa_status_t psa_key_derivation_input_integer_internal(
7548     psa_key_derivation_operation_t *operation,
7549     psa_key_derivation_step_t step,
7550     uint64_t value)
7551 {
7552     psa_status_t status;
7553     psa_algorithm_t kdf_alg = psa_key_derivation_get_kdf_alg(operation);
7554 
7555     if (kdf_alg == PSA_ALG_NONE) {
7556         /* This is a blank or aborted operation. */
7557         status = PSA_ERROR_BAD_STATE;
7558         goto exit;
7559     }
7560 
7561 #if defined(PSA_HAVE_SOFT_PBKDF2)
7562     if (PSA_ALG_IS_PBKDF2(kdf_alg)) {
7563         status = psa_pbkdf2_set_input_cost(
7564             &operation->ctx.pbkdf2, step, value);
7565     } else
7566 #endif /* PSA_HAVE_SOFT_PBKDF2 */
7567     {
7568         (void) step;
7569         (void) value;
7570         (void) kdf_alg;
7571         status = PSA_ERROR_INVALID_ARGUMENT;
7572     }
7573 
7574 exit:
7575     if (status != PSA_SUCCESS) {
7576         psa_key_derivation_abort(operation);
7577     }
7578     return status;
7579 }
7580 
7581 psa_status_t psa_key_derivation_input_bytes(
7582     psa_key_derivation_operation_t *operation,
7583     psa_key_derivation_step_t step,
7584     const uint8_t *data_external,
7585     size_t data_length)
7586 {
7587     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
7588     LOCAL_INPUT_DECLARE(data_external, data);
7589 
7590     LOCAL_INPUT_ALLOC(data_external, data_length, data);
7591 
7592     status = psa_key_derivation_input_internal(operation, step,
7593                                                PSA_KEY_TYPE_NONE,
7594                                                data, data_length);
7595 #if !defined(MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS)
7596 exit:
7597 #endif
7598     LOCAL_INPUT_FREE(data_external, data);
7599     return status;
7600 }
7601 
7602 psa_status_t psa_key_derivation_input_integer(
7603     psa_key_derivation_operation_t *operation,
7604     psa_key_derivation_step_t step,
7605     uint64_t value)
7606 {
7607     return psa_key_derivation_input_integer_internal(operation, step, value);
7608 }
7609 
7610 psa_status_t psa_key_derivation_input_key(
7611     psa_key_derivation_operation_t *operation,
7612     psa_key_derivation_step_t step,
7613     mbedtls_svc_key_id_t key)
7614 {
7615     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
7616     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
7617     psa_key_slot_t *slot;
7618 
7619     status = psa_get_and_lock_transparent_key_slot_with_policy(
7620         key, &slot, PSA_KEY_USAGE_DERIVE, operation->alg);
7621     if (status != PSA_SUCCESS) {
7622         psa_key_derivation_abort(operation);
7623         return status;
7624     }
7625 
7626     /* Passing a key object as a SECRET or PASSWORD input unlocks the
7627      * permission to output to a key object. */
7628     if (step == PSA_KEY_DERIVATION_INPUT_SECRET ||
7629         step == PSA_KEY_DERIVATION_INPUT_PASSWORD) {
7630         operation->can_output_key = 1;
7631     }
7632 
7633     status = psa_key_derivation_input_internal(operation,
7634                                                step, slot->attr.type,
7635                                                slot->key.data,
7636                                                slot->key.bytes);
7637 
7638     unlock_status = psa_unregister_read_under_mutex(slot);
7639 
7640     return (status == PSA_SUCCESS) ? unlock_status : status;
7641 }
7642 
7643 
7644 
7645 /****************************************************************/
7646 /* Key agreement */
7647 /****************************************************************/
7648 
7649 psa_status_t psa_key_agreement_raw_builtin(const psa_key_attributes_t *attributes,
7650                                            const uint8_t *key_buffer,
7651                                            size_t key_buffer_size,
7652                                            psa_algorithm_t alg,
7653                                            const uint8_t *peer_key,
7654                                            size_t peer_key_length,
7655                                            uint8_t *shared_secret,
7656                                            size_t shared_secret_size,
7657                                            size_t *shared_secret_length)
7658 {
7659     switch (alg) {
7660 #if defined(MBEDTLS_PSA_BUILTIN_ALG_ECDH)
7661         case PSA_ALG_ECDH:
7662             return mbedtls_psa_key_agreement_ecdh(attributes, key_buffer,
7663                                                   key_buffer_size, alg,
7664                                                   peer_key, peer_key_length,
7665                                                   shared_secret,
7666                                                   shared_secret_size,
7667                                                   shared_secret_length);
7668 #endif /* MBEDTLS_PSA_BUILTIN_ALG_ECDH */
7669 
7670 #if defined(MBEDTLS_PSA_BUILTIN_ALG_FFDH)
7671         case PSA_ALG_FFDH:
7672             return mbedtls_psa_ffdh_key_agreement(attributes,
7673                                                   peer_key,
7674                                                   peer_key_length,
7675                                                   key_buffer,
7676                                                   key_buffer_size,
7677                                                   shared_secret,
7678                                                   shared_secret_size,
7679                                                   shared_secret_length);
7680 #endif /* MBEDTLS_PSA_BUILTIN_ALG_FFDH */
7681 
7682         default:
7683             (void) attributes;
7684             (void) key_buffer;
7685             (void) key_buffer_size;
7686             (void) peer_key;
7687             (void) peer_key_length;
7688             (void) shared_secret;
7689             (void) shared_secret_size;
7690             (void) shared_secret_length;
7691             return PSA_ERROR_NOT_SUPPORTED;
7692     }
7693 }
7694 
7695 /** Internal function for raw key agreement
7696  *  Calls the driver wrapper which will hand off key agreement task
7697  *  to the driver's implementation if a driver is present.
7698  *  Fallback specified in the driver wrapper is built-in raw key agreement
7699  *  (psa_key_agreement_raw_builtin).
7700  */
7701 static psa_status_t psa_key_agreement_raw_internal(psa_algorithm_t alg,
7702                                                    psa_key_slot_t *private_key,
7703                                                    const uint8_t *peer_key,
7704                                                    size_t peer_key_length,
7705                                                    uint8_t *shared_secret,
7706                                                    size_t shared_secret_size,
7707                                                    size_t *shared_secret_length)
7708 {
7709     if (!PSA_ALG_IS_RAW_KEY_AGREEMENT(alg)) {
7710         return PSA_ERROR_NOT_SUPPORTED;
7711     }
7712 
7713     return psa_driver_wrapper_key_agreement(&private_key->attr,
7714                                             private_key->key.data,
7715                                             private_key->key.bytes, alg,
7716                                             peer_key, peer_key_length,
7717                                             shared_secret,
7718                                             shared_secret_size,
7719                                             shared_secret_length);
7720 }
7721 
7722 /* Note that if this function fails, you must call psa_key_derivation_abort()
7723  * to potentially free embedded data structures and wipe confidential data.
7724  */
7725 static psa_status_t psa_key_agreement_internal(psa_key_derivation_operation_t *operation,
7726                                                psa_key_derivation_step_t step,
7727                                                psa_key_slot_t *private_key,
7728                                                const uint8_t *peer_key,
7729                                                size_t peer_key_length)
7730 {
7731     psa_status_t status;
7732     uint8_t shared_secret[PSA_RAW_KEY_AGREEMENT_OUTPUT_MAX_SIZE] = { 0 };
7733     size_t shared_secret_length = 0;
7734     psa_algorithm_t ka_alg = PSA_ALG_KEY_AGREEMENT_GET_BASE(operation->alg);
7735 
7736     /* Step 1: run the secret agreement algorithm to generate the shared
7737      * secret. */
7738     status = psa_key_agreement_raw_internal(ka_alg,
7739                                             private_key,
7740                                             peer_key, peer_key_length,
7741                                             shared_secret,
7742                                             sizeof(shared_secret),
7743                                             &shared_secret_length);
7744     if (status != PSA_SUCCESS) {
7745         goto exit;
7746     }
7747 
7748     /* Step 2: set up the key derivation to generate key material from
7749      * the shared secret. A shared secret is permitted wherever a key
7750      * of type DERIVE is permitted. */
7751     status = psa_key_derivation_input_internal(operation, step,
7752                                                PSA_KEY_TYPE_DERIVE,
7753                                                shared_secret,
7754                                                shared_secret_length);
7755 exit:
7756     mbedtls_platform_zeroize(shared_secret, shared_secret_length);
7757     return status;
7758 }
7759 
7760 psa_status_t psa_key_derivation_key_agreement(psa_key_derivation_operation_t *operation,
7761                                               psa_key_derivation_step_t step,
7762                                               mbedtls_svc_key_id_t private_key,
7763                                               const uint8_t *peer_key_external,
7764                                               size_t peer_key_length)
7765 {
7766     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
7767     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
7768     psa_key_slot_t *slot;
7769     LOCAL_INPUT_DECLARE(peer_key_external, peer_key);
7770 
7771     if (!PSA_ALG_IS_KEY_AGREEMENT(operation->alg)) {
7772         return PSA_ERROR_INVALID_ARGUMENT;
7773     }
7774     status = psa_get_and_lock_transparent_key_slot_with_policy(
7775         private_key, &slot, PSA_KEY_USAGE_DERIVE, operation->alg);
7776     if (status != PSA_SUCCESS) {
7777         return status;
7778     }
7779 
7780     LOCAL_INPUT_ALLOC(peer_key_external, peer_key_length, peer_key);
7781     status = psa_key_agreement_internal(operation, step,
7782                                         slot,
7783                                         peer_key, peer_key_length);
7784 
7785 #if !defined(MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS)
7786 exit:
7787 #endif
7788     if (status != PSA_SUCCESS) {
7789         psa_key_derivation_abort(operation);
7790     } else {
7791         /* If a private key has been added as SECRET, we allow the derived
7792          * key material to be used as a key in PSA Crypto. */
7793         if (step == PSA_KEY_DERIVATION_INPUT_SECRET) {
7794             operation->can_output_key = 1;
7795         }
7796     }
7797 
7798     unlock_status = psa_unregister_read_under_mutex(slot);
7799     LOCAL_INPUT_FREE(peer_key_external, peer_key);
7800 
7801     return (status == PSA_SUCCESS) ? unlock_status : status;
7802 }
7803 
7804 psa_status_t psa_raw_key_agreement(psa_algorithm_t alg,
7805                                    mbedtls_svc_key_id_t private_key,
7806                                    const uint8_t *peer_key_external,
7807                                    size_t peer_key_length,
7808                                    uint8_t *output_external,
7809                                    size_t output_size,
7810                                    size_t *output_length)
7811 {
7812     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
7813     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
7814     psa_key_slot_t *slot = NULL;
7815     size_t expected_length;
7816     LOCAL_INPUT_DECLARE(peer_key_external, peer_key);
7817     LOCAL_OUTPUT_DECLARE(output_external, output);
7818     LOCAL_OUTPUT_ALLOC(output_external, output_size, output);
7819 
7820     if (!PSA_ALG_IS_KEY_AGREEMENT(alg)) {
7821         status = PSA_ERROR_INVALID_ARGUMENT;
7822         goto exit;
7823     }
7824     status = psa_get_and_lock_transparent_key_slot_with_policy(
7825         private_key, &slot, PSA_KEY_USAGE_DERIVE, alg);
7826     if (status != PSA_SUCCESS) {
7827         goto exit;
7828     }
7829 
7830     /* PSA_RAW_KEY_AGREEMENT_OUTPUT_SIZE() is in general an upper bound
7831      * for the output size. The PSA specification only guarantees that this
7832      * function works if output_size >= PSA_RAW_KEY_AGREEMENT_OUTPUT_SIZE(...),
7833      * but it might be nice to allow smaller buffers if the output fits.
7834      * At the time of writing this comment, with only ECDH implemented,
7835      * PSA_RAW_KEY_AGREEMENT_OUTPUT_SIZE() is exact so the point is moot.
7836      * If FFDH is implemented, PSA_RAW_KEY_AGREEMENT_OUTPUT_SIZE() can easily
7837      * be exact for it as well. */
7838     expected_length =
7839         PSA_RAW_KEY_AGREEMENT_OUTPUT_SIZE(slot->attr.type, slot->attr.bits);
7840     if (output_size < expected_length) {
7841         status = PSA_ERROR_BUFFER_TOO_SMALL;
7842         goto exit;
7843     }
7844 
7845     LOCAL_INPUT_ALLOC(peer_key_external, peer_key_length, peer_key);
7846     status = psa_key_agreement_raw_internal(alg, slot,
7847                                             peer_key, peer_key_length,
7848                                             output, output_size,
7849                                             output_length);
7850 
7851 exit:
7852     /* Check for successful allocation of output,
7853      * with an unsuccessful status. */
7854     if (output != NULL && status != PSA_SUCCESS) {
7855         /* If an error happens and is not handled properly, the output
7856          * may be used as a key to protect sensitive data. Arrange for such
7857          * a key to be random, which is likely to result in decryption or
7858          * verification errors. This is better than filling the buffer with
7859          * some constant data such as zeros, which would result in the data
7860          * being protected with a reproducible, easily knowable key.
7861          */
7862         psa_generate_random_internal(output, output_size);
7863         *output_length = output_size;
7864     }
7865 
7866     if (output == NULL) {
7867         /* output allocation failed. */
7868         *output_length = 0;
7869     }
7870 
7871     unlock_status = psa_unregister_read_under_mutex(slot);
7872 
7873     LOCAL_INPUT_FREE(peer_key_external, peer_key);
7874     LOCAL_OUTPUT_FREE(output_external, output);
7875     return (status == PSA_SUCCESS) ? unlock_status : status;
7876 }
7877 
7878 
7879 /****************************************************************/
7880 /* Random generation */
7881 /****************************************************************/
7882 
7883 #if defined(MBEDTLS_PSA_INJECT_ENTROPY)
7884 #include "entropy_poll.h"
7885 #endif
7886 
7887 /** Initialize the PSA random generator.
7888  *
7889  *  Note: the mbedtls_threading_psa_rngdata_mutex should be held when calling
7890  *  this function if mutexes are enabled.
7891  */
7892 static void mbedtls_psa_random_init(mbedtls_psa_random_context_t *rng)
7893 {
7894 #if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
7895     memset(rng, 0, sizeof(*rng));
7896 #else /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
7897 
7898     /* Set default configuration if
7899      * mbedtls_psa_crypto_configure_entropy_sources() hasn't been called. */
7900     if (rng->entropy_init == NULL) {
7901         rng->entropy_init = mbedtls_entropy_init;
7902     }
7903     if (rng->entropy_free == NULL) {
7904         rng->entropy_free = mbedtls_entropy_free;
7905     }
7906 
7907     rng->entropy_init(&rng->entropy);
7908 #if defined(MBEDTLS_PSA_INJECT_ENTROPY) && \
7909     defined(MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES)
7910     /* The PSA entropy injection feature depends on using NV seed as an entropy
7911      * source. Add NV seed as an entropy source for PSA entropy injection. */
7912     mbedtls_entropy_add_source(&rng->entropy,
7913                                mbedtls_nv_seed_poll, NULL,
7914                                MBEDTLS_ENTROPY_BLOCK_SIZE,
7915                                MBEDTLS_ENTROPY_SOURCE_STRONG);
7916 #endif
7917 
7918     mbedtls_psa_drbg_init(&rng->drbg);
7919 #endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
7920 }
7921 
7922 /** Deinitialize the PSA random generator.
7923  *
7924  *  Note: the mbedtls_threading_psa_rngdata_mutex should be held when calling
7925  *  this function if mutexes are enabled.
7926  */
7927 static void mbedtls_psa_random_free(mbedtls_psa_random_context_t *rng)
7928 {
7929 #if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
7930     memset(rng, 0, sizeof(*rng));
7931 #else /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
7932     mbedtls_psa_drbg_free(&rng->drbg);
7933     rng->entropy_free(&rng->entropy);
7934 #endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
7935 }
7936 
7937 /** Seed the PSA random generator.
7938  */
7939 static psa_status_t mbedtls_psa_random_seed(mbedtls_psa_random_context_t *rng)
7940 {
7941 #if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
7942     /* Do nothing: the external RNG seeds itself. */
7943     (void) rng;
7944     return PSA_SUCCESS;
7945 #else /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
7946     const unsigned char drbg_seed[] = "PSA";
7947     int ret = mbedtls_psa_drbg_seed(&rng->drbg, &rng->entropy,
7948                                     drbg_seed, sizeof(drbg_seed) - 1);
7949     return mbedtls_to_psa_error(ret);
7950 #endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
7951 }
7952 
7953 psa_status_t psa_generate_random(uint8_t *output_external,
7954                                  size_t output_size)
7955 {
7956     psa_status_t status;
7957 
7958     LOCAL_OUTPUT_DECLARE(output_external, output);
7959     LOCAL_OUTPUT_ALLOC(output_external, output_size, output);
7960 
7961     status = psa_generate_random_internal(output, output_size);
7962 
7963 #if !defined(MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS)
7964 exit:
7965 #endif
7966     LOCAL_OUTPUT_FREE(output_external, output);
7967     return status;
7968 }
7969 
7970 #if defined(MBEDTLS_PSA_INJECT_ENTROPY)
7971 psa_status_t mbedtls_psa_inject_entropy(const uint8_t *seed,
7972                                         size_t seed_size)
7973 {
7974     if (psa_get_initialized()) {
7975         return PSA_ERROR_NOT_PERMITTED;
7976     }
7977 
7978     if (((seed_size < MBEDTLS_ENTROPY_MIN_PLATFORM) ||
7979          (seed_size < MBEDTLS_ENTROPY_BLOCK_SIZE)) ||
7980         (seed_size > MBEDTLS_ENTROPY_MAX_SEED_SIZE)) {
7981         return PSA_ERROR_INVALID_ARGUMENT;
7982     }
7983 
7984     return mbedtls_psa_storage_inject_entropy(seed, seed_size);
7985 }
7986 #endif /* MBEDTLS_PSA_INJECT_ENTROPY */
7987 
7988 /** Validate the key type and size for key generation
7989  *
7990  * \param  type  The key type
7991  * \param  bits  The number of bits of the key
7992  *
7993  * \retval #PSA_SUCCESS
7994  *         The key type and size are valid.
7995  * \retval #PSA_ERROR_INVALID_ARGUMENT
7996  *         The size in bits of the key is not valid.
7997  * \retval #PSA_ERROR_NOT_SUPPORTED
7998  *         The type and/or the size in bits of the key or the combination of
7999  *         the two is not supported.
8000  */
8001 static psa_status_t psa_validate_key_type_and_size_for_key_generation(
8002     psa_key_type_t type, size_t bits)
8003 {
8004     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
8005 
8006     if (key_type_is_raw_bytes(type)) {
8007         status = psa_validate_unstructured_key_bit_size(type, bits);
8008         if (status != PSA_SUCCESS) {
8009             return status;
8010         }
8011     } else
8012 #if defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_GENERATE)
8013     if (PSA_KEY_TYPE_IS_RSA(type) && PSA_KEY_TYPE_IS_KEY_PAIR(type)) {
8014         if (bits > PSA_VENDOR_RSA_MAX_KEY_BITS) {
8015             return PSA_ERROR_NOT_SUPPORTED;
8016         }
8017         if (bits < PSA_VENDOR_RSA_GENERATE_MIN_KEY_BITS) {
8018             return PSA_ERROR_NOT_SUPPORTED;
8019         }
8020 
8021         /* Accept only byte-aligned keys, for the same reasons as
8022          * in psa_import_rsa_key(). */
8023         if (bits % 8 != 0) {
8024             return PSA_ERROR_NOT_SUPPORTED;
8025         }
8026     } else
8027 #endif /* defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_GENERATE) */
8028 
8029 #if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_GENERATE)
8030     if (PSA_KEY_TYPE_IS_ECC(type) && PSA_KEY_TYPE_IS_KEY_PAIR(type)) {
8031         /* To avoid empty block, return successfully here. */
8032         return PSA_SUCCESS;
8033     } else
8034 #endif /* defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_GENERATE) */
8035 
8036 #if defined(PSA_WANT_KEY_TYPE_DH_KEY_PAIR_GENERATE)
8037     if (PSA_KEY_TYPE_IS_DH(type) && PSA_KEY_TYPE_IS_KEY_PAIR(type)) {
8038         if (psa_is_dh_key_size_valid(bits) == 0) {
8039             return PSA_ERROR_NOT_SUPPORTED;
8040         }
8041     } else
8042 #endif /* defined(PSA_WANT_KEY_TYPE_DH_KEY_PAIR_GENERATE) */
8043     {
8044         return PSA_ERROR_NOT_SUPPORTED;
8045     }
8046 
8047     return PSA_SUCCESS;
8048 }
8049 
8050 psa_status_t psa_generate_key_internal(
8051     const psa_key_attributes_t *attributes,
8052     const psa_custom_key_parameters_t *custom,
8053     const uint8_t *custom_data,
8054     size_t custom_data_length,
8055     uint8_t *key_buffer, size_t key_buffer_size, size_t *key_buffer_length)
8056 {
8057     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
8058     psa_key_type_t type = attributes->type;
8059 
8060     /* Only used for RSA */
8061     (void) custom;
8062     (void) custom_data;
8063     (void) custom_data_length;
8064 
8065     if (key_type_is_raw_bytes(type)) {
8066         status = psa_generate_random_internal(key_buffer, key_buffer_size);
8067         if (status != PSA_SUCCESS) {
8068             return status;
8069         }
8070 
8071 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES)
8072         if (type == PSA_KEY_TYPE_DES) {
8073             psa_des_set_key_parity(key_buffer, key_buffer_size);
8074         }
8075 #endif /* MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES */
8076     } else
8077 
8078 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_GENERATE)
8079     if (type == PSA_KEY_TYPE_RSA_KEY_PAIR) {
8080         return mbedtls_psa_rsa_generate_key(attributes,
8081                                             custom_data, custom_data_length,
8082                                             key_buffer,
8083                                             key_buffer_size,
8084                                             key_buffer_length);
8085     } else
8086 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_GENERATE) */
8087 
8088 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_GENERATE)
8089     if (PSA_KEY_TYPE_IS_ECC(type) && PSA_KEY_TYPE_IS_KEY_PAIR(type)) {
8090         return mbedtls_psa_ecp_generate_key(attributes,
8091                                             key_buffer,
8092                                             key_buffer_size,
8093                                             key_buffer_length);
8094     } else
8095 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_GENERATE) */
8096 
8097 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_KEY_PAIR_GENERATE)
8098     if (PSA_KEY_TYPE_IS_DH(type) && PSA_KEY_TYPE_IS_KEY_PAIR(type)) {
8099         return mbedtls_psa_ffdh_generate_key(attributes,
8100                                              key_buffer,
8101                                              key_buffer_size,
8102                                              key_buffer_length);
8103     } else
8104 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_KEY_PAIR_GENERATE) */
8105     {
8106         (void) key_buffer_length;
8107         return PSA_ERROR_NOT_SUPPORTED;
8108     }
8109 
8110     return PSA_SUCCESS;
8111 }
8112 
8113 psa_status_t psa_generate_key_custom(const psa_key_attributes_t *attributes,
8114                                      const psa_custom_key_parameters_t *custom,
8115                                      const uint8_t *custom_data,
8116                                      size_t custom_data_length,
8117                                      mbedtls_svc_key_id_t *key)
8118 {
8119     psa_status_t status;
8120     psa_key_slot_t *slot = NULL;
8121     psa_se_drv_table_entry_t *driver = NULL;
8122     size_t key_buffer_size;
8123 
8124     *key = MBEDTLS_SVC_KEY_ID_INIT;
8125 
8126     /* Reject any attempt to create a zero-length key so that we don't
8127      * risk tripping up later, e.g. on a malloc(0) that returns NULL. */
8128     if (psa_get_key_bits(attributes) == 0) {
8129         return PSA_ERROR_INVALID_ARGUMENT;
8130     }
8131 
8132     /* Reject any attempt to create a public key. */
8133     if (PSA_KEY_TYPE_IS_PUBLIC_KEY(attributes->type)) {
8134         return PSA_ERROR_INVALID_ARGUMENT;
8135     }
8136 
8137 #if defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_GENERATE)
8138     if (attributes->type == PSA_KEY_TYPE_RSA_KEY_PAIR) {
8139         if (custom->flags != 0) {
8140             return PSA_ERROR_INVALID_ARGUMENT;
8141         }
8142     } else
8143 #endif
8144     if (!psa_custom_key_parameters_are_default(custom, custom_data_length)) {
8145         return PSA_ERROR_INVALID_ARGUMENT;
8146     }
8147 
8148     status = psa_start_key_creation(PSA_KEY_CREATION_GENERATE, attributes,
8149                                     &slot, &driver);
8150     if (status != PSA_SUCCESS) {
8151         goto exit;
8152     }
8153 
8154     /* In the case of a transparent key or an opaque key stored in local
8155      * storage ( thus not in the case of generating a key in a secure element
8156      * with storage ( MBEDTLS_PSA_CRYPTO_SE_C ) ),we have to allocate a
8157      * buffer to hold the generated key material. */
8158     if (slot->key.bytes == 0) {
8159         if (PSA_KEY_LIFETIME_GET_LOCATION(attributes->lifetime) ==
8160             PSA_KEY_LOCATION_LOCAL_STORAGE) {
8161             status = psa_validate_key_type_and_size_for_key_generation(
8162                 attributes->type, attributes->bits);
8163             if (status != PSA_SUCCESS) {
8164                 goto exit;
8165             }
8166 
8167             key_buffer_size = PSA_EXPORT_KEY_OUTPUT_SIZE(
8168                 attributes->type,
8169                 attributes->bits);
8170         } else {
8171             status = psa_driver_wrapper_get_key_buffer_size(
8172                 attributes, &key_buffer_size);
8173             if (status != PSA_SUCCESS) {
8174                 goto exit;
8175             }
8176         }
8177 
8178         status = psa_allocate_buffer_to_slot(slot, key_buffer_size);
8179         if (status != PSA_SUCCESS) {
8180             goto exit;
8181         }
8182     }
8183 
8184     status = psa_driver_wrapper_generate_key(attributes,
8185                                              custom,
8186                                              custom_data, custom_data_length,
8187                                              slot->key.data, slot->key.bytes,
8188                                              &slot->key.bytes);
8189     if (status != PSA_SUCCESS) {
8190         psa_remove_key_data_from_memory(slot);
8191     }
8192 
8193 exit:
8194     if (status == PSA_SUCCESS) {
8195         status = psa_finish_key_creation(slot, driver, key);
8196     }
8197     if (status != PSA_SUCCESS) {
8198         psa_fail_key_creation(slot, driver);
8199     }
8200 
8201     return status;
8202 }
8203 
8204 psa_status_t psa_generate_key_ext(const psa_key_attributes_t *attributes,
8205                                   const psa_key_production_parameters_t *params,
8206                                   size_t params_data_length,
8207                                   mbedtls_svc_key_id_t *key)
8208 {
8209     return psa_generate_key_custom(
8210         attributes,
8211         (const psa_custom_key_parameters_t *) params,
8212         params->data, params_data_length,
8213         key);
8214 }
8215 
8216 psa_status_t psa_generate_key(const psa_key_attributes_t *attributes,
8217                               mbedtls_svc_key_id_t *key)
8218 {
8219     return psa_generate_key_custom(attributes,
8220                                    &default_custom_production,
8221                                    NULL, 0,
8222                                    key);
8223 }
8224 
8225 /****************************************************************/
8226 /* Module setup */
8227 /****************************************************************/
8228 
8229 #if !defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
8230 psa_status_t mbedtls_psa_crypto_configure_entropy_sources(
8231     void (* entropy_init)(mbedtls_entropy_context *ctx),
8232     void (* entropy_free)(mbedtls_entropy_context *ctx))
8233 {
8234     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
8235 
8236 #if defined(MBEDTLS_THREADING_C)
8237     mbedtls_mutex_lock(&mbedtls_threading_psa_rngdata_mutex);
8238 #endif /* defined(MBEDTLS_THREADING_C) */
8239 
8240     if (global_data.rng_state != RNG_NOT_INITIALIZED) {
8241         status = PSA_ERROR_BAD_STATE;
8242     } else {
8243         global_data.rng.entropy_init = entropy_init;
8244         global_data.rng.entropy_free = entropy_free;
8245         status = PSA_SUCCESS;
8246     }
8247 
8248 #if defined(MBEDTLS_THREADING_C)
8249     mbedtls_mutex_unlock(&mbedtls_threading_psa_rngdata_mutex);
8250 #endif /* defined(MBEDTLS_THREADING_C) */
8251 
8252     return status;
8253 }
8254 #endif /* !defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG) */
8255 
8256 void mbedtls_psa_crypto_free(void)
8257 {
8258 
8259 #if defined(MBEDTLS_THREADING_C)
8260     mbedtls_mutex_lock(&mbedtls_threading_psa_globaldata_mutex);
8261 #endif /* defined(MBEDTLS_THREADING_C) */
8262 
8263     /* Nothing to do to free transaction. */
8264     if (global_data.initialized & PSA_CRYPTO_SUBSYSTEM_TRANSACTION_INITIALIZED) {
8265         global_data.initialized &= ~PSA_CRYPTO_SUBSYSTEM_TRANSACTION_INITIALIZED;
8266     }
8267 
8268     if (global_data.initialized & PSA_CRYPTO_SUBSYSTEM_KEY_SLOTS_INITIALIZED) {
8269         psa_wipe_all_key_slots();
8270         global_data.initialized &= ~PSA_CRYPTO_SUBSYSTEM_KEY_SLOTS_INITIALIZED;
8271     }
8272 
8273 #if defined(MBEDTLS_THREADING_C)
8274     mbedtls_mutex_unlock(&mbedtls_threading_psa_globaldata_mutex);
8275 #endif /* defined(MBEDTLS_THREADING_C) */
8276 
8277 #if defined(MBEDTLS_THREADING_C)
8278     mbedtls_mutex_lock(&mbedtls_threading_psa_rngdata_mutex);
8279 #endif /* defined(MBEDTLS_THREADING_C) */
8280 
8281     if (global_data.rng_state != RNG_NOT_INITIALIZED) {
8282         mbedtls_psa_random_free(&global_data.rng);
8283     }
8284     global_data.rng_state = RNG_NOT_INITIALIZED;
8285     mbedtls_platform_zeroize(&global_data.rng, sizeof(global_data.rng));
8286 
8287 #if defined(MBEDTLS_THREADING_C)
8288     mbedtls_mutex_unlock(&mbedtls_threading_psa_rngdata_mutex);
8289 #endif /* defined(MBEDTLS_THREADING_C) */
8290 
8291 #if defined(MBEDTLS_THREADING_C)
8292     mbedtls_mutex_lock(&mbedtls_threading_psa_globaldata_mutex);
8293 #endif /* defined(MBEDTLS_THREADING_C) */
8294 
8295     /* Terminate drivers */
8296     if (global_data.initialized & PSA_CRYPTO_SUBSYSTEM_DRIVER_WRAPPERS_INITIALIZED) {
8297         psa_driver_wrapper_free();
8298         global_data.initialized &= ~PSA_CRYPTO_SUBSYSTEM_DRIVER_WRAPPERS_INITIALIZED;
8299     }
8300 
8301 #if defined(MBEDTLS_THREADING_C)
8302     mbedtls_mutex_unlock(&mbedtls_threading_psa_globaldata_mutex);
8303 #endif /* defined(MBEDTLS_THREADING_C) */
8304 
8305 }
8306 
8307 #if defined(PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS)
8308 /** Recover a transaction that was interrupted by a power failure.
8309  *
8310  * This function is called during initialization, before psa_crypto_init()
8311  * returns. If this function returns a failure status, the initialization
8312  * fails.
8313  */
8314 static psa_status_t psa_crypto_recover_transaction(
8315     const psa_crypto_transaction_t *transaction)
8316 {
8317     switch (transaction->unknown.type) {
8318         case PSA_CRYPTO_TRANSACTION_CREATE_KEY:
8319         case PSA_CRYPTO_TRANSACTION_DESTROY_KEY:
8320         /* TODO - fall through to the failure case until this
8321          * is implemented.
8322          * https://github.com/ARMmbed/mbed-crypto/issues/218
8323          */
8324         default:
8325             /* We found an unsupported transaction in the storage.
8326              * We don't know what state the storage is in. Give up. */
8327             return PSA_ERROR_DATA_INVALID;
8328     }
8329 }
8330 #endif /* PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS */
8331 
8332 static psa_status_t mbedtls_psa_crypto_init_subsystem(mbedtls_psa_crypto_subsystem subsystem)
8333 {
8334     psa_status_t status = PSA_SUCCESS;
8335     uint8_t driver_wrappers_initialized = 0;
8336 
8337     switch (subsystem) {
8338         case PSA_CRYPTO_SUBSYSTEM_DRIVER_WRAPPERS:
8339 
8340 #if defined(MBEDTLS_THREADING_C)
8341             PSA_THREADING_CHK_GOTO_EXIT(mbedtls_mutex_lock(&mbedtls_threading_psa_globaldata_mutex));
8342 #endif /* defined(MBEDTLS_THREADING_C) */
8343 
8344             if (!(global_data.initialized & PSA_CRYPTO_SUBSYSTEM_DRIVER_WRAPPERS_INITIALIZED)) {
8345                 /* Init drivers */
8346                 status = psa_driver_wrapper_init();
8347 
8348                 /* Drivers need shutdown regardless of startup errors. */
8349                 global_data.initialized |= PSA_CRYPTO_SUBSYSTEM_DRIVER_WRAPPERS_INITIALIZED;
8350 
8351 
8352             }
8353 #if defined(MBEDTLS_THREADING_C)
8354             PSA_THREADING_CHK_GOTO_EXIT(mbedtls_mutex_unlock(
8355                                             &mbedtls_threading_psa_globaldata_mutex));
8356 #endif /* defined(MBEDTLS_THREADING_C) */
8357 
8358             break;
8359 
8360         case PSA_CRYPTO_SUBSYSTEM_KEY_SLOTS:
8361 
8362 #if defined(MBEDTLS_THREADING_C)
8363             PSA_THREADING_CHK_GOTO_EXIT(mbedtls_mutex_lock(&mbedtls_threading_psa_globaldata_mutex));
8364 #endif /* defined(MBEDTLS_THREADING_C) */
8365 
8366             if (!(global_data.initialized & PSA_CRYPTO_SUBSYSTEM_KEY_SLOTS_INITIALIZED)) {
8367                 status = psa_initialize_key_slots();
8368 
8369                 /* Need to wipe keys even if initialization fails. */
8370                 global_data.initialized |= PSA_CRYPTO_SUBSYSTEM_KEY_SLOTS_INITIALIZED;
8371 
8372             }
8373 #if defined(MBEDTLS_THREADING_C)
8374             PSA_THREADING_CHK_GOTO_EXIT(mbedtls_mutex_unlock(
8375                                             &mbedtls_threading_psa_globaldata_mutex));
8376 #endif /* defined(MBEDTLS_THREADING_C) */
8377 
8378             break;
8379 
8380         case PSA_CRYPTO_SUBSYSTEM_RNG:
8381 
8382 #if defined(MBEDTLS_THREADING_C)
8383             PSA_THREADING_CHK_GOTO_EXIT(mbedtls_mutex_lock(&mbedtls_threading_psa_globaldata_mutex));
8384 #endif /* defined(MBEDTLS_THREADING_C) */
8385 
8386             driver_wrappers_initialized =
8387                 (global_data.initialized & PSA_CRYPTO_SUBSYSTEM_DRIVER_WRAPPERS_INITIALIZED);
8388 
8389 #if defined(MBEDTLS_THREADING_C)
8390             PSA_THREADING_CHK_GOTO_EXIT(mbedtls_mutex_unlock(
8391                                             &mbedtls_threading_psa_globaldata_mutex));
8392 #endif /* defined(MBEDTLS_THREADING_C) */
8393 
8394             /* Need to use separate mutex here, as initialisation can require
8395              * testing of init flags, which requires locking the global data
8396              * mutex. */
8397 #if defined(MBEDTLS_THREADING_C)
8398             PSA_THREADING_CHK_GOTO_EXIT(mbedtls_mutex_lock(&mbedtls_threading_psa_rngdata_mutex));
8399 #endif /* defined(MBEDTLS_THREADING_C) */
8400 
8401             /* Initialize and seed the random generator. */
8402             if (global_data.rng_state == RNG_NOT_INITIALIZED && driver_wrappers_initialized) {
8403                 mbedtls_psa_random_init(&global_data.rng);
8404                 global_data.rng_state = RNG_INITIALIZED;
8405 
8406                 status = mbedtls_psa_random_seed(&global_data.rng);
8407                 if (status == PSA_SUCCESS) {
8408                     global_data.rng_state = RNG_SEEDED;
8409                 }
8410             }
8411 
8412 #if defined(MBEDTLS_THREADING_C)
8413             PSA_THREADING_CHK_GOTO_EXIT(mbedtls_mutex_unlock(
8414                                             &mbedtls_threading_psa_rngdata_mutex));
8415 #endif /* defined(MBEDTLS_THREADING_C) */
8416 
8417             break;
8418 
8419         case PSA_CRYPTO_SUBSYSTEM_TRANSACTION:
8420 
8421 #if defined(MBEDTLS_THREADING_C)
8422             PSA_THREADING_CHK_GOTO_EXIT(mbedtls_mutex_lock(&mbedtls_threading_psa_globaldata_mutex));
8423 #endif /* defined(MBEDTLS_THREADING_C) */
8424 
8425             if (!(global_data.initialized & PSA_CRYPTO_SUBSYSTEM_TRANSACTION_INITIALIZED)) {
8426 #if defined(PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS)
8427                 status = psa_crypto_load_transaction();
8428                 if (status == PSA_SUCCESS) {
8429                     status = psa_crypto_recover_transaction(&psa_crypto_transaction);
8430                     if (status == PSA_SUCCESS) {
8431                         global_data.initialized |= PSA_CRYPTO_SUBSYSTEM_TRANSACTION_INITIALIZED;
8432                     }
8433                     status = psa_crypto_stop_transaction();
8434                 } else if (status == PSA_ERROR_DOES_NOT_EXIST) {
8435                     /* There's no transaction to complete. It's all good. */
8436                     global_data.initialized |= PSA_CRYPTO_SUBSYSTEM_TRANSACTION_INITIALIZED;
8437                     status = PSA_SUCCESS;
8438                 }
8439 #else /* defined(PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS) */
8440                 global_data.initialized |= PSA_CRYPTO_SUBSYSTEM_TRANSACTION_INITIALIZED;
8441                 status = PSA_SUCCESS;
8442 #endif /* defined(PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS) */
8443             }
8444 
8445 #if defined(MBEDTLS_THREADING_C)
8446             PSA_THREADING_CHK_GOTO_EXIT(mbedtls_mutex_unlock(
8447                                             &mbedtls_threading_psa_globaldata_mutex));
8448 #endif /* defined(MBEDTLS_THREADING_C) */
8449 
8450             break;
8451 
8452         default:
8453             status = PSA_ERROR_CORRUPTION_DETECTED;
8454     }
8455 
8456     /* Exit label only required when using threading macros. */
8457 #if defined(MBEDTLS_THREADING_C)
8458 exit:
8459 #endif /* defined(MBEDTLS_THREADING_C) */
8460 
8461     return status;
8462 }
8463 
8464 psa_status_t psa_crypto_init(void)
8465 {
8466     psa_status_t status;
8467 
8468     /* Double initialization is explicitly allowed. Early out if everything is
8469      * done. */
8470     if (psa_get_initialized()) {
8471         return PSA_SUCCESS;
8472     }
8473 
8474     status = mbedtls_psa_crypto_init_subsystem(PSA_CRYPTO_SUBSYSTEM_DRIVER_WRAPPERS);
8475     if (status != PSA_SUCCESS) {
8476         goto exit;
8477     }
8478 
8479     status = mbedtls_psa_crypto_init_subsystem(PSA_CRYPTO_SUBSYSTEM_KEY_SLOTS);
8480     if (status != PSA_SUCCESS) {
8481         goto exit;
8482     }
8483 
8484     status = mbedtls_psa_crypto_init_subsystem(PSA_CRYPTO_SUBSYSTEM_RNG);
8485     if (status != PSA_SUCCESS) {
8486         goto exit;
8487     }
8488 
8489     status = mbedtls_psa_crypto_init_subsystem(PSA_CRYPTO_SUBSYSTEM_TRANSACTION);
8490 
8491 exit:
8492 
8493     if (status != PSA_SUCCESS) {
8494         mbedtls_psa_crypto_free();
8495     }
8496 
8497     return status;
8498 }
8499 
8500 #if defined(PSA_WANT_ALG_SOME_PAKE)
8501 psa_status_t psa_crypto_driver_pake_get_password_len(
8502     const psa_crypto_driver_pake_inputs_t *inputs,
8503     size_t *password_len)
8504 {
8505     if (inputs->password_len == 0) {
8506         return PSA_ERROR_BAD_STATE;
8507     }
8508 
8509     *password_len = inputs->password_len;
8510 
8511     return PSA_SUCCESS;
8512 }
8513 
8514 psa_status_t psa_crypto_driver_pake_get_password(
8515     const psa_crypto_driver_pake_inputs_t *inputs,
8516     uint8_t *buffer, size_t buffer_size, size_t *buffer_length)
8517 {
8518     if (inputs->password_len == 0) {
8519         return PSA_ERROR_BAD_STATE;
8520     }
8521 
8522     if (buffer_size < inputs->password_len) {
8523         return PSA_ERROR_BUFFER_TOO_SMALL;
8524     }
8525 
8526     memcpy(buffer, inputs->password, inputs->password_len);
8527     *buffer_length = inputs->password_len;
8528 
8529     return PSA_SUCCESS;
8530 }
8531 
8532 psa_status_t psa_crypto_driver_pake_get_user_len(
8533     const psa_crypto_driver_pake_inputs_t *inputs,
8534     size_t *user_len)
8535 {
8536     if (inputs->user_len == 0) {
8537         return PSA_ERROR_BAD_STATE;
8538     }
8539 
8540     *user_len = inputs->user_len;
8541 
8542     return PSA_SUCCESS;
8543 }
8544 
8545 psa_status_t psa_crypto_driver_pake_get_user(
8546     const psa_crypto_driver_pake_inputs_t *inputs,
8547     uint8_t *user_id, size_t user_id_size, size_t *user_id_len)
8548 {
8549     if (inputs->user_len == 0) {
8550         return PSA_ERROR_BAD_STATE;
8551     }
8552 
8553     if (user_id_size < inputs->user_len) {
8554         return PSA_ERROR_BUFFER_TOO_SMALL;
8555     }
8556 
8557     memcpy(user_id, inputs->user, inputs->user_len);
8558     *user_id_len = inputs->user_len;
8559 
8560     return PSA_SUCCESS;
8561 }
8562 
8563 psa_status_t psa_crypto_driver_pake_get_peer_len(
8564     const psa_crypto_driver_pake_inputs_t *inputs,
8565     size_t *peer_len)
8566 {
8567     if (inputs->peer_len == 0) {
8568         return PSA_ERROR_BAD_STATE;
8569     }
8570 
8571     *peer_len = inputs->peer_len;
8572 
8573     return PSA_SUCCESS;
8574 }
8575 
8576 psa_status_t psa_crypto_driver_pake_get_peer(
8577     const psa_crypto_driver_pake_inputs_t *inputs,
8578     uint8_t *peer_id, size_t peer_id_size, size_t *peer_id_length)
8579 {
8580     if (inputs->peer_len == 0) {
8581         return PSA_ERROR_BAD_STATE;
8582     }
8583 
8584     if (peer_id_size < inputs->peer_len) {
8585         return PSA_ERROR_BUFFER_TOO_SMALL;
8586     }
8587 
8588     memcpy(peer_id, inputs->peer, inputs->peer_len);
8589     *peer_id_length = inputs->peer_len;
8590 
8591     return PSA_SUCCESS;
8592 }
8593 
8594 psa_status_t psa_crypto_driver_pake_get_cipher_suite(
8595     const psa_crypto_driver_pake_inputs_t *inputs,
8596     psa_pake_cipher_suite_t *cipher_suite)
8597 {
8598     if (inputs->cipher_suite.algorithm == PSA_ALG_NONE) {
8599         return PSA_ERROR_BAD_STATE;
8600     }
8601 
8602     *cipher_suite = inputs->cipher_suite;
8603 
8604     return PSA_SUCCESS;
8605 }
8606 
8607 psa_status_t psa_pake_setup(
8608     psa_pake_operation_t *operation,
8609     const psa_pake_cipher_suite_t *cipher_suite)
8610 {
8611     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
8612 
8613     if (operation->stage != PSA_PAKE_OPERATION_STAGE_SETUP) {
8614         status = PSA_ERROR_BAD_STATE;
8615         goto exit;
8616     }
8617 
8618     if (PSA_ALG_IS_PAKE(cipher_suite->algorithm) == 0 ||
8619         PSA_ALG_IS_HASH(cipher_suite->hash) == 0) {
8620         status = PSA_ERROR_INVALID_ARGUMENT;
8621         goto exit;
8622     }
8623 
8624     memset(&operation->data.inputs, 0, sizeof(operation->data.inputs));
8625 
8626     operation->alg = cipher_suite->algorithm;
8627     operation->primitive = PSA_PAKE_PRIMITIVE(cipher_suite->type,
8628                                               cipher_suite->family, cipher_suite->bits);
8629     operation->data.inputs.cipher_suite = *cipher_suite;
8630 
8631 #if defined(PSA_WANT_ALG_JPAKE)
8632     if (operation->alg == PSA_ALG_JPAKE) {
8633         psa_jpake_computation_stage_t *computation_stage =
8634             &operation->computation_stage.jpake;
8635 
8636         memset(computation_stage, 0, sizeof(*computation_stage));
8637         computation_stage->step = PSA_PAKE_STEP_KEY_SHARE;
8638     } else
8639 #endif /* PSA_WANT_ALG_JPAKE */
8640     {
8641         status = PSA_ERROR_NOT_SUPPORTED;
8642         goto exit;
8643     }
8644 
8645     operation->stage = PSA_PAKE_OPERATION_STAGE_COLLECT_INPUTS;
8646 
8647     return PSA_SUCCESS;
8648 exit:
8649     psa_pake_abort(operation);
8650     return status;
8651 }
8652 
8653 psa_status_t psa_pake_set_password_key(
8654     psa_pake_operation_t *operation,
8655     mbedtls_svc_key_id_t password)
8656 {
8657     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
8658     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
8659     psa_key_slot_t *slot = NULL;
8660     psa_key_type_t type;
8661 
8662     if (operation->stage != PSA_PAKE_OPERATION_STAGE_COLLECT_INPUTS) {
8663         status = PSA_ERROR_BAD_STATE;
8664         goto exit;
8665     }
8666 
8667     status = psa_get_and_lock_key_slot_with_policy(password, &slot,
8668                                                    PSA_KEY_USAGE_DERIVE,
8669                                                    operation->alg);
8670     if (status != PSA_SUCCESS) {
8671         goto exit;
8672     }
8673 
8674     type = psa_get_key_type(&slot->attr);
8675 
8676     if (type != PSA_KEY_TYPE_PASSWORD &&
8677         type != PSA_KEY_TYPE_PASSWORD_HASH) {
8678         status = PSA_ERROR_INVALID_ARGUMENT;
8679         goto exit;
8680     }
8681 
8682     operation->data.inputs.password = mbedtls_calloc(1, slot->key.bytes);
8683     if (operation->data.inputs.password == NULL) {
8684         status = PSA_ERROR_INSUFFICIENT_MEMORY;
8685         goto exit;
8686     }
8687 
8688     memcpy(operation->data.inputs.password, slot->key.data, slot->key.bytes);
8689     operation->data.inputs.password_len = slot->key.bytes;
8690     operation->data.inputs.attributes = slot->attr;
8691 
8692 exit:
8693     if (status != PSA_SUCCESS) {
8694         psa_pake_abort(operation);
8695     }
8696     unlock_status = psa_unregister_read_under_mutex(slot);
8697     return (status == PSA_SUCCESS) ? unlock_status : status;
8698 }
8699 
8700 psa_status_t psa_pake_set_user(
8701     psa_pake_operation_t *operation,
8702     const uint8_t *user_id_external,
8703     size_t user_id_len)
8704 {
8705     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
8706     LOCAL_INPUT_DECLARE(user_id_external, user_id);
8707 
8708     if (operation->stage != PSA_PAKE_OPERATION_STAGE_COLLECT_INPUTS) {
8709         status = PSA_ERROR_BAD_STATE;
8710         goto exit;
8711     }
8712 
8713     if (user_id_len == 0) {
8714         status = PSA_ERROR_INVALID_ARGUMENT;
8715         goto exit;
8716     }
8717 
8718     if (operation->data.inputs.user_len != 0) {
8719         status = PSA_ERROR_BAD_STATE;
8720         goto exit;
8721     }
8722 
8723     operation->data.inputs.user = mbedtls_calloc(1, user_id_len);
8724     if (operation->data.inputs.user == NULL) {
8725         status = PSA_ERROR_INSUFFICIENT_MEMORY;
8726         goto exit;
8727     }
8728 
8729     LOCAL_INPUT_ALLOC(user_id_external, user_id_len, user_id);
8730 
8731     memcpy(operation->data.inputs.user, user_id, user_id_len);
8732     operation->data.inputs.user_len = user_id_len;
8733 
8734     status = PSA_SUCCESS;
8735 
8736 exit:
8737     LOCAL_INPUT_FREE(user_id_external, user_id);
8738     if (status != PSA_SUCCESS) {
8739         psa_pake_abort(operation);
8740     }
8741     return status;
8742 }
8743 
8744 psa_status_t psa_pake_set_peer(
8745     psa_pake_operation_t *operation,
8746     const uint8_t *peer_id_external,
8747     size_t peer_id_len)
8748 {
8749     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
8750     LOCAL_INPUT_DECLARE(peer_id_external, peer_id);
8751 
8752     if (operation->stage != PSA_PAKE_OPERATION_STAGE_COLLECT_INPUTS) {
8753         status = PSA_ERROR_BAD_STATE;
8754         goto exit;
8755     }
8756 
8757     if (peer_id_len == 0) {
8758         status = PSA_ERROR_INVALID_ARGUMENT;
8759         goto exit;
8760     }
8761 
8762     if (operation->data.inputs.peer_len != 0) {
8763         status = PSA_ERROR_BAD_STATE;
8764         goto exit;
8765     }
8766 
8767     operation->data.inputs.peer = mbedtls_calloc(1, peer_id_len);
8768     if (operation->data.inputs.peer == NULL) {
8769         status = PSA_ERROR_INSUFFICIENT_MEMORY;
8770         goto exit;
8771     }
8772 
8773     LOCAL_INPUT_ALLOC(peer_id_external, peer_id_len, peer_id);
8774 
8775     memcpy(operation->data.inputs.peer, peer_id, peer_id_len);
8776     operation->data.inputs.peer_len = peer_id_len;
8777 
8778     status = PSA_SUCCESS;
8779 
8780 exit:
8781     LOCAL_INPUT_FREE(peer_id_external, peer_id);
8782     if (status != PSA_SUCCESS) {
8783         psa_pake_abort(operation);
8784     }
8785     return status;
8786 }
8787 
8788 psa_status_t psa_pake_set_role(
8789     psa_pake_operation_t *operation,
8790     psa_pake_role_t role)
8791 {
8792     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
8793 
8794     if (operation->stage != PSA_PAKE_OPERATION_STAGE_COLLECT_INPUTS) {
8795         status = PSA_ERROR_BAD_STATE;
8796         goto exit;
8797     }
8798 
8799     switch (operation->alg) {
8800 #if defined(PSA_WANT_ALG_JPAKE)
8801         case PSA_ALG_JPAKE:
8802             if (role == PSA_PAKE_ROLE_NONE) {
8803                 return PSA_SUCCESS;
8804             }
8805             status = PSA_ERROR_INVALID_ARGUMENT;
8806             break;
8807 #endif
8808         default:
8809             (void) role;
8810             status = PSA_ERROR_NOT_SUPPORTED;
8811             goto exit;
8812     }
8813 exit:
8814     psa_pake_abort(operation);
8815     return status;
8816 }
8817 
8818 /* Auxiliary function to convert core computation stage to single driver step. */
8819 #if defined(PSA_WANT_ALG_JPAKE)
8820 static psa_crypto_driver_pake_step_t convert_jpake_computation_stage_to_driver_step(
8821     psa_jpake_computation_stage_t *stage)
8822 {
8823     psa_crypto_driver_pake_step_t key_share_step;
8824     if (stage->round == PSA_JPAKE_FIRST) {
8825         int is_x1;
8826 
8827         if (stage->io_mode == PSA_JPAKE_OUTPUT) {
8828             is_x1 = (stage->outputs < 1);
8829         } else {
8830             is_x1 = (stage->inputs < 1);
8831         }
8832 
8833         key_share_step = is_x1 ?
8834                          PSA_JPAKE_X1_STEP_KEY_SHARE :
8835                          PSA_JPAKE_X2_STEP_KEY_SHARE;
8836     } else if (stage->round == PSA_JPAKE_SECOND) {
8837         key_share_step = (stage->io_mode == PSA_JPAKE_OUTPUT) ?
8838                          PSA_JPAKE_X2S_STEP_KEY_SHARE :
8839                          PSA_JPAKE_X4S_STEP_KEY_SHARE;
8840     } else {
8841         return PSA_JPAKE_STEP_INVALID;
8842     }
8843     return (psa_crypto_driver_pake_step_t) (key_share_step + stage->step - PSA_PAKE_STEP_KEY_SHARE);
8844 }
8845 #endif /* PSA_WANT_ALG_JPAKE */
8846 
8847 static psa_status_t psa_pake_complete_inputs(
8848     psa_pake_operation_t *operation)
8849 {
8850     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
8851     /* Create copy of the inputs on stack as inputs share memory
8852        with the driver context which will be setup by the driver. */
8853     psa_crypto_driver_pake_inputs_t inputs = operation->data.inputs;
8854 
8855     if (inputs.password_len == 0) {
8856         return PSA_ERROR_BAD_STATE;
8857     }
8858 
8859     if (operation->alg == PSA_ALG_JPAKE) {
8860         if (inputs.user_len == 0 || inputs.peer_len == 0) {
8861             return PSA_ERROR_BAD_STATE;
8862         }
8863     }
8864 
8865     /* Clear driver context */
8866     mbedtls_platform_zeroize(&operation->data, sizeof(operation->data));
8867 
8868     status = psa_driver_wrapper_pake_setup(operation, &inputs);
8869 
8870     /* Driver is responsible for creating its own copy of the password. */
8871     mbedtls_zeroize_and_free(inputs.password, inputs.password_len);
8872 
8873     /* User and peer are translated to role. */
8874     mbedtls_free(inputs.user);
8875     mbedtls_free(inputs.peer);
8876 
8877     if (status == PSA_SUCCESS) {
8878 #if defined(PSA_WANT_ALG_JPAKE)
8879         if (operation->alg == PSA_ALG_JPAKE) {
8880             operation->stage = PSA_PAKE_OPERATION_STAGE_COMPUTATION;
8881         } else
8882 #endif /* PSA_WANT_ALG_JPAKE */
8883         {
8884             status = PSA_ERROR_NOT_SUPPORTED;
8885         }
8886     }
8887     return status;
8888 }
8889 
8890 #if defined(PSA_WANT_ALG_JPAKE)
8891 static psa_status_t psa_jpake_prologue(
8892     psa_pake_operation_t *operation,
8893     psa_pake_step_t step,
8894     psa_jpake_io_mode_t io_mode)
8895 {
8896     if (step != PSA_PAKE_STEP_KEY_SHARE &&
8897         step != PSA_PAKE_STEP_ZK_PUBLIC &&
8898         step != PSA_PAKE_STEP_ZK_PROOF) {
8899         return PSA_ERROR_INVALID_ARGUMENT;
8900     }
8901 
8902     psa_jpake_computation_stage_t *computation_stage =
8903         &operation->computation_stage.jpake;
8904 
8905     if (computation_stage->round != PSA_JPAKE_FIRST &&
8906         computation_stage->round != PSA_JPAKE_SECOND) {
8907         return PSA_ERROR_BAD_STATE;
8908     }
8909 
8910     /* Check that the step we are given is the one we were expecting */
8911     if (step != computation_stage->step) {
8912         return PSA_ERROR_BAD_STATE;
8913     }
8914 
8915     if (step == PSA_PAKE_STEP_KEY_SHARE &&
8916         computation_stage->inputs == 0 &&
8917         computation_stage->outputs == 0) {
8918         /* Start of the round, so function decides whether we are inputting
8919          * or outputting */
8920         computation_stage->io_mode = io_mode;
8921     } else if (computation_stage->io_mode != io_mode) {
8922         /* Middle of the round so the mode we are in must match the function
8923          * called by the user */
8924         return PSA_ERROR_BAD_STATE;
8925     }
8926 
8927     return PSA_SUCCESS;
8928 }
8929 
8930 static psa_status_t psa_jpake_epilogue(
8931     psa_pake_operation_t *operation,
8932     psa_jpake_io_mode_t io_mode)
8933 {
8934     psa_jpake_computation_stage_t *stage =
8935         &operation->computation_stage.jpake;
8936 
8937     if (stage->step == PSA_PAKE_STEP_ZK_PROOF) {
8938         /* End of an input/output */
8939         if (io_mode == PSA_JPAKE_INPUT) {
8940             stage->inputs++;
8941             if (stage->inputs == PSA_JPAKE_EXPECTED_INPUTS(stage->round)) {
8942                 stage->io_mode = PSA_JPAKE_OUTPUT;
8943             }
8944         }
8945         if (io_mode == PSA_JPAKE_OUTPUT) {
8946             stage->outputs++;
8947             if (stage->outputs == PSA_JPAKE_EXPECTED_OUTPUTS(stage->round)) {
8948                 stage->io_mode = PSA_JPAKE_INPUT;
8949             }
8950         }
8951         if (stage->inputs == PSA_JPAKE_EXPECTED_INPUTS(stage->round) &&
8952             stage->outputs == PSA_JPAKE_EXPECTED_OUTPUTS(stage->round)) {
8953             /* End of a round, move to the next round */
8954             stage->inputs = 0;
8955             stage->outputs = 0;
8956             stage->round++;
8957         }
8958         stage->step = PSA_PAKE_STEP_KEY_SHARE;
8959     } else {
8960         stage->step++;
8961     }
8962     return PSA_SUCCESS;
8963 }
8964 
8965 #endif /* PSA_WANT_ALG_JPAKE */
8966 
8967 psa_status_t psa_pake_output(
8968     psa_pake_operation_t *operation,
8969     psa_pake_step_t step,
8970     uint8_t *output_external,
8971     size_t output_size,
8972     size_t *output_length)
8973 {
8974     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
8975     psa_crypto_driver_pake_step_t driver_step = PSA_JPAKE_STEP_INVALID;
8976     LOCAL_OUTPUT_DECLARE(output_external, output);
8977     *output_length = 0;
8978 
8979     if (operation->stage == PSA_PAKE_OPERATION_STAGE_COLLECT_INPUTS) {
8980         status = psa_pake_complete_inputs(operation);
8981         if (status != PSA_SUCCESS) {
8982             goto exit;
8983         }
8984     }
8985 
8986     if (operation->stage != PSA_PAKE_OPERATION_STAGE_COMPUTATION) {
8987         status = PSA_ERROR_BAD_STATE;
8988         goto exit;
8989     }
8990 
8991     if (output_size == 0) {
8992         status = PSA_ERROR_INVALID_ARGUMENT;
8993         goto exit;
8994     }
8995 
8996     switch (operation->alg) {
8997 #if defined(PSA_WANT_ALG_JPAKE)
8998         case PSA_ALG_JPAKE:
8999             status = psa_jpake_prologue(operation, step, PSA_JPAKE_OUTPUT);
9000             if (status != PSA_SUCCESS) {
9001                 goto exit;
9002             }
9003             driver_step = convert_jpake_computation_stage_to_driver_step(
9004                 &operation->computation_stage.jpake);
9005             break;
9006 #endif /* PSA_WANT_ALG_JPAKE */
9007         default:
9008             (void) step;
9009             status = PSA_ERROR_NOT_SUPPORTED;
9010             goto exit;
9011     }
9012 
9013     LOCAL_OUTPUT_ALLOC(output_external, output_size, output);
9014 
9015     status = psa_driver_wrapper_pake_output(operation, driver_step,
9016                                             output, output_size, output_length);
9017 
9018     if (status != PSA_SUCCESS) {
9019         goto exit;
9020     }
9021 
9022     switch (operation->alg) {
9023 #if defined(PSA_WANT_ALG_JPAKE)
9024         case PSA_ALG_JPAKE:
9025             status = psa_jpake_epilogue(operation, PSA_JPAKE_OUTPUT);
9026             if (status != PSA_SUCCESS) {
9027                 goto exit;
9028             }
9029             break;
9030 #endif /* PSA_WANT_ALG_JPAKE */
9031         default:
9032             status = PSA_ERROR_NOT_SUPPORTED;
9033             goto exit;
9034     }
9035 
9036 exit:
9037     LOCAL_OUTPUT_FREE(output_external, output);
9038     if (status != PSA_SUCCESS) {
9039         psa_pake_abort(operation);
9040     }
9041     return status;
9042 }
9043 
9044 psa_status_t psa_pake_input(
9045     psa_pake_operation_t *operation,
9046     psa_pake_step_t step,
9047     const uint8_t *input_external,
9048     size_t input_length)
9049 {
9050     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
9051     psa_crypto_driver_pake_step_t driver_step = PSA_JPAKE_STEP_INVALID;
9052     const size_t max_input_length = (size_t) PSA_PAKE_INPUT_SIZE(operation->alg,
9053                                                                  operation->primitive,
9054                                                                  step);
9055     LOCAL_INPUT_DECLARE(input_external, input);
9056 
9057     if (operation->stage == PSA_PAKE_OPERATION_STAGE_COLLECT_INPUTS) {
9058         status = psa_pake_complete_inputs(operation);
9059         if (status != PSA_SUCCESS) {
9060             goto exit;
9061         }
9062     }
9063 
9064     if (operation->stage != PSA_PAKE_OPERATION_STAGE_COMPUTATION) {
9065         status =  PSA_ERROR_BAD_STATE;
9066         goto exit;
9067     }
9068 
9069     if (input_length == 0 || input_length > max_input_length) {
9070         status = PSA_ERROR_INVALID_ARGUMENT;
9071         goto exit;
9072     }
9073 
9074     switch (operation->alg) {
9075 #if defined(PSA_WANT_ALG_JPAKE)
9076         case PSA_ALG_JPAKE:
9077             status = psa_jpake_prologue(operation, step, PSA_JPAKE_INPUT);
9078             if (status != PSA_SUCCESS) {
9079                 goto exit;
9080             }
9081             driver_step = convert_jpake_computation_stage_to_driver_step(
9082                 &operation->computation_stage.jpake);
9083             break;
9084 #endif /* PSA_WANT_ALG_JPAKE */
9085         default:
9086             (void) step;
9087             status = PSA_ERROR_NOT_SUPPORTED;
9088             goto exit;
9089     }
9090 
9091     LOCAL_INPUT_ALLOC(input_external, input_length, input);
9092     status = psa_driver_wrapper_pake_input(operation, driver_step,
9093                                            input, input_length);
9094 
9095     if (status != PSA_SUCCESS) {
9096         goto exit;
9097     }
9098 
9099     switch (operation->alg) {
9100 #if defined(PSA_WANT_ALG_JPAKE)
9101         case PSA_ALG_JPAKE:
9102             status = psa_jpake_epilogue(operation, PSA_JPAKE_INPUT);
9103             if (status != PSA_SUCCESS) {
9104                 goto exit;
9105             }
9106             break;
9107 #endif /* PSA_WANT_ALG_JPAKE */
9108         default:
9109             status = PSA_ERROR_NOT_SUPPORTED;
9110             goto exit;
9111     }
9112 
9113 exit:
9114     LOCAL_INPUT_FREE(input_external, input);
9115     if (status != PSA_SUCCESS) {
9116         psa_pake_abort(operation);
9117     }
9118     return status;
9119 }
9120 
9121 psa_status_t psa_pake_get_implicit_key(
9122     psa_pake_operation_t *operation,
9123     psa_key_derivation_operation_t *output)
9124 {
9125     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
9126     psa_status_t abort_status = PSA_ERROR_CORRUPTION_DETECTED;
9127     uint8_t shared_key[MBEDTLS_PSA_JPAKE_BUFFER_SIZE];
9128     size_t shared_key_len = 0;
9129 
9130     if (operation->stage != PSA_PAKE_OPERATION_STAGE_COMPUTATION) {
9131         status = PSA_ERROR_BAD_STATE;
9132         goto exit;
9133     }
9134 
9135 #if defined(PSA_WANT_ALG_JPAKE)
9136     if (operation->alg == PSA_ALG_JPAKE) {
9137         psa_jpake_computation_stage_t *computation_stage =
9138             &operation->computation_stage.jpake;
9139         if (computation_stage->round != PSA_JPAKE_FINISHED) {
9140             status = PSA_ERROR_BAD_STATE;
9141             goto exit;
9142         }
9143     } else
9144 #endif /* PSA_WANT_ALG_JPAKE */
9145     {
9146         status = PSA_ERROR_NOT_SUPPORTED;
9147         goto exit;
9148     }
9149 
9150     status = psa_driver_wrapper_pake_get_implicit_key(operation,
9151                                                       shared_key,
9152                                                       sizeof(shared_key),
9153                                                       &shared_key_len);
9154 
9155     if (status != PSA_SUCCESS) {
9156         goto exit;
9157     }
9158 
9159     status = psa_key_derivation_input_bytes(output,
9160                                             PSA_KEY_DERIVATION_INPUT_SECRET,
9161                                             shared_key,
9162                                             shared_key_len);
9163 
9164     mbedtls_platform_zeroize(shared_key, sizeof(shared_key));
9165 exit:
9166     abort_status = psa_pake_abort(operation);
9167     return status == PSA_SUCCESS ? abort_status : status;
9168 }
9169 
9170 psa_status_t psa_pake_abort(
9171     psa_pake_operation_t *operation)
9172 {
9173     psa_status_t status = PSA_SUCCESS;
9174 
9175     if (operation->stage == PSA_PAKE_OPERATION_STAGE_COMPUTATION) {
9176         status = psa_driver_wrapper_pake_abort(operation);
9177     }
9178 
9179     if (operation->stage == PSA_PAKE_OPERATION_STAGE_COLLECT_INPUTS) {
9180         if (operation->data.inputs.password != NULL) {
9181             mbedtls_zeroize_and_free(operation->data.inputs.password,
9182                                      operation->data.inputs.password_len);
9183         }
9184         if (operation->data.inputs.user != NULL) {
9185             mbedtls_free(operation->data.inputs.user);
9186         }
9187         if (operation->data.inputs.peer != NULL) {
9188             mbedtls_free(operation->data.inputs.peer);
9189         }
9190     }
9191     memset(operation, 0, sizeof(psa_pake_operation_t));
9192 
9193     return status;
9194 }
9195 #endif /* PSA_WANT_ALG_SOME_PAKE */
9196 
9197 /* Memory copying test hooks. These are called before input copy, after input
9198  * copy, before output copy and after output copy, respectively.
9199  * They are used by memory-poisoning tests to temporarily unpoison buffers
9200  * while they are copied. */
9201 #if defined(MBEDTLS_TEST_HOOKS)
9202 void (*psa_input_pre_copy_hook)(const uint8_t *input, size_t input_len) = NULL;
9203 void (*psa_input_post_copy_hook)(const uint8_t *input, size_t input_len) = NULL;
9204 void (*psa_output_pre_copy_hook)(const uint8_t *output, size_t output_len) = NULL;
9205 void (*psa_output_post_copy_hook)(const uint8_t *output, size_t output_len) = NULL;
9206 #endif
9207 
9208 /** Copy from an input buffer to a local copy.
9209  *
9210  * \param[in] input             Pointer to input buffer.
9211  * \param[in] input_len         Length of the input buffer.
9212  * \param[out] input_copy       Pointer to a local copy in which to store the input data.
9213  * \param[out] input_copy_len   Length of the local copy buffer.
9214  * \return                      #PSA_SUCCESS, if the buffer was successfully
9215  *                              copied.
9216  * \return                      #PSA_ERROR_CORRUPTION_DETECTED, if the local
9217  *                              copy is too small to hold contents of the
9218  *                              input buffer.
9219  */
9220 MBEDTLS_STATIC_TESTABLE
9221 psa_status_t psa_crypto_copy_input(const uint8_t *input, size_t input_len,
9222                                    uint8_t *input_copy, size_t input_copy_len)
9223 {
9224     if (input_len > input_copy_len) {
9225         return PSA_ERROR_CORRUPTION_DETECTED;
9226     }
9227 
9228 #if defined(MBEDTLS_TEST_HOOKS)
9229     if (psa_input_pre_copy_hook != NULL) {
9230         psa_input_pre_copy_hook(input, input_len);
9231     }
9232 #endif
9233 
9234     if (input_len > 0) {
9235         memcpy(input_copy, input, input_len);
9236     }
9237 
9238 #if defined(MBEDTLS_TEST_HOOKS)
9239     if (psa_input_post_copy_hook != NULL) {
9240         psa_input_post_copy_hook(input, input_len);
9241     }
9242 #endif
9243 
9244     return PSA_SUCCESS;
9245 }
9246 
9247 /** Copy from a local output buffer into a user-supplied one.
9248  *
9249  * \param[in] output_copy       Pointer to a local buffer containing the output.
9250  * \param[in] output_copy_len   Length of the local buffer.
9251  * \param[out] output           Pointer to user-supplied output buffer.
9252  * \param[out] output_len       Length of the user-supplied output buffer.
9253  * \return                      #PSA_SUCCESS, if the buffer was successfully
9254  *                              copied.
9255  * \return                      #PSA_ERROR_BUFFER_TOO_SMALL, if the
9256  *                              user-supplied output buffer is too small to
9257  *                              hold the contents of the local buffer.
9258  */
9259 MBEDTLS_STATIC_TESTABLE
9260 psa_status_t psa_crypto_copy_output(const uint8_t *output_copy, size_t output_copy_len,
9261                                     uint8_t *output, size_t output_len)
9262 {
9263     if (output_len < output_copy_len) {
9264         return PSA_ERROR_BUFFER_TOO_SMALL;
9265     }
9266 
9267 #if defined(MBEDTLS_TEST_HOOKS)
9268     if (psa_output_pre_copy_hook != NULL) {
9269         psa_output_pre_copy_hook(output, output_len);
9270     }
9271 #endif
9272 
9273     if (output_copy_len > 0) {
9274         memcpy(output, output_copy, output_copy_len);
9275     }
9276 
9277 #if defined(MBEDTLS_TEST_HOOKS)
9278     if (psa_output_post_copy_hook != NULL) {
9279         psa_output_post_copy_hook(output, output_len);
9280     }
9281 #endif
9282 
9283     return PSA_SUCCESS;
9284 }
9285 
9286 psa_status_t psa_crypto_local_input_alloc(const uint8_t *input, size_t input_len,
9287                                           psa_crypto_local_input_t *local_input)
9288 {
9289     psa_status_t status;
9290 
9291     *local_input = PSA_CRYPTO_LOCAL_INPUT_INIT;
9292 
9293     if (input_len == 0) {
9294         return PSA_SUCCESS;
9295     }
9296 
9297     local_input->buffer = mbedtls_calloc(input_len, 1);
9298     if (local_input->buffer == NULL) {
9299         /* Since we dealt with the zero-length case above, we know that
9300          * a NULL return value means a failure of allocation. */
9301         return PSA_ERROR_INSUFFICIENT_MEMORY;
9302     }
9303     /* From now on, we must free local_input->buffer on error. */
9304 
9305     local_input->length = input_len;
9306 
9307     status = psa_crypto_copy_input(input, input_len,
9308                                    local_input->buffer, local_input->length);
9309     if (status != PSA_SUCCESS) {
9310         goto error;
9311     }
9312 
9313     return PSA_SUCCESS;
9314 
9315 error:
9316     mbedtls_zeroize_and_free(local_input->buffer, local_input->length);
9317     local_input->buffer = NULL;
9318     local_input->length = 0;
9319     return status;
9320 }
9321 
9322 void psa_crypto_local_input_free(psa_crypto_local_input_t *local_input)
9323 {
9324     mbedtls_zeroize_and_free(local_input->buffer, local_input->length);
9325     local_input->buffer = NULL;
9326     local_input->length = 0;
9327 }
9328 
9329 psa_status_t psa_crypto_local_output_alloc(uint8_t *output, size_t output_len,
9330                                            psa_crypto_local_output_t *local_output)
9331 {
9332     *local_output = PSA_CRYPTO_LOCAL_OUTPUT_INIT;
9333 
9334     if (output_len == 0) {
9335         return PSA_SUCCESS;
9336     }
9337     local_output->buffer = mbedtls_calloc(output_len, 1);
9338     if (local_output->buffer == NULL) {
9339         /* Since we dealt with the zero-length case above, we know that
9340          * a NULL return value means a failure of allocation. */
9341         return PSA_ERROR_INSUFFICIENT_MEMORY;
9342     }
9343     local_output->length = output_len;
9344     local_output->original = output;
9345 
9346     return PSA_SUCCESS;
9347 }
9348 
9349 psa_status_t psa_crypto_local_output_free(psa_crypto_local_output_t *local_output)
9350 {
9351     psa_status_t status;
9352 
9353     if (local_output->buffer == NULL) {
9354         local_output->length = 0;
9355         return PSA_SUCCESS;
9356     }
9357     if (local_output->original == NULL) {
9358         /* We have an internal copy but nothing to copy back to. */
9359         return PSA_ERROR_CORRUPTION_DETECTED;
9360     }
9361 
9362     status = psa_crypto_copy_output(local_output->buffer, local_output->length,
9363                                     local_output->original, local_output->length);
9364     if (status != PSA_SUCCESS) {
9365         return status;
9366     }
9367 
9368     mbedtls_zeroize_and_free(local_output->buffer, local_output->length);
9369     local_output->buffer = NULL;
9370     local_output->length = 0;
9371 
9372     return PSA_SUCCESS;
9373 }
9374 
9375 #endif /* MBEDTLS_PSA_CRYPTO_C */
9376