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