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