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