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