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