• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  PSA crypto layer on top of Mbed TLS crypto
3  */
4 /*
5  *  Copyright The Mbed TLS Contributors
6  *  SPDX-License-Identifier: Apache-2.0 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     LOCAL_INPUT_DECLARE(input_external, input);
3327     LOCAL_INPUT_DECLARE(salt_external, salt);
3328     LOCAL_OUTPUT_DECLARE(output_external, output);
3329 
3330     (void) input;
3331     (void) input_length;
3332     (void) salt;
3333     (void) output;
3334     (void) output_size;
3335 
3336     *output_length = 0;
3337 
3338     if (!PSA_ALG_IS_RSA_OAEP(alg) && salt_length != 0) {
3339         return PSA_ERROR_INVALID_ARGUMENT;
3340     }
3341 
3342     status = psa_get_and_lock_key_slot_with_policy(
3343         key, &slot, PSA_KEY_USAGE_ENCRYPT, alg);
3344     if (status != PSA_SUCCESS) {
3345         return status;
3346     }
3347     if (!(PSA_KEY_TYPE_IS_PUBLIC_KEY(slot->attr.type) ||
3348           PSA_KEY_TYPE_IS_KEY_PAIR(slot->attr.type))) {
3349         status = PSA_ERROR_INVALID_ARGUMENT;
3350         goto exit;
3351     }
3352     LOCAL_INPUT_ALLOC(input_external, input_length, input);
3353     LOCAL_INPUT_ALLOC(salt_external, salt_length, salt);
3354     LOCAL_OUTPUT_ALLOC(output_external, output_size, output);
3355 
3356     status = psa_driver_wrapper_asymmetric_encrypt(
3357         &slot->attr, slot->key.data, slot->key.bytes,
3358         alg, input, input_length, salt, salt_length,
3359         output, output_size, output_length);
3360 exit:
3361     unlock_status = psa_unregister_read_under_mutex(slot);
3362 
3363     LOCAL_INPUT_FREE(input_external, input);
3364     LOCAL_INPUT_FREE(salt_external, salt);
3365     LOCAL_OUTPUT_FREE(output_external, output);
3366 
3367     return (status == PSA_SUCCESS) ? unlock_status : status;
3368 }
3369 
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)3370 psa_status_t psa_asymmetric_decrypt(mbedtls_svc_key_id_t key,
3371                                     psa_algorithm_t alg,
3372                                     const uint8_t *input_external,
3373                                     size_t input_length,
3374                                     const uint8_t *salt_external,
3375                                     size_t salt_length,
3376                                     uint8_t *output_external,
3377                                     size_t output_size,
3378                                     size_t *output_length)
3379 {
3380     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3381     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
3382     psa_key_slot_t *slot;
3383     LOCAL_INPUT_DECLARE(input_external, input);
3384     LOCAL_INPUT_DECLARE(salt_external, salt);
3385     LOCAL_OUTPUT_DECLARE(output_external, output);
3386 
3387     (void) input;
3388     (void) input_length;
3389     (void) salt;
3390     (void) output;
3391     (void) output_size;
3392 
3393     *output_length = 0;
3394 
3395     if (!PSA_ALG_IS_RSA_OAEP(alg) && salt_length != 0) {
3396         return PSA_ERROR_INVALID_ARGUMENT;
3397     }
3398 
3399     status = psa_get_and_lock_key_slot_with_policy(
3400         key, &slot, PSA_KEY_USAGE_DECRYPT, alg);
3401     if (status != PSA_SUCCESS) {
3402         return status;
3403     }
3404     if (!PSA_KEY_TYPE_IS_KEY_PAIR(slot->attr.type)) {
3405         status = PSA_ERROR_INVALID_ARGUMENT;
3406         goto exit;
3407     }
3408     LOCAL_INPUT_ALLOC(input_external, input_length, input);
3409     LOCAL_INPUT_ALLOC(salt_external, salt_length, salt);
3410     LOCAL_OUTPUT_ALLOC(output_external, output_size, output);
3411 
3412     status = psa_driver_wrapper_asymmetric_decrypt(
3413         &slot->attr, slot->key.data, slot->key.bytes,
3414         alg, input, input_length, salt, salt_length,
3415         output, output_size, output_length);
3416 
3417 exit:
3418     unlock_status = psa_unregister_read_under_mutex(slot);
3419 
3420     LOCAL_INPUT_FREE(input_external, input);
3421     LOCAL_INPUT_FREE(salt_external, salt);
3422     LOCAL_OUTPUT_FREE(output_external, output);
3423 
3424     return (status == PSA_SUCCESS) ? unlock_status : status;
3425 }
3426 
3427 /****************************************************************/
3428 /* Asymmetric interruptible cryptography                        */
3429 /****************************************************************/
3430 
3431 static uint32_t psa_interruptible_max_ops = PSA_INTERRUPTIBLE_MAX_OPS_UNLIMITED;
3432 
psa_interruptible_set_max_ops(uint32_t max_ops)3433 void psa_interruptible_set_max_ops(uint32_t max_ops)
3434 {
3435     psa_interruptible_max_ops = max_ops;
3436 }
3437 
psa_interruptible_get_max_ops(void)3438 uint32_t psa_interruptible_get_max_ops(void)
3439 {
3440     return psa_interruptible_max_ops;
3441 }
3442 
psa_sign_hash_get_num_ops(const psa_sign_hash_interruptible_operation_t * operation)3443 uint32_t psa_sign_hash_get_num_ops(
3444     const psa_sign_hash_interruptible_operation_t *operation)
3445 {
3446     return operation->num_ops;
3447 }
3448 
psa_verify_hash_get_num_ops(const psa_verify_hash_interruptible_operation_t * operation)3449 uint32_t psa_verify_hash_get_num_ops(
3450     const psa_verify_hash_interruptible_operation_t *operation)
3451 {
3452     return operation->num_ops;
3453 }
3454 
psa_sign_hash_abort_internal(psa_sign_hash_interruptible_operation_t * operation)3455 static psa_status_t psa_sign_hash_abort_internal(
3456     psa_sign_hash_interruptible_operation_t *operation)
3457 {
3458     if (operation->id == 0) {
3459         /* The object has (apparently) been initialized but it is not (yet)
3460          * in use. It's ok to call abort on such an object, and there's
3461          * nothing to do. */
3462         return PSA_SUCCESS;
3463     }
3464 
3465     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3466 
3467     status = psa_driver_wrapper_sign_hash_abort(operation);
3468 
3469     operation->id = 0;
3470 
3471     /* Do not clear either the error_occurred or num_ops elements here as they
3472      * only want to be cleared by the application calling abort, not by abort
3473      * being called at completion of an operation. */
3474 
3475     return status;
3476 }
3477 
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)3478 psa_status_t psa_sign_hash_start(
3479     psa_sign_hash_interruptible_operation_t *operation,
3480     mbedtls_svc_key_id_t key, psa_algorithm_t alg,
3481     const uint8_t *hash_external, size_t hash_length)
3482 {
3483     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3484     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
3485     psa_key_slot_t *slot;
3486 
3487     LOCAL_INPUT_DECLARE(hash_external, hash);
3488 
3489     /* Check that start has not been previously called, or operation has not
3490      * previously errored. */
3491     if (operation->id != 0 || operation->error_occurred) {
3492         return PSA_ERROR_BAD_STATE;
3493     }
3494 
3495     status = psa_sign_verify_check_alg(0, alg);
3496     if (status != PSA_SUCCESS) {
3497         operation->error_occurred = 1;
3498         return status;
3499     }
3500 
3501     status = psa_get_and_lock_key_slot_with_policy(key, &slot,
3502                                                    PSA_KEY_USAGE_SIGN_HASH,
3503                                                    alg);
3504 
3505     if (status != PSA_SUCCESS) {
3506         goto exit;
3507     }
3508 
3509     if (!PSA_KEY_TYPE_IS_KEY_PAIR(slot->attr.type)) {
3510         status = PSA_ERROR_INVALID_ARGUMENT;
3511         goto exit;
3512     }
3513 
3514     LOCAL_INPUT_ALLOC(hash_external, hash_length, hash);
3515 
3516     /* Ensure ops count gets reset, in case of operation re-use. */
3517     operation->num_ops = 0;
3518 
3519     status = psa_driver_wrapper_sign_hash_start(operation, &slot->attr,
3520                                                 slot->key.data,
3521                                                 slot->key.bytes, alg,
3522                                                 hash, hash_length);
3523 exit:
3524 
3525     if (status != PSA_SUCCESS) {
3526         operation->error_occurred = 1;
3527         psa_sign_hash_abort_internal(operation);
3528     }
3529 
3530     unlock_status = psa_unregister_read_under_mutex(slot);
3531 
3532     if (unlock_status != PSA_SUCCESS) {
3533         operation->error_occurred = 1;
3534     }
3535 
3536     LOCAL_INPUT_FREE(hash_external, hash);
3537 
3538     return (status == PSA_SUCCESS) ? unlock_status : status;
3539 }
3540 
3541 
psa_sign_hash_complete(psa_sign_hash_interruptible_operation_t * operation,uint8_t * signature_external,size_t signature_size,size_t * signature_length)3542 psa_status_t psa_sign_hash_complete(
3543     psa_sign_hash_interruptible_operation_t *operation,
3544     uint8_t *signature_external, size_t signature_size,
3545     size_t *signature_length)
3546 {
3547     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3548 
3549     LOCAL_OUTPUT_DECLARE(signature_external, signature);
3550 
3551     *signature_length = 0;
3552 
3553     /* Check that start has been called first, and that operation has not
3554      * previously errored. */
3555     if (operation->id == 0 || operation->error_occurred) {
3556         status = PSA_ERROR_BAD_STATE;
3557         goto exit;
3558     }
3559 
3560     /* Immediately reject a zero-length signature buffer. This guarantees that
3561      * signature must be a valid pointer. */
3562     if (signature_size == 0) {
3563         status = PSA_ERROR_BUFFER_TOO_SMALL;
3564         goto exit;
3565     }
3566 
3567     LOCAL_OUTPUT_ALLOC(signature_external, signature_size, signature);
3568 
3569     status = psa_driver_wrapper_sign_hash_complete(operation, signature,
3570                                                    signature_size,
3571                                                    signature_length);
3572 
3573     /* Update ops count with work done. */
3574     operation->num_ops = psa_driver_wrapper_sign_hash_get_num_ops(operation);
3575 
3576 exit:
3577 
3578     if (signature != NULL) {
3579         psa_wipe_tag_output_buffer(signature, status, signature_size,
3580                                    *signature_length);
3581     }
3582 
3583     if (status != PSA_OPERATION_INCOMPLETE) {
3584         if (status != PSA_SUCCESS) {
3585             operation->error_occurred = 1;
3586         }
3587 
3588         psa_sign_hash_abort_internal(operation);
3589     }
3590 
3591     LOCAL_OUTPUT_FREE(signature_external, signature);
3592 
3593     return status;
3594 }
3595 
psa_sign_hash_abort(psa_sign_hash_interruptible_operation_t * operation)3596 psa_status_t psa_sign_hash_abort(
3597     psa_sign_hash_interruptible_operation_t *operation)
3598 {
3599     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3600 
3601     status = psa_sign_hash_abort_internal(operation);
3602 
3603     /* We clear the number of ops done here, so that it is not cleared when
3604      * the operation fails or succeeds, only on manual abort. */
3605     operation->num_ops = 0;
3606 
3607     /* Likewise, failure state. */
3608     operation->error_occurred = 0;
3609 
3610     return status;
3611 }
3612 
psa_verify_hash_abort_internal(psa_verify_hash_interruptible_operation_t * operation)3613 static psa_status_t psa_verify_hash_abort_internal(
3614     psa_verify_hash_interruptible_operation_t *operation)
3615 {
3616     if (operation->id == 0) {
3617         /* The object has (apparently) been initialized but it is not (yet)
3618          * in use. It's ok to call abort on such an object, and there's
3619          * nothing to do. */
3620         return PSA_SUCCESS;
3621     }
3622 
3623     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3624 
3625     status = psa_driver_wrapper_verify_hash_abort(operation);
3626 
3627     operation->id = 0;
3628 
3629     /* Do not clear either the error_occurred or num_ops elements here as they
3630      * only want to be cleared by the application calling abort, not by abort
3631      * being called at completion of an operation. */
3632 
3633     return status;
3634 }
3635 
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)3636 psa_status_t psa_verify_hash_start(
3637     psa_verify_hash_interruptible_operation_t *operation,
3638     mbedtls_svc_key_id_t key, psa_algorithm_t alg,
3639     const uint8_t *hash_external, size_t hash_length,
3640     const uint8_t *signature_external, size_t signature_length)
3641 {
3642     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3643     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
3644     psa_key_slot_t *slot;
3645 
3646     LOCAL_INPUT_DECLARE(hash_external, hash);
3647     LOCAL_INPUT_DECLARE(signature_external, signature);
3648 
3649     /* Check that start has not been previously called, or operation has not
3650      * previously errored. */
3651     if (operation->id != 0 || operation->error_occurred) {
3652         return PSA_ERROR_BAD_STATE;
3653     }
3654 
3655     status = psa_sign_verify_check_alg(0, alg);
3656     if (status != PSA_SUCCESS) {
3657         operation->error_occurred = 1;
3658         return status;
3659     }
3660 
3661     status = psa_get_and_lock_key_slot_with_policy(key, &slot,
3662                                                    PSA_KEY_USAGE_VERIFY_HASH,
3663                                                    alg);
3664 
3665     if (status != PSA_SUCCESS) {
3666         operation->error_occurred = 1;
3667         return status;
3668     }
3669 
3670     LOCAL_INPUT_ALLOC(hash_external, hash_length, hash);
3671     LOCAL_INPUT_ALLOC(signature_external, signature_length, signature);
3672 
3673     /* Ensure ops count gets reset, in case of operation re-use. */
3674     operation->num_ops = 0;
3675 
3676     status = psa_driver_wrapper_verify_hash_start(operation, &slot->attr,
3677                                                   slot->key.data,
3678                                                   slot->key.bytes,
3679                                                   alg, hash, hash_length,
3680                                                   signature, signature_length);
3681 #if !defined(MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS)
3682 exit:
3683 #endif
3684 
3685     if (status != PSA_SUCCESS) {
3686         operation->error_occurred = 1;
3687         psa_verify_hash_abort_internal(operation);
3688     }
3689 
3690     unlock_status = psa_unregister_read_under_mutex(slot);
3691 
3692     if (unlock_status != PSA_SUCCESS) {
3693         operation->error_occurred = 1;
3694     }
3695 
3696     LOCAL_INPUT_FREE(hash_external, hash);
3697     LOCAL_INPUT_FREE(signature_external, signature);
3698 
3699     return (status == PSA_SUCCESS) ? unlock_status : status;
3700 }
3701 
psa_verify_hash_complete(psa_verify_hash_interruptible_operation_t * operation)3702 psa_status_t psa_verify_hash_complete(
3703     psa_verify_hash_interruptible_operation_t *operation)
3704 {
3705     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3706 
3707     /* Check that start has been called first, and that operation has not
3708      * previously errored. */
3709     if (operation->id == 0 || operation->error_occurred) {
3710         status = PSA_ERROR_BAD_STATE;
3711         goto exit;
3712     }
3713 
3714     status = psa_driver_wrapper_verify_hash_complete(operation);
3715 
3716     /* Update ops count with work done. */
3717     operation->num_ops = psa_driver_wrapper_verify_hash_get_num_ops(
3718         operation);
3719 
3720 exit:
3721 
3722     if (status != PSA_OPERATION_INCOMPLETE) {
3723         if (status != PSA_SUCCESS) {
3724             operation->error_occurred = 1;
3725         }
3726 
3727         psa_verify_hash_abort_internal(operation);
3728     }
3729 
3730     return status;
3731 }
3732 
psa_verify_hash_abort(psa_verify_hash_interruptible_operation_t * operation)3733 psa_status_t psa_verify_hash_abort(
3734     psa_verify_hash_interruptible_operation_t *operation)
3735 {
3736     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3737 
3738     status = psa_verify_hash_abort_internal(operation);
3739 
3740     /* We clear the number of ops done here, so that it is not cleared when
3741      * the operation fails or succeeds, only on manual abort. */
3742     operation->num_ops = 0;
3743 
3744     /* Likewise, failure state. */
3745     operation->error_occurred = 0;
3746 
3747     return status;
3748 }
3749 
3750 /****************************************************************/
3751 /* Asymmetric interruptible cryptography internal               */
3752 /* implementations                                              */
3753 /****************************************************************/
3754 
mbedtls_psa_interruptible_set_max_ops(uint32_t max_ops)3755 void mbedtls_psa_interruptible_set_max_ops(uint32_t max_ops)
3756 {
3757 
3758 #if (defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
3759     defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)) && \
3760     defined(MBEDTLS_ECP_RESTARTABLE)
3761 
3762     /* Internal implementation uses zero to indicate infinite number max ops,
3763      * therefore avoid this value, and set to minimum possible. */
3764     if (max_ops == 0) {
3765         max_ops = 1;
3766     }
3767 
3768     mbedtls_ecp_set_max_ops(max_ops);
3769 #else
3770     (void) max_ops;
3771 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
3772         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) &&
3773         * defined( MBEDTLS_ECP_RESTARTABLE ) */
3774 }
3775 
mbedtls_psa_sign_hash_get_num_ops(const mbedtls_psa_sign_hash_interruptible_operation_t * operation)3776 uint32_t mbedtls_psa_sign_hash_get_num_ops(
3777     const mbedtls_psa_sign_hash_interruptible_operation_t *operation)
3778 {
3779 #if (defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
3780     defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)) && \
3781     defined(MBEDTLS_ECP_RESTARTABLE)
3782 
3783     return operation->num_ops;
3784 #else
3785     (void) operation;
3786     return 0;
3787 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
3788         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) &&
3789         * defined( MBEDTLS_ECP_RESTARTABLE ) */
3790 }
3791 
mbedtls_psa_verify_hash_get_num_ops(const mbedtls_psa_verify_hash_interruptible_operation_t * operation)3792 uint32_t mbedtls_psa_verify_hash_get_num_ops(
3793     const mbedtls_psa_verify_hash_interruptible_operation_t *operation)
3794 {
3795     #if (defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
3796     defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)) && \
3797     defined(MBEDTLS_ECP_RESTARTABLE)
3798 
3799     return operation->num_ops;
3800 #else
3801     (void) operation;
3802     return 0;
3803 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
3804         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) &&
3805         * defined( MBEDTLS_ECP_RESTARTABLE ) */
3806 }
3807 
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)3808 psa_status_t mbedtls_psa_sign_hash_start(
3809     mbedtls_psa_sign_hash_interruptible_operation_t *operation,
3810     const psa_key_attributes_t *attributes, const uint8_t *key_buffer,
3811     size_t key_buffer_size, psa_algorithm_t alg,
3812     const uint8_t *hash, size_t hash_length)
3813 {
3814     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3815     size_t required_hash_length;
3816 
3817     if (!PSA_KEY_TYPE_IS_ECC(attributes->type)) {
3818         return PSA_ERROR_NOT_SUPPORTED;
3819     }
3820 
3821     if (!PSA_ALG_IS_ECDSA(alg)) {
3822         return PSA_ERROR_NOT_SUPPORTED;
3823     }
3824 
3825 #if (defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
3826     defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)) && \
3827     defined(MBEDTLS_ECP_RESTARTABLE)
3828 
3829     mbedtls_ecdsa_restart_init(&operation->restart_ctx);
3830 
3831     /* Ensure num_ops is zero'ed in case of context re-use. */
3832     operation->num_ops = 0;
3833 
3834     status = mbedtls_psa_ecp_load_representation(attributes->type,
3835                                                  attributes->bits,
3836                                                  key_buffer,
3837                                                  key_buffer_size,
3838                                                  &operation->ctx);
3839 
3840     if (status != PSA_SUCCESS) {
3841         return status;
3842     }
3843 
3844     operation->coordinate_bytes = PSA_BITS_TO_BYTES(
3845         operation->ctx->grp.nbits);
3846 
3847     psa_algorithm_t hash_alg = PSA_ALG_SIGN_GET_HASH(alg);
3848     operation->md_alg = mbedtls_md_type_from_psa_alg(hash_alg);
3849     operation->alg = alg;
3850 
3851     /* We only need to store the same length of hash as the private key size
3852      * here, it would be truncated by the internal implementation anyway. */
3853     required_hash_length = (hash_length < operation->coordinate_bytes ?
3854                             hash_length : operation->coordinate_bytes);
3855 
3856     if (required_hash_length > sizeof(operation->hash)) {
3857         /* Shouldn't happen, but better safe than sorry. */
3858         return PSA_ERROR_CORRUPTION_DETECTED;
3859     }
3860 
3861     memcpy(operation->hash, hash, required_hash_length);
3862     operation->hash_length = required_hash_length;
3863 
3864     return PSA_SUCCESS;
3865 
3866 #else
3867     (void) operation;
3868     (void) key_buffer;
3869     (void) key_buffer_size;
3870     (void) alg;
3871     (void) hash;
3872     (void) hash_length;
3873     (void) status;
3874     (void) required_hash_length;
3875 
3876     return PSA_ERROR_NOT_SUPPORTED;
3877 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
3878         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) &&
3879         * defined( MBEDTLS_ECP_RESTARTABLE ) */
3880 }
3881 
mbedtls_psa_sign_hash_complete(mbedtls_psa_sign_hash_interruptible_operation_t * operation,uint8_t * signature,size_t signature_size,size_t * signature_length)3882 psa_status_t mbedtls_psa_sign_hash_complete(
3883     mbedtls_psa_sign_hash_interruptible_operation_t *operation,
3884     uint8_t *signature, size_t signature_size,
3885     size_t *signature_length)
3886 {
3887 #if (defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
3888     defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)) && \
3889     defined(MBEDTLS_ECP_RESTARTABLE)
3890 
3891     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3892     mbedtls_mpi r;
3893     mbedtls_mpi s;
3894 
3895     mbedtls_mpi_init(&r);
3896     mbedtls_mpi_init(&s);
3897 
3898     /* Ensure max_ops is set to the current value (or default). */
3899     mbedtls_psa_interruptible_set_max_ops(psa_interruptible_get_max_ops());
3900 
3901     if (signature_size < 2 * operation->coordinate_bytes) {
3902         status = PSA_ERROR_BUFFER_TOO_SMALL;
3903         goto exit;
3904     }
3905 
3906     if (PSA_ALG_ECDSA_IS_DETERMINISTIC(operation->alg)) {
3907 
3908 #if defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)
3909         status = mbedtls_to_psa_error(
3910             mbedtls_ecdsa_sign_det_restartable(&operation->ctx->grp,
3911                                                &r,
3912                                                &s,
3913                                                &operation->ctx->d,
3914                                                operation->hash,
3915                                                operation->hash_length,
3916                                                operation->md_alg,
3917                                                mbedtls_psa_get_random,
3918                                                MBEDTLS_PSA_RANDOM_STATE,
3919                                                &operation->restart_ctx));
3920 #else /* defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) */
3921         status = PSA_ERROR_NOT_SUPPORTED;
3922         goto exit;
3923 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) */
3924     } else {
3925         status = mbedtls_to_psa_error(
3926             mbedtls_ecdsa_sign_restartable(&operation->ctx->grp,
3927                                            &r,
3928                                            &s,
3929                                            &operation->ctx->d,
3930                                            operation->hash,
3931                                            operation->hash_length,
3932                                            mbedtls_psa_get_random,
3933                                            MBEDTLS_PSA_RANDOM_STATE,
3934                                            mbedtls_psa_get_random,
3935                                            MBEDTLS_PSA_RANDOM_STATE,
3936                                            &operation->restart_ctx));
3937     }
3938 
3939     /* Hide the fact that the restart context only holds a delta of number of
3940      * ops done during the last operation, not an absolute value. */
3941     operation->num_ops += operation->restart_ctx.ecp.ops_done;
3942 
3943     if (status == PSA_SUCCESS) {
3944         status =  mbedtls_to_psa_error(
3945             mbedtls_mpi_write_binary(&r,
3946                                      signature,
3947                                      operation->coordinate_bytes)
3948             );
3949 
3950         if (status != PSA_SUCCESS) {
3951             goto exit;
3952         }
3953 
3954         status =  mbedtls_to_psa_error(
3955             mbedtls_mpi_write_binary(&s,
3956                                      signature +
3957                                      operation->coordinate_bytes,
3958                                      operation->coordinate_bytes)
3959             );
3960 
3961         if (status != PSA_SUCCESS) {
3962             goto exit;
3963         }
3964 
3965         *signature_length = operation->coordinate_bytes * 2;
3966 
3967         status = PSA_SUCCESS;
3968     }
3969 
3970 exit:
3971 
3972     mbedtls_mpi_free(&r);
3973     mbedtls_mpi_free(&s);
3974     return status;
3975 
3976  #else
3977 
3978     (void) operation;
3979     (void) signature;
3980     (void) signature_size;
3981     (void) signature_length;
3982 
3983     return PSA_ERROR_NOT_SUPPORTED;
3984 
3985 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
3986         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) &&
3987         * defined( MBEDTLS_ECP_RESTARTABLE ) */
3988 }
3989 
mbedtls_psa_sign_hash_abort(mbedtls_psa_sign_hash_interruptible_operation_t * operation)3990 psa_status_t mbedtls_psa_sign_hash_abort(
3991     mbedtls_psa_sign_hash_interruptible_operation_t *operation)
3992 {
3993 
3994 #if (defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
3995     defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)) && \
3996     defined(MBEDTLS_ECP_RESTARTABLE)
3997 
3998     if (operation->ctx) {
3999         mbedtls_ecdsa_free(operation->ctx);
4000         mbedtls_free(operation->ctx);
4001         operation->ctx = NULL;
4002     }
4003 
4004     mbedtls_ecdsa_restart_free(&operation->restart_ctx);
4005 
4006     operation->num_ops = 0;
4007 
4008     return PSA_SUCCESS;
4009 
4010 #else
4011 
4012     (void) operation;
4013 
4014     return PSA_ERROR_NOT_SUPPORTED;
4015 
4016 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
4017         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) &&
4018         * defined( MBEDTLS_ECP_RESTARTABLE ) */
4019 }
4020 
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)4021 psa_status_t mbedtls_psa_verify_hash_start(
4022     mbedtls_psa_verify_hash_interruptible_operation_t *operation,
4023     const psa_key_attributes_t *attributes,
4024     const uint8_t *key_buffer, size_t key_buffer_size,
4025     psa_algorithm_t alg,
4026     const uint8_t *hash, size_t hash_length,
4027     const uint8_t *signature, size_t signature_length)
4028 {
4029     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4030     size_t coordinate_bytes = 0;
4031     size_t required_hash_length = 0;
4032 
4033     if (!PSA_KEY_TYPE_IS_ECC(attributes->type)) {
4034         return PSA_ERROR_NOT_SUPPORTED;
4035     }
4036 
4037     if (!PSA_ALG_IS_ECDSA(alg)) {
4038         return PSA_ERROR_NOT_SUPPORTED;
4039     }
4040 
4041 #if (defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
4042     defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)) && \
4043     defined(MBEDTLS_ECP_RESTARTABLE)
4044 
4045     mbedtls_ecdsa_restart_init(&operation->restart_ctx);
4046     mbedtls_mpi_init(&operation->r);
4047     mbedtls_mpi_init(&operation->s);
4048 
4049     /* Ensure num_ops is zero'ed in case of context re-use. */
4050     operation->num_ops = 0;
4051 
4052     status = mbedtls_psa_ecp_load_representation(attributes->type,
4053                                                  attributes->bits,
4054                                                  key_buffer,
4055                                                  key_buffer_size,
4056                                                  &operation->ctx);
4057 
4058     if (status != PSA_SUCCESS) {
4059         return status;
4060     }
4061 
4062     coordinate_bytes = PSA_BITS_TO_BYTES(operation->ctx->grp.nbits);
4063 
4064     if (signature_length != 2 * coordinate_bytes) {
4065         return PSA_ERROR_INVALID_SIGNATURE;
4066     }
4067 
4068     status = mbedtls_to_psa_error(
4069         mbedtls_mpi_read_binary(&operation->r,
4070                                 signature,
4071                                 coordinate_bytes));
4072 
4073     if (status != PSA_SUCCESS) {
4074         return status;
4075     }
4076 
4077     status = mbedtls_to_psa_error(
4078         mbedtls_mpi_read_binary(&operation->s,
4079                                 signature +
4080                                 coordinate_bytes,
4081                                 coordinate_bytes));
4082 
4083     if (status != PSA_SUCCESS) {
4084         return status;
4085     }
4086 
4087     status = mbedtls_psa_ecp_load_public_part(operation->ctx);
4088 
4089     if (status != PSA_SUCCESS) {
4090         return status;
4091     }
4092 
4093     /* We only need to store the same length of hash as the private key size
4094      * here, it would be truncated by the internal implementation anyway. */
4095     required_hash_length = (hash_length < coordinate_bytes ? hash_length :
4096                             coordinate_bytes);
4097 
4098     if (required_hash_length > sizeof(operation->hash)) {
4099         /* Shouldn't happen, but better safe than sorry. */
4100         return PSA_ERROR_CORRUPTION_DETECTED;
4101     }
4102 
4103     memcpy(operation->hash, hash, required_hash_length);
4104     operation->hash_length = required_hash_length;
4105 
4106     return PSA_SUCCESS;
4107 #else
4108     (void) operation;
4109     (void) key_buffer;
4110     (void) key_buffer_size;
4111     (void) alg;
4112     (void) hash;
4113     (void) hash_length;
4114     (void) signature;
4115     (void) signature_length;
4116     (void) status;
4117     (void) coordinate_bytes;
4118     (void) required_hash_length;
4119 
4120     return PSA_ERROR_NOT_SUPPORTED;
4121 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
4122         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) &&
4123         * defined( MBEDTLS_ECP_RESTARTABLE ) */
4124 }
4125 
mbedtls_psa_verify_hash_complete(mbedtls_psa_verify_hash_interruptible_operation_t * operation)4126 psa_status_t mbedtls_psa_verify_hash_complete(
4127     mbedtls_psa_verify_hash_interruptible_operation_t *operation)
4128 {
4129 
4130 #if (defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
4131     defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)) && \
4132     defined(MBEDTLS_ECP_RESTARTABLE)
4133 
4134     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4135 
4136     /* Ensure max_ops is set to the current value (or default). */
4137     mbedtls_psa_interruptible_set_max_ops(psa_interruptible_get_max_ops());
4138 
4139     status = mbedtls_to_psa_error(
4140         mbedtls_ecdsa_verify_restartable(&operation->ctx->grp,
4141                                          operation->hash,
4142                                          operation->hash_length,
4143                                          &operation->ctx->Q,
4144                                          &operation->r,
4145                                          &operation->s,
4146                                          &operation->restart_ctx));
4147 
4148     /* Hide the fact that the restart context only holds a delta of number of
4149      * ops done during the last operation, not an absolute value. */
4150     operation->num_ops += operation->restart_ctx.ecp.ops_done;
4151 
4152     return status;
4153 #else
4154     (void) operation;
4155 
4156     return PSA_ERROR_NOT_SUPPORTED;
4157 
4158 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
4159         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) &&
4160         * defined( MBEDTLS_ECP_RESTARTABLE ) */
4161 }
4162 
mbedtls_psa_verify_hash_abort(mbedtls_psa_verify_hash_interruptible_operation_t * operation)4163 psa_status_t mbedtls_psa_verify_hash_abort(
4164     mbedtls_psa_verify_hash_interruptible_operation_t *operation)
4165 {
4166 
4167 #if (defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
4168     defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)) && \
4169     defined(MBEDTLS_ECP_RESTARTABLE)
4170 
4171     if (operation->ctx) {
4172         mbedtls_ecdsa_free(operation->ctx);
4173         mbedtls_free(operation->ctx);
4174         operation->ctx = NULL;
4175     }
4176 
4177     mbedtls_ecdsa_restart_free(&operation->restart_ctx);
4178 
4179     operation->num_ops = 0;
4180 
4181     mbedtls_mpi_free(&operation->r);
4182     mbedtls_mpi_free(&operation->s);
4183 
4184     return PSA_SUCCESS;
4185 
4186 #else
4187     (void) operation;
4188 
4189     return PSA_ERROR_NOT_SUPPORTED;
4190 
4191 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
4192         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) &&
4193         * defined( MBEDTLS_ECP_RESTARTABLE ) */
4194 }
4195 
psa_generate_random_internal(uint8_t * output,size_t output_size)4196 static psa_status_t psa_generate_random_internal(uint8_t *output,
4197                                                  size_t output_size)
4198 {
4199     GUARD_MODULE_INITIALIZED;
4200 
4201 #if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
4202 
4203     psa_status_t status;
4204     size_t output_length = 0;
4205     status = mbedtls_psa_external_get_random(&global_data.rng,
4206                                              output, output_size,
4207                                              &output_length);
4208     if (status != PSA_SUCCESS) {
4209         return status;
4210     }
4211     /* Breaking up a request into smaller chunks is currently not supported
4212      * for the external RNG interface. */
4213     if (output_length != output_size) {
4214         return PSA_ERROR_INSUFFICIENT_ENTROPY;
4215     }
4216     return PSA_SUCCESS;
4217 
4218 #else /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
4219 
4220     while (output_size > 0) {
4221         int ret = MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED;
4222         size_t request_size =
4223             (output_size > MBEDTLS_PSA_RANDOM_MAX_REQUEST ?
4224              MBEDTLS_PSA_RANDOM_MAX_REQUEST :
4225              output_size);
4226 #if defined(MBEDTLS_CTR_DRBG_C)
4227         ret = mbedtls_ctr_drbg_random(&global_data.rng.drbg, output, request_size);
4228 #elif defined(MBEDTLS_HMAC_DRBG_C)
4229         ret = mbedtls_hmac_drbg_random(&global_data.rng.drbg, output, request_size);
4230 #endif /* !MBEDTLS_CTR_DRBG_C && !MBEDTLS_HMAC_DRBG_C */
4231         if (ret != 0) {
4232             return mbedtls_to_psa_error(ret);
4233         }
4234         output_size -= request_size;
4235         output += request_size;
4236     }
4237     return PSA_SUCCESS;
4238 #endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
4239 }
4240 
4241 
4242 /****************************************************************/
4243 /* Symmetric cryptography */
4244 /****************************************************************/
4245 
psa_cipher_setup(psa_cipher_operation_t * operation,mbedtls_svc_key_id_t key,psa_algorithm_t alg,mbedtls_operation_t cipher_operation)4246 static psa_status_t psa_cipher_setup(psa_cipher_operation_t *operation,
4247                                      mbedtls_svc_key_id_t key,
4248                                      psa_algorithm_t alg,
4249                                      mbedtls_operation_t cipher_operation)
4250 {
4251     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4252     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
4253     psa_key_slot_t *slot = NULL;
4254     psa_key_usage_t usage = (cipher_operation == MBEDTLS_ENCRYPT ?
4255                              PSA_KEY_USAGE_ENCRYPT :
4256                              PSA_KEY_USAGE_DECRYPT);
4257 
4258     /* A context must be freshly initialized before it can be set up. */
4259     if (operation->id != 0) {
4260         status = PSA_ERROR_BAD_STATE;
4261         goto exit;
4262     }
4263 
4264     if (!PSA_ALG_IS_CIPHER(alg)) {
4265         status = PSA_ERROR_INVALID_ARGUMENT;
4266         goto exit;
4267     }
4268 
4269     status = psa_get_and_lock_key_slot_with_policy(key, &slot, usage, alg);
4270     if (status != PSA_SUCCESS) {
4271         goto exit;
4272     }
4273 
4274     /* Initialize the operation struct members, except for id. The id member
4275      * is used to indicate to psa_cipher_abort that there are resources to free,
4276      * so we only set it (in the driver wrapper) after resources have been
4277      * allocated/initialized. */
4278     operation->iv_set = 0;
4279     if (alg == PSA_ALG_ECB_NO_PADDING) {
4280         operation->iv_required = 0;
4281     } else {
4282         operation->iv_required = 1;
4283     }
4284     operation->default_iv_length = PSA_CIPHER_IV_LENGTH(slot->attr.type, alg);
4285 
4286     /* Try doing the operation through a driver before using software fallback. */
4287     if (cipher_operation == MBEDTLS_ENCRYPT) {
4288         status = psa_driver_wrapper_cipher_encrypt_setup(operation,
4289                                                          &slot->attr,
4290                                                          slot->key.data,
4291                                                          slot->key.bytes,
4292                                                          alg);
4293     } else {
4294         status = psa_driver_wrapper_cipher_decrypt_setup(operation,
4295                                                          &slot->attr,
4296                                                          slot->key.data,
4297                                                          slot->key.bytes,
4298                                                          alg);
4299     }
4300 
4301 exit:
4302     if (status != PSA_SUCCESS) {
4303         psa_cipher_abort(operation);
4304     }
4305 
4306     unlock_status = psa_unregister_read_under_mutex(slot);
4307 
4308     return (status == PSA_SUCCESS) ? unlock_status : status;
4309 }
4310 
psa_cipher_encrypt_setup(psa_cipher_operation_t * operation,mbedtls_svc_key_id_t key,psa_algorithm_t alg)4311 psa_status_t psa_cipher_encrypt_setup(psa_cipher_operation_t *operation,
4312                                       mbedtls_svc_key_id_t key,
4313                                       psa_algorithm_t alg)
4314 {
4315     return psa_cipher_setup(operation, key, alg, MBEDTLS_ENCRYPT);
4316 }
4317 
psa_cipher_decrypt_setup(psa_cipher_operation_t * operation,mbedtls_svc_key_id_t key,psa_algorithm_t alg)4318 psa_status_t psa_cipher_decrypt_setup(psa_cipher_operation_t *operation,
4319                                       mbedtls_svc_key_id_t key,
4320                                       psa_algorithm_t alg)
4321 {
4322     return psa_cipher_setup(operation, key, alg, MBEDTLS_DECRYPT);
4323 }
4324 
psa_cipher_generate_iv(psa_cipher_operation_t * operation,uint8_t * iv_external,size_t iv_size,size_t * iv_length)4325 psa_status_t psa_cipher_generate_iv(psa_cipher_operation_t *operation,
4326                                     uint8_t *iv_external,
4327                                     size_t iv_size,
4328                                     size_t *iv_length)
4329 {
4330     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4331     size_t default_iv_length = 0;
4332 
4333     LOCAL_OUTPUT_DECLARE(iv_external, iv);
4334 
4335     if (operation->id == 0) {
4336         status = PSA_ERROR_BAD_STATE;
4337         goto exit;
4338     }
4339 
4340     if (operation->iv_set || !operation->iv_required) {
4341         status = PSA_ERROR_BAD_STATE;
4342         goto exit;
4343     }
4344 
4345     default_iv_length = operation->default_iv_length;
4346     if (iv_size < default_iv_length) {
4347         status = PSA_ERROR_BUFFER_TOO_SMALL;
4348         goto exit;
4349     }
4350 
4351     if (default_iv_length > PSA_CIPHER_IV_MAX_SIZE) {
4352         status = PSA_ERROR_GENERIC_ERROR;
4353         goto exit;
4354     }
4355 
4356     LOCAL_OUTPUT_ALLOC(iv_external, default_iv_length, iv);
4357 
4358     status = psa_generate_random_internal(iv, default_iv_length);
4359     if (status != PSA_SUCCESS) {
4360         goto exit;
4361     }
4362 
4363     status = psa_driver_wrapper_cipher_set_iv(operation,
4364                                               iv, default_iv_length);
4365 
4366 exit:
4367     if (status == PSA_SUCCESS) {
4368         *iv_length = default_iv_length;
4369         operation->iv_set = 1;
4370     } else {
4371         *iv_length = 0;
4372         psa_cipher_abort(operation);
4373         if (iv != NULL) {
4374             mbedtls_platform_zeroize(iv, default_iv_length);
4375         }
4376     }
4377 
4378     LOCAL_OUTPUT_FREE(iv_external, iv);
4379     return status;
4380 }
4381 
psa_cipher_set_iv(psa_cipher_operation_t * operation,const uint8_t * iv_external,size_t iv_length)4382 psa_status_t psa_cipher_set_iv(psa_cipher_operation_t *operation,
4383                                const uint8_t *iv_external,
4384                                size_t iv_length)
4385 {
4386     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4387 
4388     LOCAL_INPUT_DECLARE(iv_external, iv);
4389 
4390     if (operation->id == 0) {
4391         status = PSA_ERROR_BAD_STATE;
4392         goto exit;
4393     }
4394 
4395     if (operation->iv_set || !operation->iv_required) {
4396         status = PSA_ERROR_BAD_STATE;
4397         goto exit;
4398     }
4399 
4400     if (iv_length > PSA_CIPHER_IV_MAX_SIZE) {
4401         status = PSA_ERROR_INVALID_ARGUMENT;
4402         goto exit;
4403     }
4404 
4405     LOCAL_INPUT_ALLOC(iv_external, iv_length, iv);
4406 
4407     status = psa_driver_wrapper_cipher_set_iv(operation,
4408                                               iv,
4409                                               iv_length);
4410 
4411 exit:
4412     if (status == PSA_SUCCESS) {
4413         operation->iv_set = 1;
4414     } else {
4415         psa_cipher_abort(operation);
4416     }
4417 
4418     LOCAL_INPUT_FREE(iv_external, iv);
4419 
4420     return status;
4421 }
4422 
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)4423 psa_status_t psa_cipher_update(psa_cipher_operation_t *operation,
4424                                const uint8_t *input_external,
4425                                size_t input_length,
4426                                uint8_t *output_external,
4427                                size_t output_size,
4428                                size_t *output_length)
4429 {
4430     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4431 
4432     LOCAL_INPUT_DECLARE(input_external, input);
4433     LOCAL_OUTPUT_DECLARE(output_external, output);
4434 
4435     if (operation->id == 0) {
4436         status = PSA_ERROR_BAD_STATE;
4437         goto exit;
4438     }
4439 
4440     if (operation->iv_required && !operation->iv_set) {
4441         status = PSA_ERROR_BAD_STATE;
4442         goto exit;
4443     }
4444 
4445     LOCAL_INPUT_ALLOC(input_external, input_length, input);
4446     LOCAL_OUTPUT_ALLOC(output_external, output_size, output);
4447 
4448     status = psa_driver_wrapper_cipher_update(operation,
4449                                               input,
4450                                               input_length,
4451                                               output,
4452                                               output_size,
4453                                               output_length);
4454 
4455 exit:
4456     if (status != PSA_SUCCESS) {
4457         psa_cipher_abort(operation);
4458     }
4459 
4460     LOCAL_INPUT_FREE(input_external, input);
4461     LOCAL_OUTPUT_FREE(output_external, output);
4462 
4463     return status;
4464 }
4465 
psa_cipher_finish(psa_cipher_operation_t * operation,uint8_t * output_external,size_t output_size,size_t * output_length)4466 psa_status_t psa_cipher_finish(psa_cipher_operation_t *operation,
4467                                uint8_t *output_external,
4468                                size_t output_size,
4469                                size_t *output_length)
4470 {
4471     psa_status_t status = PSA_ERROR_GENERIC_ERROR;
4472 
4473     LOCAL_OUTPUT_DECLARE(output_external, output);
4474 
4475     if (operation->id == 0) {
4476         status = PSA_ERROR_BAD_STATE;
4477         goto exit;
4478     }
4479 
4480     if (operation->iv_required && !operation->iv_set) {
4481         status = PSA_ERROR_BAD_STATE;
4482         goto exit;
4483     }
4484 
4485     LOCAL_OUTPUT_ALLOC(output_external, output_size, output);
4486 
4487     status = psa_driver_wrapper_cipher_finish(operation,
4488                                               output,
4489                                               output_size,
4490                                               output_length);
4491 
4492 exit:
4493     if (status == PSA_SUCCESS) {
4494         status = psa_cipher_abort(operation);
4495     } else {
4496         *output_length = 0;
4497         (void) psa_cipher_abort(operation);
4498     }
4499 
4500     LOCAL_OUTPUT_FREE(output_external, output);
4501 
4502     return status;
4503 }
4504 
psa_cipher_abort(psa_cipher_operation_t * operation)4505 psa_status_t psa_cipher_abort(psa_cipher_operation_t *operation)
4506 {
4507     if (operation->id == 0) {
4508         /* The object has (apparently) been initialized but it is not (yet)
4509          * in use. It's ok to call abort on such an object, and there's
4510          * nothing to do. */
4511         return PSA_SUCCESS;
4512     }
4513 
4514     psa_driver_wrapper_cipher_abort(operation);
4515 
4516     operation->id = 0;
4517     operation->iv_set = 0;
4518     operation->iv_required = 0;
4519 
4520     return PSA_SUCCESS;
4521 }
4522 
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)4523 psa_status_t psa_cipher_encrypt(mbedtls_svc_key_id_t key,
4524                                 psa_algorithm_t alg,
4525                                 const uint8_t *input_external,
4526                                 size_t input_length,
4527                                 uint8_t *output_external,
4528                                 size_t output_size,
4529                                 size_t *output_length)
4530 {
4531     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4532     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
4533     psa_key_slot_t *slot = NULL;
4534     uint8_t local_iv[PSA_CIPHER_IV_MAX_SIZE];
4535     size_t default_iv_length = 0;
4536 
4537     LOCAL_INPUT_DECLARE(input_external, input);
4538     LOCAL_OUTPUT_DECLARE(output_external, output);
4539 
4540     if (!PSA_ALG_IS_CIPHER(alg)) {
4541         status = PSA_ERROR_INVALID_ARGUMENT;
4542         goto exit;
4543     }
4544 
4545     status = psa_get_and_lock_key_slot_with_policy(key, &slot,
4546                                                    PSA_KEY_USAGE_ENCRYPT,
4547                                                    alg);
4548     if (status != PSA_SUCCESS) {
4549         goto exit;
4550     }
4551 
4552     default_iv_length = PSA_CIPHER_IV_LENGTH(slot->attr.type, alg);
4553     if (default_iv_length > PSA_CIPHER_IV_MAX_SIZE) {
4554         status = PSA_ERROR_GENERIC_ERROR;
4555         goto exit;
4556     }
4557 
4558     if (default_iv_length > 0) {
4559         if (output_size < default_iv_length) {
4560             status = PSA_ERROR_BUFFER_TOO_SMALL;
4561             goto exit;
4562         }
4563 
4564         status = psa_generate_random_internal(local_iv, default_iv_length);
4565         if (status != PSA_SUCCESS) {
4566             goto exit;
4567         }
4568     }
4569 
4570     LOCAL_INPUT_ALLOC(input_external, input_length, input);
4571     LOCAL_OUTPUT_ALLOC(output_external, output_size, output);
4572 
4573     status = psa_driver_wrapper_cipher_encrypt(
4574         &slot->attr, slot->key.data, slot->key.bytes,
4575         alg, local_iv, default_iv_length, input, input_length,
4576         psa_crypto_buffer_offset(output, default_iv_length),
4577         output_size - default_iv_length, output_length);
4578 
4579 exit:
4580     unlock_status = psa_unregister_read_under_mutex(slot);
4581     if (status == PSA_SUCCESS) {
4582         status = unlock_status;
4583     }
4584 
4585     if (status == PSA_SUCCESS) {
4586         if (default_iv_length > 0) {
4587             memcpy(output, local_iv, default_iv_length);
4588         }
4589         *output_length += default_iv_length;
4590     } else {
4591         *output_length = 0;
4592     }
4593 
4594     LOCAL_INPUT_FREE(input_external, input);
4595     LOCAL_OUTPUT_FREE(output_external, output);
4596 
4597     return status;
4598 }
4599 
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)4600 psa_status_t psa_cipher_decrypt(mbedtls_svc_key_id_t key,
4601                                 psa_algorithm_t alg,
4602                                 const uint8_t *input_external,
4603                                 size_t input_length,
4604                                 uint8_t *output_external,
4605                                 size_t output_size,
4606                                 size_t *output_length)
4607 {
4608     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4609     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
4610     psa_key_slot_t *slot = NULL;
4611 
4612     LOCAL_INPUT_DECLARE(input_external, input);
4613     LOCAL_OUTPUT_DECLARE(output_external, output);
4614 
4615     if (!PSA_ALG_IS_CIPHER(alg)) {
4616         status = PSA_ERROR_INVALID_ARGUMENT;
4617         goto exit;
4618     }
4619 
4620     status = psa_get_and_lock_key_slot_with_policy(key, &slot,
4621                                                    PSA_KEY_USAGE_DECRYPT,
4622                                                    alg);
4623     if (status != PSA_SUCCESS) {
4624         goto exit;
4625     }
4626 
4627     if (alg == PSA_ALG_CCM_STAR_NO_TAG &&
4628         input_length < PSA_BLOCK_CIPHER_BLOCK_LENGTH(slot->attr.type)) {
4629         status = PSA_ERROR_INVALID_ARGUMENT;
4630         goto exit;
4631     } else if (input_length < PSA_CIPHER_IV_LENGTH(slot->attr.type, alg)) {
4632         status = PSA_ERROR_INVALID_ARGUMENT;
4633         goto exit;
4634     }
4635 
4636     LOCAL_INPUT_ALLOC(input_external, input_length, input);
4637     LOCAL_OUTPUT_ALLOC(output_external, output_size, output);
4638 
4639     status = psa_driver_wrapper_cipher_decrypt(
4640         &slot->attr, slot->key.data, slot->key.bytes,
4641         alg, input, input_length,
4642         output, output_size, output_length);
4643 
4644 exit:
4645     unlock_status = psa_unregister_read_under_mutex(slot);
4646     if (status == PSA_SUCCESS) {
4647         status = unlock_status;
4648     }
4649 
4650     if (status != PSA_SUCCESS) {
4651         *output_length = 0;
4652     }
4653 
4654     LOCAL_INPUT_FREE(input_external, input);
4655     LOCAL_OUTPUT_FREE(output_external, output);
4656 
4657     return status;
4658 }
4659 
4660 
4661 /****************************************************************/
4662 /* AEAD */
4663 /****************************************************************/
4664 
4665 /* Helper function to get the base algorithm from its variants. */
psa_aead_get_base_algorithm(psa_algorithm_t alg)4666 static psa_algorithm_t psa_aead_get_base_algorithm(psa_algorithm_t alg)
4667 {
4668     return PSA_ALG_AEAD_WITH_DEFAULT_LENGTH_TAG(alg);
4669 }
4670 
4671 /* Helper function to perform common nonce length checks. */
psa_aead_check_nonce_length(psa_algorithm_t alg,size_t nonce_length)4672 static psa_status_t psa_aead_check_nonce_length(psa_algorithm_t alg,
4673                                                 size_t nonce_length)
4674 {
4675     psa_algorithm_t base_alg = psa_aead_get_base_algorithm(alg);
4676 
4677     switch (base_alg) {
4678 #if defined(PSA_WANT_ALG_GCM)
4679         case PSA_ALG_GCM:
4680             /* Not checking max nonce size here as GCM spec allows almost
4681              * arbitrarily large nonces. Please note that we do not generally
4682              * recommend the usage of nonces of greater length than
4683              * PSA_AEAD_NONCE_MAX_SIZE, as large nonces are hashed to a shorter
4684              * size, which can then lead to collisions if you encrypt a very
4685              * large number of messages.*/
4686             if (nonce_length != 0) {
4687                 return PSA_SUCCESS;
4688             }
4689             break;
4690 #endif /* PSA_WANT_ALG_GCM */
4691 #if defined(PSA_WANT_ALG_CCM)
4692         case PSA_ALG_CCM:
4693             if (nonce_length >= 7 && nonce_length <= 13) {
4694                 return PSA_SUCCESS;
4695             }
4696             break;
4697 #endif /* PSA_WANT_ALG_CCM */
4698 #if defined(PSA_WANT_ALG_CHACHA20_POLY1305)
4699         case PSA_ALG_CHACHA20_POLY1305:
4700             if (nonce_length == 12) {
4701                 return PSA_SUCCESS;
4702             } else if (nonce_length == 8) {
4703                 return PSA_ERROR_NOT_SUPPORTED;
4704             }
4705             break;
4706 #endif /* PSA_WANT_ALG_CHACHA20_POLY1305 */
4707         default:
4708             (void) nonce_length;
4709             return PSA_ERROR_NOT_SUPPORTED;
4710     }
4711 
4712     return PSA_ERROR_INVALID_ARGUMENT;
4713 }
4714 
psa_aead_check_algorithm(psa_algorithm_t alg)4715 static psa_status_t psa_aead_check_algorithm(psa_algorithm_t alg)
4716 {
4717     if (!PSA_ALG_IS_AEAD(alg) || PSA_ALG_IS_WILDCARD(alg)) {
4718         return PSA_ERROR_INVALID_ARGUMENT;
4719     }
4720 
4721     return PSA_SUCCESS;
4722 }
4723 
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)4724 psa_status_t psa_aead_encrypt(mbedtls_svc_key_id_t key,
4725                               psa_algorithm_t alg,
4726                               const uint8_t *nonce_external,
4727                               size_t nonce_length,
4728                               const uint8_t *additional_data_external,
4729                               size_t additional_data_length,
4730                               const uint8_t *plaintext_external,
4731                               size_t plaintext_length,
4732                               uint8_t *ciphertext_external,
4733                               size_t ciphertext_size,
4734                               size_t *ciphertext_length)
4735 {
4736     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4737     psa_key_slot_t *slot;
4738 
4739     LOCAL_INPUT_DECLARE(nonce_external, nonce);
4740     LOCAL_INPUT_DECLARE(additional_data_external, additional_data);
4741     LOCAL_INPUT_DECLARE(plaintext_external, plaintext);
4742     LOCAL_OUTPUT_DECLARE(ciphertext_external, ciphertext);
4743 
4744     *ciphertext_length = 0;
4745 
4746     status = psa_aead_check_algorithm(alg);
4747     if (status != PSA_SUCCESS) {
4748         return status;
4749     }
4750 
4751     status = psa_get_and_lock_key_slot_with_policy(
4752         key, &slot, PSA_KEY_USAGE_ENCRYPT, alg);
4753     if (status != PSA_SUCCESS) {
4754         return status;
4755     }
4756 
4757     LOCAL_INPUT_ALLOC(nonce_external, nonce_length, nonce);
4758     LOCAL_INPUT_ALLOC(additional_data_external, additional_data_length, additional_data);
4759     LOCAL_INPUT_ALLOC(plaintext_external, plaintext_length, plaintext);
4760     LOCAL_OUTPUT_ALLOC(ciphertext_external, ciphertext_size, ciphertext);
4761 
4762     status = psa_aead_check_nonce_length(alg, nonce_length);
4763     if (status != PSA_SUCCESS) {
4764         goto exit;
4765     }
4766 
4767     status = psa_driver_wrapper_aead_encrypt(
4768         &slot->attr, slot->key.data, slot->key.bytes,
4769         alg,
4770         nonce, nonce_length,
4771         additional_data, additional_data_length,
4772         plaintext, plaintext_length,
4773         ciphertext, ciphertext_size, ciphertext_length);
4774 
4775     if (status != PSA_SUCCESS && ciphertext_size != 0) {
4776         memset(ciphertext, 0, ciphertext_size);
4777     }
4778 
4779 exit:
4780     LOCAL_INPUT_FREE(nonce_external, nonce);
4781     LOCAL_INPUT_FREE(additional_data_external, additional_data);
4782     LOCAL_INPUT_FREE(plaintext_external, plaintext);
4783     LOCAL_OUTPUT_FREE(ciphertext_external, ciphertext);
4784 
4785     psa_unregister_read_under_mutex(slot);
4786 
4787     return status;
4788 }
4789 
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)4790 psa_status_t psa_aead_decrypt(mbedtls_svc_key_id_t key,
4791                               psa_algorithm_t alg,
4792                               const uint8_t *nonce_external,
4793                               size_t nonce_length,
4794                               const uint8_t *additional_data_external,
4795                               size_t additional_data_length,
4796                               const uint8_t *ciphertext_external,
4797                               size_t ciphertext_length,
4798                               uint8_t *plaintext_external,
4799                               size_t plaintext_size,
4800                               size_t *plaintext_length)
4801 {
4802     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4803     psa_key_slot_t *slot;
4804 
4805     LOCAL_INPUT_DECLARE(nonce_external, nonce);
4806     LOCAL_INPUT_DECLARE(additional_data_external, additional_data);
4807     LOCAL_INPUT_DECLARE(ciphertext_external, ciphertext);
4808     LOCAL_OUTPUT_DECLARE(plaintext_external, plaintext);
4809 
4810     *plaintext_length = 0;
4811 
4812     status = psa_aead_check_algorithm(alg);
4813     if (status != PSA_SUCCESS) {
4814         return status;
4815     }
4816 
4817     status = psa_get_and_lock_key_slot_with_policy(
4818         key, &slot, PSA_KEY_USAGE_DECRYPT, alg);
4819     if (status != PSA_SUCCESS) {
4820         return status;
4821     }
4822 
4823     LOCAL_INPUT_ALLOC(nonce_external, nonce_length, nonce);
4824     LOCAL_INPUT_ALLOC(additional_data_external, additional_data_length,
4825                       additional_data);
4826     LOCAL_INPUT_ALLOC(ciphertext_external, ciphertext_length, ciphertext);
4827     LOCAL_OUTPUT_ALLOC(plaintext_external, plaintext_size, plaintext);
4828 
4829     status = psa_aead_check_nonce_length(alg, nonce_length);
4830     if (status != PSA_SUCCESS) {
4831         goto exit;
4832     }
4833 
4834     status = psa_driver_wrapper_aead_decrypt(
4835         &slot->attr, slot->key.data, slot->key.bytes,
4836         alg,
4837         nonce, nonce_length,
4838         additional_data, additional_data_length,
4839         ciphertext, ciphertext_length,
4840         plaintext, plaintext_size, plaintext_length);
4841 
4842     if (status != PSA_SUCCESS && plaintext_size != 0) {
4843         memset(plaintext, 0, plaintext_size);
4844     }
4845 
4846 exit:
4847     LOCAL_INPUT_FREE(nonce_external, nonce);
4848     LOCAL_INPUT_FREE(additional_data_external, additional_data);
4849     LOCAL_INPUT_FREE(ciphertext_external, ciphertext);
4850     LOCAL_OUTPUT_FREE(plaintext_external, plaintext);
4851 
4852     psa_unregister_read_under_mutex(slot);
4853 
4854     return status;
4855 }
4856 
psa_validate_tag_length(psa_algorithm_t alg)4857 static psa_status_t psa_validate_tag_length(psa_algorithm_t alg)
4858 {
4859     const uint8_t tag_len = PSA_ALG_AEAD_GET_TAG_LENGTH(alg);
4860 
4861     switch (PSA_ALG_AEAD_WITH_SHORTENED_TAG(alg, 0)) {
4862 #if defined(PSA_WANT_ALG_CCM)
4863         case PSA_ALG_AEAD_WITH_SHORTENED_TAG(PSA_ALG_CCM, 0):
4864             /* CCM allows the following tag lengths: 4, 6, 8, 10, 12, 14, 16.*/
4865             if (tag_len < 4 || tag_len > 16 || tag_len % 2) {
4866                 return PSA_ERROR_INVALID_ARGUMENT;
4867             }
4868             break;
4869 #endif /* PSA_WANT_ALG_CCM */
4870 
4871 #if defined(PSA_WANT_ALG_GCM)
4872         case PSA_ALG_AEAD_WITH_SHORTENED_TAG(PSA_ALG_GCM, 0):
4873             /* GCM allows the following tag lengths: 4, 8, 12, 13, 14, 15, 16. */
4874             if (tag_len != 4 && tag_len != 8 && (tag_len < 12 || tag_len > 16)) {
4875                 return PSA_ERROR_INVALID_ARGUMENT;
4876             }
4877             break;
4878 #endif /* PSA_WANT_ALG_GCM */
4879 
4880 #if defined(PSA_WANT_ALG_CHACHA20_POLY1305)
4881         case PSA_ALG_AEAD_WITH_SHORTENED_TAG(PSA_ALG_CHACHA20_POLY1305, 0):
4882             /* We only support the default tag length. */
4883             if (tag_len != 16) {
4884                 return PSA_ERROR_INVALID_ARGUMENT;
4885             }
4886             break;
4887 #endif /* PSA_WANT_ALG_CHACHA20_POLY1305 */
4888 
4889         default:
4890             (void) tag_len;
4891             return PSA_ERROR_NOT_SUPPORTED;
4892     }
4893     return PSA_SUCCESS;
4894 }
4895 
4896 /* 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)4897 static psa_status_t psa_aead_setup(psa_aead_operation_t *operation,
4898                                    int is_encrypt,
4899                                    mbedtls_svc_key_id_t key,
4900                                    psa_algorithm_t alg)
4901 {
4902     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4903     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
4904     psa_key_slot_t *slot = NULL;
4905     psa_key_usage_t key_usage = 0;
4906 
4907     status = psa_aead_check_algorithm(alg);
4908     if (status != PSA_SUCCESS) {
4909         goto exit;
4910     }
4911 
4912     if (operation->id != 0) {
4913         status = PSA_ERROR_BAD_STATE;
4914         goto exit;
4915     }
4916 
4917     if (operation->nonce_set || operation->lengths_set ||
4918         operation->ad_started || operation->body_started) {
4919         status = PSA_ERROR_BAD_STATE;
4920         goto exit;
4921     }
4922 
4923     if (is_encrypt) {
4924         key_usage = PSA_KEY_USAGE_ENCRYPT;
4925     } else {
4926         key_usage = PSA_KEY_USAGE_DECRYPT;
4927     }
4928 
4929     status = psa_get_and_lock_key_slot_with_policy(key, &slot, key_usage,
4930                                                    alg);
4931     if (status != PSA_SUCCESS) {
4932         goto exit;
4933     }
4934 
4935     if ((status = psa_validate_tag_length(alg)) != PSA_SUCCESS) {
4936         goto exit;
4937     }
4938 
4939     if (is_encrypt) {
4940         status = psa_driver_wrapper_aead_encrypt_setup(operation,
4941                                                        &slot->attr,
4942                                                        slot->key.data,
4943                                                        slot->key.bytes,
4944                                                        alg);
4945     } else {
4946         status = psa_driver_wrapper_aead_decrypt_setup(operation,
4947                                                        &slot->attr,
4948                                                        slot->key.data,
4949                                                        slot->key.bytes,
4950                                                        alg);
4951     }
4952     if (status != PSA_SUCCESS) {
4953         goto exit;
4954     }
4955 
4956     operation->key_type = psa_get_key_type(&slot->attr);
4957 
4958 exit:
4959     unlock_status = psa_unregister_read_under_mutex(slot);
4960 
4961     if (status == PSA_SUCCESS) {
4962         status = unlock_status;
4963         operation->alg = psa_aead_get_base_algorithm(alg);
4964         operation->is_encrypt = is_encrypt;
4965     } else {
4966         psa_aead_abort(operation);
4967     }
4968 
4969     return status;
4970 }
4971 
4972 /* 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)4973 psa_status_t psa_aead_encrypt_setup(psa_aead_operation_t *operation,
4974                                     mbedtls_svc_key_id_t key,
4975                                     psa_algorithm_t alg)
4976 {
4977     return psa_aead_setup(operation, 1, key, alg);
4978 }
4979 
4980 /* 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)4981 psa_status_t psa_aead_decrypt_setup(psa_aead_operation_t *operation,
4982                                     mbedtls_svc_key_id_t key,
4983                                     psa_algorithm_t alg)
4984 {
4985     return psa_aead_setup(operation, 0, key, alg);
4986 }
4987 
psa_aead_set_nonce_internal(psa_aead_operation_t * operation,const uint8_t * nonce,size_t nonce_length)4988 static psa_status_t psa_aead_set_nonce_internal(psa_aead_operation_t *operation,
4989                                                 const uint8_t *nonce,
4990                                                 size_t nonce_length)
4991 {
4992     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4993 
4994     if (operation->id == 0) {
4995         status = PSA_ERROR_BAD_STATE;
4996         goto exit;
4997     }
4998 
4999     if (operation->nonce_set) {
5000         status = PSA_ERROR_BAD_STATE;
5001         goto exit;
5002     }
5003 
5004     status = psa_aead_check_nonce_length(operation->alg, nonce_length);
5005     if (status != PSA_SUCCESS) {
5006         status = PSA_ERROR_INVALID_ARGUMENT;
5007         goto exit;
5008     }
5009 
5010     status = psa_driver_wrapper_aead_set_nonce(operation, nonce,
5011                                                nonce_length);
5012 
5013 exit:
5014     if (status == PSA_SUCCESS) {
5015         operation->nonce_set = 1;
5016     } else {
5017         psa_aead_abort(operation);
5018     }
5019 
5020     return status;
5021 }
5022 
5023 /* 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)5024 psa_status_t psa_aead_generate_nonce(psa_aead_operation_t *operation,
5025                                      uint8_t *nonce_external,
5026                                      size_t nonce_size,
5027                                      size_t *nonce_length)
5028 {
5029     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
5030     uint8_t local_nonce[PSA_AEAD_NONCE_MAX_SIZE];
5031     size_t required_nonce_size = 0;
5032 
5033     LOCAL_OUTPUT_DECLARE(nonce_external, nonce);
5034     LOCAL_OUTPUT_ALLOC(nonce_external, nonce_size, nonce);
5035 
5036     *nonce_length = 0;
5037 
5038     if (operation->id == 0) {
5039         status = PSA_ERROR_BAD_STATE;
5040         goto exit;
5041     }
5042 
5043     if (operation->nonce_set || !operation->is_encrypt) {
5044         status = PSA_ERROR_BAD_STATE;
5045         goto exit;
5046     }
5047 
5048     /* For CCM, this size may not be correct according to the PSA
5049      * specification. The PSA Crypto 1.0.1 specification states:
5050      *
5051      * CCM encodes the plaintext length pLen in L octets, with L the smallest
5052      * integer >= 2 where pLen < 2^(8L). The nonce length is then 15 - L bytes.
5053      *
5054      * However this restriction that L has to be the smallest integer is not
5055      * applied in practice, and it is not implementable here since the
5056      * plaintext length may or may not be known at this time. */
5057     required_nonce_size = PSA_AEAD_NONCE_LENGTH(operation->key_type,
5058                                                 operation->alg);
5059     if (nonce_size < required_nonce_size) {
5060         status = PSA_ERROR_BUFFER_TOO_SMALL;
5061         goto exit;
5062     }
5063 
5064     status = psa_generate_random_internal(local_nonce, required_nonce_size);
5065     if (status != PSA_SUCCESS) {
5066         goto exit;
5067     }
5068 
5069     status = psa_aead_set_nonce_internal(operation, local_nonce,
5070                                          required_nonce_size);
5071 
5072 exit:
5073     if (status == PSA_SUCCESS) {
5074         memcpy(nonce, local_nonce, required_nonce_size);
5075         *nonce_length = required_nonce_size;
5076     } else {
5077         psa_aead_abort(operation);
5078     }
5079 
5080     LOCAL_OUTPUT_FREE(nonce_external, nonce);
5081 
5082     return status;
5083 }
5084 
5085 /* Set the nonce for a multipart authenticated encryption or decryption
5086    operation.*/
psa_aead_set_nonce(psa_aead_operation_t * operation,const uint8_t * nonce_external,size_t nonce_length)5087 psa_status_t psa_aead_set_nonce(psa_aead_operation_t *operation,
5088                                 const uint8_t *nonce_external,
5089                                 size_t nonce_length)
5090 {
5091     psa_status_t status;
5092 
5093     LOCAL_INPUT_DECLARE(nonce_external, nonce);
5094     LOCAL_INPUT_ALLOC(nonce_external, nonce_length, nonce);
5095 
5096     status = psa_aead_set_nonce_internal(operation, nonce, nonce_length);
5097 
5098 /* Exit label is only needed for buffer copying, prevent unused warnings. */
5099 #if !defined(MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS)
5100 exit:
5101 #endif
5102 
5103     LOCAL_INPUT_FREE(nonce_external, nonce);
5104 
5105     return status;
5106 }
5107 
5108 /* 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)5109 psa_status_t psa_aead_set_lengths(psa_aead_operation_t *operation,
5110                                   size_t ad_length,
5111                                   size_t plaintext_length)
5112 {
5113     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
5114 
5115     if (operation->id == 0) {
5116         status = PSA_ERROR_BAD_STATE;
5117         goto exit;
5118     }
5119 
5120     if (operation->lengths_set || operation->ad_started ||
5121         operation->body_started) {
5122         status = PSA_ERROR_BAD_STATE;
5123         goto exit;
5124     }
5125 
5126     switch (operation->alg) {
5127 #if defined(PSA_WANT_ALG_GCM)
5128         case PSA_ALG_GCM:
5129             /* Lengths can only be too large for GCM if size_t is bigger than 32
5130              * bits. Without the guard this code will generate warnings on 32bit
5131              * builds. */
5132 #if SIZE_MAX > UINT32_MAX
5133             if (((uint64_t) ad_length) >> 61 != 0 ||
5134                 ((uint64_t) plaintext_length) > 0xFFFFFFFE0ull) {
5135                 status = PSA_ERROR_INVALID_ARGUMENT;
5136                 goto exit;
5137             }
5138 #endif
5139             break;
5140 #endif /* PSA_WANT_ALG_GCM */
5141 #if defined(PSA_WANT_ALG_CCM)
5142         case PSA_ALG_CCM:
5143             if (ad_length > 0xFF00) {
5144                 status = PSA_ERROR_INVALID_ARGUMENT;
5145                 goto exit;
5146             }
5147             break;
5148 #endif /* PSA_WANT_ALG_CCM */
5149 #if defined(PSA_WANT_ALG_CHACHA20_POLY1305)
5150         case PSA_ALG_CHACHA20_POLY1305:
5151             /* No length restrictions for ChaChaPoly. */
5152             break;
5153 #endif /* PSA_WANT_ALG_CHACHA20_POLY1305 */
5154         default:
5155             break;
5156     }
5157 
5158     status = psa_driver_wrapper_aead_set_lengths(operation, ad_length,
5159                                                  plaintext_length);
5160 
5161 exit:
5162     if (status == PSA_SUCCESS) {
5163         operation->ad_remaining = ad_length;
5164         operation->body_remaining = plaintext_length;
5165         operation->lengths_set = 1;
5166     } else {
5167         psa_aead_abort(operation);
5168     }
5169 
5170     return status;
5171 }
5172 
5173 /* 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)5174 psa_status_t psa_aead_update_ad(psa_aead_operation_t *operation,
5175                                 const uint8_t *input_external,
5176                                 size_t input_length)
5177 {
5178     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
5179 
5180     LOCAL_INPUT_DECLARE(input_external, input);
5181     LOCAL_INPUT_ALLOC(input_external, input_length, input);
5182 
5183     if (operation->id == 0) {
5184         status = PSA_ERROR_BAD_STATE;
5185         goto exit;
5186     }
5187 
5188     if (!operation->nonce_set || operation->body_started) {
5189         status = PSA_ERROR_BAD_STATE;
5190         goto exit;
5191     }
5192 
5193     if (operation->lengths_set) {
5194         if (operation->ad_remaining < input_length) {
5195             status = PSA_ERROR_INVALID_ARGUMENT;
5196             goto exit;
5197         }
5198 
5199         operation->ad_remaining -= input_length;
5200     }
5201 #if defined(PSA_WANT_ALG_CCM)
5202     else if (operation->alg == PSA_ALG_CCM) {
5203         status = PSA_ERROR_BAD_STATE;
5204         goto exit;
5205     }
5206 #endif /* PSA_WANT_ALG_CCM */
5207 
5208     status = psa_driver_wrapper_aead_update_ad(operation, input,
5209                                                input_length);
5210 
5211 exit:
5212     if (status == PSA_SUCCESS) {
5213         operation->ad_started = 1;
5214     } else {
5215         psa_aead_abort(operation);
5216     }
5217 
5218     LOCAL_INPUT_FREE(input_external, input);
5219 
5220     return status;
5221 }
5222 
5223 /* Encrypt or decrypt a message fragment in an active multipart AEAD
5224    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)5225 psa_status_t psa_aead_update(psa_aead_operation_t *operation,
5226                              const uint8_t *input_external,
5227                              size_t input_length,
5228                              uint8_t *output_external,
5229                              size_t output_size,
5230                              size_t *output_length)
5231 {
5232     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
5233 
5234 
5235     LOCAL_INPUT_DECLARE(input_external, input);
5236     LOCAL_OUTPUT_DECLARE(output_external, output);
5237 
5238     LOCAL_INPUT_ALLOC(input_external, input_length, input);
5239     LOCAL_OUTPUT_ALLOC(output_external, output_size, output);
5240 
5241     *output_length = 0;
5242 
5243     if (operation->id == 0) {
5244         status = PSA_ERROR_BAD_STATE;
5245         goto exit;
5246     }
5247 
5248     if (!operation->nonce_set) {
5249         status = PSA_ERROR_BAD_STATE;
5250         goto exit;
5251     }
5252 
5253     if (operation->lengths_set) {
5254         /* Additional data length was supplied, but not all the additional
5255            data was supplied.*/
5256         if (operation->ad_remaining != 0) {
5257             status = PSA_ERROR_INVALID_ARGUMENT;
5258             goto exit;
5259         }
5260 
5261         /* Too much data provided. */
5262         if (operation->body_remaining < input_length) {
5263             status = PSA_ERROR_INVALID_ARGUMENT;
5264             goto exit;
5265         }
5266 
5267         operation->body_remaining -= input_length;
5268     }
5269 #if defined(PSA_WANT_ALG_CCM)
5270     else if (operation->alg == PSA_ALG_CCM) {
5271         status = PSA_ERROR_BAD_STATE;
5272         goto exit;
5273     }
5274 #endif /* PSA_WANT_ALG_CCM */
5275 
5276     status = psa_driver_wrapper_aead_update(operation, input, input_length,
5277                                             output, output_size,
5278                                             output_length);
5279 
5280 exit:
5281     if (status == PSA_SUCCESS) {
5282         operation->body_started = 1;
5283     } else {
5284         psa_aead_abort(operation);
5285     }
5286 
5287     LOCAL_INPUT_FREE(input_external, input);
5288     LOCAL_OUTPUT_FREE(output_external, output);
5289 
5290     return status;
5291 }
5292 
psa_aead_final_checks(const psa_aead_operation_t * operation)5293 static psa_status_t psa_aead_final_checks(const psa_aead_operation_t *operation)
5294 {
5295     if (operation->id == 0 || !operation->nonce_set) {
5296         return PSA_ERROR_BAD_STATE;
5297     }
5298 
5299     if (operation->lengths_set && (operation->ad_remaining != 0 ||
5300                                    operation->body_remaining != 0)) {
5301         return PSA_ERROR_INVALID_ARGUMENT;
5302     }
5303 
5304     return PSA_SUCCESS;
5305 }
5306 
5307 /* 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)5308 psa_status_t psa_aead_finish(psa_aead_operation_t *operation,
5309                              uint8_t *ciphertext_external,
5310                              size_t ciphertext_size,
5311                              size_t *ciphertext_length,
5312                              uint8_t *tag_external,
5313                              size_t tag_size,
5314                              size_t *tag_length)
5315 {
5316     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
5317 
5318     LOCAL_OUTPUT_DECLARE(ciphertext_external, ciphertext);
5319     LOCAL_OUTPUT_DECLARE(tag_external, tag);
5320 
5321     LOCAL_OUTPUT_ALLOC(ciphertext_external, ciphertext_size, ciphertext);
5322     LOCAL_OUTPUT_ALLOC(tag_external, tag_size, tag);
5323 
5324     *ciphertext_length = 0;
5325     *tag_length = tag_size;
5326 
5327     status = psa_aead_final_checks(operation);
5328     if (status != PSA_SUCCESS) {
5329         goto exit;
5330     }
5331 
5332     if (!operation->is_encrypt) {
5333         status = PSA_ERROR_BAD_STATE;
5334         goto exit;
5335     }
5336 
5337     status = psa_driver_wrapper_aead_finish(operation, ciphertext,
5338                                             ciphertext_size,
5339                                             ciphertext_length,
5340                                             tag, tag_size, tag_length);
5341 
5342 exit:
5343 
5344 
5345     /* In case the operation fails and the user fails to check for failure or
5346      * the zero tag size, make sure the tag is set to something implausible.
5347      * Even if the operation succeeds, make sure we clear the rest of the
5348      * buffer to prevent potential leakage of anything previously placed in
5349      * the same buffer.*/
5350     psa_wipe_tag_output_buffer(tag, status, tag_size, *tag_length);
5351 
5352     psa_aead_abort(operation);
5353 
5354     LOCAL_OUTPUT_FREE(ciphertext_external, ciphertext);
5355     LOCAL_OUTPUT_FREE(tag_external, tag);
5356 
5357     return status;
5358 }
5359 
5360 /* Finish authenticating and decrypting a message in a multipart AEAD
5361    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)5362 psa_status_t psa_aead_verify(psa_aead_operation_t *operation,
5363                              uint8_t *plaintext_external,
5364                              size_t plaintext_size,
5365                              size_t *plaintext_length,
5366                              const uint8_t *tag_external,
5367                              size_t tag_length)
5368 {
5369     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
5370 
5371     LOCAL_OUTPUT_DECLARE(plaintext_external, plaintext);
5372     LOCAL_INPUT_DECLARE(tag_external, tag);
5373 
5374     LOCAL_OUTPUT_ALLOC(plaintext_external, plaintext_size, plaintext);
5375     LOCAL_INPUT_ALLOC(tag_external, tag_length, tag);
5376 
5377     *plaintext_length = 0;
5378 
5379     status = psa_aead_final_checks(operation);
5380     if (status != PSA_SUCCESS) {
5381         goto exit;
5382     }
5383 
5384     if (operation->is_encrypt) {
5385         status = PSA_ERROR_BAD_STATE;
5386         goto exit;
5387     }
5388 
5389     status = psa_driver_wrapper_aead_verify(operation, plaintext,
5390                                             plaintext_size,
5391                                             plaintext_length,
5392                                             tag, tag_length);
5393 
5394 exit:
5395     psa_aead_abort(operation);
5396 
5397     LOCAL_OUTPUT_FREE(plaintext_external, plaintext);
5398     LOCAL_INPUT_FREE(tag_external, tag);
5399 
5400     return status;
5401 }
5402 
5403 /* Abort an AEAD operation. */
psa_aead_abort(psa_aead_operation_t * operation)5404 psa_status_t psa_aead_abort(psa_aead_operation_t *operation)
5405 {
5406     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
5407 
5408     if (operation->id == 0) {
5409         /* The object has (apparently) been initialized but it is not (yet)
5410          * in use. It's ok to call abort on such an object, and there's
5411          * nothing to do. */
5412         return PSA_SUCCESS;
5413     }
5414 
5415     status = psa_driver_wrapper_aead_abort(operation);
5416 
5417     memset(operation, 0, sizeof(*operation));
5418 
5419     return status;
5420 }
5421 
5422 /****************************************************************/
5423 /* Generators */
5424 /****************************************************************/
5425 
5426 #if defined(BUILTIN_ALG_ANY_HKDF) || \
5427     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
5428     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS) || \
5429     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS) || \
5430     defined(PSA_HAVE_SOFT_PBKDF2)
5431 #define AT_LEAST_ONE_BUILTIN_KDF
5432 #endif /* At least one builtin KDF */
5433 
5434 #if defined(BUILTIN_ALG_ANY_HKDF) || \
5435     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
5436     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)5437 static psa_status_t psa_key_derivation_start_hmac(
5438     psa_mac_operation_t *operation,
5439     psa_algorithm_t hash_alg,
5440     const uint8_t *hmac_key,
5441     size_t hmac_key_length)
5442 {
5443     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
5444     psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
5445     psa_set_key_type(&attributes, PSA_KEY_TYPE_HMAC);
5446     psa_set_key_bits(&attributes, PSA_BYTES_TO_BITS(hmac_key_length));
5447     psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_HASH);
5448 
5449     operation->is_sign = 1;
5450     operation->mac_size = PSA_HASH_LENGTH(hash_alg);
5451 
5452     status = psa_driver_wrapper_mac_sign_setup(operation,
5453                                                &attributes,
5454                                                hmac_key, hmac_key_length,
5455                                                PSA_ALG_HMAC(hash_alg));
5456 
5457     psa_reset_key_attributes(&attributes);
5458     return status;
5459 }
5460 #endif /* KDF algorithms reliant on HMAC */
5461 
5462 #define HKDF_STATE_INIT 0 /* no input yet */
5463 #define HKDF_STATE_STARTED 1 /* got salt */
5464 #define HKDF_STATE_KEYED 2 /* got key */
5465 #define HKDF_STATE_OUTPUT 3 /* output started */
5466 
psa_key_derivation_get_kdf_alg(const psa_key_derivation_operation_t * operation)5467 static psa_algorithm_t psa_key_derivation_get_kdf_alg(
5468     const psa_key_derivation_operation_t *operation)
5469 {
5470     if (PSA_ALG_IS_KEY_AGREEMENT(operation->alg)) {
5471         return PSA_ALG_KEY_AGREEMENT_GET_KDF(operation->alg);
5472     } else {
5473         return operation->alg;
5474     }
5475 }
5476 
psa_key_derivation_abort(psa_key_derivation_operation_t * operation)5477 psa_status_t psa_key_derivation_abort(psa_key_derivation_operation_t *operation)
5478 {
5479     psa_status_t status = PSA_SUCCESS;
5480     psa_algorithm_t kdf_alg = psa_key_derivation_get_kdf_alg(operation);
5481     if (kdf_alg == 0) {
5482         /* The object has (apparently) been initialized but it is not
5483          * in use. It's ok to call abort on such an object, and there's
5484          * nothing to do. */
5485     } else
5486 #if defined(BUILTIN_ALG_ANY_HKDF)
5487     if (PSA_ALG_IS_ANY_HKDF(kdf_alg)) {
5488         mbedtls_free(operation->ctx.hkdf.info);
5489         status = psa_mac_abort(&operation->ctx.hkdf.hmac);
5490     } else
5491 #endif /* BUILTIN_ALG_ANY_HKDF */
5492 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
5493     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
5494     if (PSA_ALG_IS_TLS12_PRF(kdf_alg) ||
5495         /* TLS-1.2 PSK-to-MS KDF uses the same core as TLS-1.2 PRF */
5496         PSA_ALG_IS_TLS12_PSK_TO_MS(kdf_alg)) {
5497         if (operation->ctx.tls12_prf.secret != NULL) {
5498             mbedtls_zeroize_and_free(operation->ctx.tls12_prf.secret,
5499                                      operation->ctx.tls12_prf.secret_length);
5500         }
5501 
5502         if (operation->ctx.tls12_prf.seed != NULL) {
5503             mbedtls_zeroize_and_free(operation->ctx.tls12_prf.seed,
5504                                      operation->ctx.tls12_prf.seed_length);
5505         }
5506 
5507         if (operation->ctx.tls12_prf.label != NULL) {
5508             mbedtls_zeroize_and_free(operation->ctx.tls12_prf.label,
5509                                      operation->ctx.tls12_prf.label_length);
5510         }
5511 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
5512         if (operation->ctx.tls12_prf.other_secret != NULL) {
5513             mbedtls_zeroize_and_free(operation->ctx.tls12_prf.other_secret,
5514                                      operation->ctx.tls12_prf.other_secret_length);
5515         }
5516 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
5517         status = PSA_SUCCESS;
5518 
5519         /* We leave the fields Ai and output_block to be erased safely by the
5520          * mbedtls_platform_zeroize() in the end of this function. */
5521     } else
5522 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) ||
5523         * defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS) */
5524 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS)
5525     if (kdf_alg == PSA_ALG_TLS12_ECJPAKE_TO_PMS) {
5526         mbedtls_platform_zeroize(operation->ctx.tls12_ecjpake_to_pms.data,
5527                                  sizeof(operation->ctx.tls12_ecjpake_to_pms.data));
5528     } else
5529 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS) */
5530 #if defined(PSA_HAVE_SOFT_PBKDF2)
5531     if (PSA_ALG_IS_PBKDF2(kdf_alg)) {
5532         if (operation->ctx.pbkdf2.salt != NULL) {
5533             mbedtls_zeroize_and_free(operation->ctx.pbkdf2.salt,
5534                                      operation->ctx.pbkdf2.salt_length);
5535         }
5536 
5537         status = PSA_SUCCESS;
5538     } else
5539 #endif /* defined(PSA_HAVE_SOFT_PBKDF2) */
5540     {
5541         status = PSA_ERROR_BAD_STATE;
5542     }
5543     mbedtls_platform_zeroize(operation, sizeof(*operation));
5544     return status;
5545 }
5546 
psa_key_derivation_get_capacity(const psa_key_derivation_operation_t * operation,size_t * capacity)5547 psa_status_t psa_key_derivation_get_capacity(const psa_key_derivation_operation_t *operation,
5548                                              size_t *capacity)
5549 {
5550     if (operation->alg == 0) {
5551         /* This is a blank key derivation operation. */
5552         return PSA_ERROR_BAD_STATE;
5553     }
5554 
5555     *capacity = operation->capacity;
5556     return PSA_SUCCESS;
5557 }
5558 
psa_key_derivation_set_capacity(psa_key_derivation_operation_t * operation,size_t capacity)5559 psa_status_t psa_key_derivation_set_capacity(psa_key_derivation_operation_t *operation,
5560                                              size_t capacity)
5561 {
5562     if (operation->alg == 0) {
5563         return PSA_ERROR_BAD_STATE;
5564     }
5565     if (capacity > operation->capacity) {
5566         return PSA_ERROR_INVALID_ARGUMENT;
5567     }
5568     operation->capacity = capacity;
5569     return PSA_SUCCESS;
5570 }
5571 
5572 #if defined(BUILTIN_ALG_ANY_HKDF)
5573 /* 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)5574 static psa_status_t psa_key_derivation_hkdf_read(psa_hkdf_key_derivation_t *hkdf,
5575                                                  psa_algorithm_t kdf_alg,
5576                                                  uint8_t *output,
5577                                                  size_t output_length)
5578 {
5579     psa_algorithm_t hash_alg = PSA_ALG_HKDF_GET_HASH(kdf_alg);
5580     uint8_t hash_length = PSA_HASH_LENGTH(hash_alg);
5581     size_t hmac_output_length;
5582     psa_status_t status;
5583 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT)
5584     const uint8_t last_block = PSA_ALG_IS_HKDF_EXTRACT(kdf_alg) ? 0 : 0xff;
5585 #else
5586     const uint8_t last_block = 0xff;
5587 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT */
5588 
5589     if (hkdf->state < HKDF_STATE_KEYED ||
5590         (!hkdf->info_set
5591 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT)
5592          && !PSA_ALG_IS_HKDF_EXTRACT(kdf_alg)
5593 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT */
5594         )) {
5595         return PSA_ERROR_BAD_STATE;
5596     }
5597     hkdf->state = HKDF_STATE_OUTPUT;
5598 
5599     while (output_length != 0) {
5600         /* Copy what remains of the current block */
5601         uint8_t n = hash_length - hkdf->offset_in_block;
5602         if (n > output_length) {
5603             n = (uint8_t) output_length;
5604         }
5605         memcpy(output, hkdf->output_block + hkdf->offset_in_block, n);
5606         output += n;
5607         output_length -= n;
5608         hkdf->offset_in_block += n;
5609         if (output_length == 0) {
5610             break;
5611         }
5612         /* We can't be wanting more output after the last block, otherwise
5613          * the capacity check in psa_key_derivation_output_bytes() would have
5614          * prevented this call. It could happen only if the operation
5615          * object was corrupted or if this function is called directly
5616          * inside the library. */
5617         if (hkdf->block_number == last_block) {
5618             return PSA_ERROR_BAD_STATE;
5619         }
5620 
5621         /* We need a new block */
5622         ++hkdf->block_number;
5623         hkdf->offset_in_block = 0;
5624 
5625         status = psa_key_derivation_start_hmac(&hkdf->hmac,
5626                                                hash_alg,
5627                                                hkdf->prk,
5628                                                hash_length);
5629         if (status != PSA_SUCCESS) {
5630             return status;
5631         }
5632 
5633         if (hkdf->block_number != 1) {
5634             status = psa_mac_update(&hkdf->hmac,
5635                                     hkdf->output_block,
5636                                     hash_length);
5637             if (status != PSA_SUCCESS) {
5638                 return status;
5639             }
5640         }
5641         status = psa_mac_update(&hkdf->hmac,
5642                                 hkdf->info,
5643                                 hkdf->info_length);
5644         if (status != PSA_SUCCESS) {
5645             return status;
5646         }
5647         status = psa_mac_update(&hkdf->hmac,
5648                                 &hkdf->block_number, 1);
5649         if (status != PSA_SUCCESS) {
5650             return status;
5651         }
5652         status = psa_mac_sign_finish(&hkdf->hmac,
5653                                      hkdf->output_block,
5654                                      sizeof(hkdf->output_block),
5655                                      &hmac_output_length);
5656         if (status != PSA_SUCCESS) {
5657             return status;
5658         }
5659     }
5660 
5661     return PSA_SUCCESS;
5662 }
5663 #endif /* BUILTIN_ALG_ANY_HKDF */
5664 
5665 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
5666     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)5667 static psa_status_t psa_key_derivation_tls12_prf_generate_next_block(
5668     psa_tls12_prf_key_derivation_t *tls12_prf,
5669     psa_algorithm_t alg)
5670 {
5671     psa_algorithm_t hash_alg = PSA_ALG_HKDF_GET_HASH(alg);
5672     uint8_t hash_length = PSA_HASH_LENGTH(hash_alg);
5673     psa_mac_operation_t hmac = PSA_MAC_OPERATION_INIT;
5674     size_t hmac_output_length;
5675     psa_status_t status, cleanup_status;
5676 
5677     /* We can't be wanting more output after block 0xff, otherwise
5678      * the capacity check in psa_key_derivation_output_bytes() would have
5679      * prevented this call. It could happen only if the operation
5680      * object was corrupted or if this function is called directly
5681      * inside the library. */
5682     if (tls12_prf->block_number == 0xff) {
5683         return PSA_ERROR_CORRUPTION_DETECTED;
5684     }
5685 
5686     /* We need a new block */
5687     ++tls12_prf->block_number;
5688     tls12_prf->left_in_block = hash_length;
5689 
5690     /* Recall the definition of the TLS-1.2-PRF from RFC 5246:
5691      *
5692      * PRF(secret, label, seed) = P_<hash>(secret, label + seed)
5693      *
5694      * P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
5695      *                        HMAC_hash(secret, A(2) + seed) +
5696      *                        HMAC_hash(secret, A(3) + seed) + ...
5697      *
5698      * A(0) = seed
5699      * A(i) = HMAC_hash(secret, A(i-1))
5700      *
5701      * The `psa_tls12_prf_key_derivation` structure saves the block
5702      * `HMAC_hash(secret, A(i) + seed)` from which the output
5703      * is currently extracted as `output_block` and where i is
5704      * `block_number`.
5705      */
5706 
5707     status = psa_key_derivation_start_hmac(&hmac,
5708                                            hash_alg,
5709                                            tls12_prf->secret,
5710                                            tls12_prf->secret_length);
5711     if (status != PSA_SUCCESS) {
5712         goto cleanup;
5713     }
5714 
5715     /* Calculate A(i) where i = tls12_prf->block_number. */
5716     if (tls12_prf->block_number == 1) {
5717         /* A(1) = HMAC_hash(secret, A(0)), where A(0) = seed. (The RFC overloads
5718          * the variable seed and in this instance means it in the context of the
5719          * P_hash function, where seed = label + seed.) */
5720         status = psa_mac_update(&hmac,
5721                                 tls12_prf->label,
5722                                 tls12_prf->label_length);
5723         if (status != PSA_SUCCESS) {
5724             goto cleanup;
5725         }
5726         status = psa_mac_update(&hmac,
5727                                 tls12_prf->seed,
5728                                 tls12_prf->seed_length);
5729         if (status != PSA_SUCCESS) {
5730             goto cleanup;
5731         }
5732     } else {
5733         /* A(i) = HMAC_hash(secret, A(i-1)) */
5734         status = psa_mac_update(&hmac, tls12_prf->Ai, hash_length);
5735         if (status != PSA_SUCCESS) {
5736             goto cleanup;
5737         }
5738     }
5739 
5740     status = psa_mac_sign_finish(&hmac,
5741                                  tls12_prf->Ai, hash_length,
5742                                  &hmac_output_length);
5743     if (hmac_output_length != hash_length) {
5744         status = PSA_ERROR_CORRUPTION_DETECTED;
5745     }
5746     if (status != PSA_SUCCESS) {
5747         goto cleanup;
5748     }
5749 
5750     /* Calculate HMAC_hash(secret, A(i) + label + seed). */
5751     status = psa_key_derivation_start_hmac(&hmac,
5752                                            hash_alg,
5753                                            tls12_prf->secret,
5754                                            tls12_prf->secret_length);
5755     if (status != PSA_SUCCESS) {
5756         goto cleanup;
5757     }
5758     status = psa_mac_update(&hmac, tls12_prf->Ai, hash_length);
5759     if (status != PSA_SUCCESS) {
5760         goto cleanup;
5761     }
5762     status = psa_mac_update(&hmac, tls12_prf->label, tls12_prf->label_length);
5763     if (status != PSA_SUCCESS) {
5764         goto cleanup;
5765     }
5766     status = psa_mac_update(&hmac, tls12_prf->seed, tls12_prf->seed_length);
5767     if (status != PSA_SUCCESS) {
5768         goto cleanup;
5769     }
5770     status = psa_mac_sign_finish(&hmac,
5771                                  tls12_prf->output_block, hash_length,
5772                                  &hmac_output_length);
5773     if (status != PSA_SUCCESS) {
5774         goto cleanup;
5775     }
5776 
5777 
5778 cleanup:
5779     cleanup_status = psa_mac_abort(&hmac);
5780     if (status == PSA_SUCCESS && cleanup_status != PSA_SUCCESS) {
5781         status = cleanup_status;
5782     }
5783 
5784     return status;
5785 }
5786 
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)5787 static psa_status_t psa_key_derivation_tls12_prf_read(
5788     psa_tls12_prf_key_derivation_t *tls12_prf,
5789     psa_algorithm_t alg,
5790     uint8_t *output,
5791     size_t output_length)
5792 {
5793     psa_algorithm_t hash_alg = PSA_ALG_TLS12_PRF_GET_HASH(alg);
5794     uint8_t hash_length = PSA_HASH_LENGTH(hash_alg);
5795     psa_status_t status;
5796     uint8_t offset, length;
5797 
5798     switch (tls12_prf->state) {
5799         case PSA_TLS12_PRF_STATE_LABEL_SET:
5800             tls12_prf->state = PSA_TLS12_PRF_STATE_OUTPUT;
5801             break;
5802         case PSA_TLS12_PRF_STATE_OUTPUT:
5803             break;
5804         default:
5805             return PSA_ERROR_BAD_STATE;
5806     }
5807 
5808     while (output_length != 0) {
5809         /* Check if we have fully processed the current block. */
5810         if (tls12_prf->left_in_block == 0) {
5811             status = psa_key_derivation_tls12_prf_generate_next_block(tls12_prf,
5812                                                                       alg);
5813             if (status != PSA_SUCCESS) {
5814                 return status;
5815             }
5816 
5817             continue;
5818         }
5819 
5820         if (tls12_prf->left_in_block > output_length) {
5821             length = (uint8_t) output_length;
5822         } else {
5823             length = tls12_prf->left_in_block;
5824         }
5825 
5826         offset = hash_length - tls12_prf->left_in_block;
5827         memcpy(output, tls12_prf->output_block + offset, length);
5828         output += length;
5829         output_length -= length;
5830         tls12_prf->left_in_block -= length;
5831     }
5832 
5833     return PSA_SUCCESS;
5834 }
5835 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF ||
5836         * MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
5837 
5838 #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)5839 static psa_status_t psa_key_derivation_tls12_ecjpake_to_pms_read(
5840     psa_tls12_ecjpake_to_pms_t *ecjpake,
5841     uint8_t *output,
5842     size_t output_length)
5843 {
5844     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
5845     size_t output_size = 0;
5846 
5847     if (output_length != 32) {
5848         return PSA_ERROR_INVALID_ARGUMENT;
5849     }
5850 
5851     status = psa_hash_compute(PSA_ALG_SHA_256, ecjpake->data,
5852                               PSA_TLS12_ECJPAKE_TO_PMS_DATA_SIZE, output, output_length,
5853                               &output_size);
5854     if (status != PSA_SUCCESS) {
5855         return status;
5856     }
5857 
5858     if (output_size != output_length) {
5859         return PSA_ERROR_GENERIC_ERROR;
5860     }
5861 
5862     return PSA_SUCCESS;
5863 }
5864 #endif
5865 
5866 #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)5867 static psa_status_t psa_key_derivation_pbkdf2_generate_block(
5868     psa_pbkdf2_key_derivation_t *pbkdf2,
5869     psa_algorithm_t prf_alg,
5870     uint8_t prf_output_length,
5871     psa_key_attributes_t *attributes)
5872 {
5873     psa_status_t status;
5874     psa_mac_operation_t mac_operation = PSA_MAC_OPERATION_INIT;
5875     size_t mac_output_length;
5876     uint8_t U_i[PSA_MAC_MAX_SIZE];
5877     uint8_t *U_accumulator = pbkdf2->output_block;
5878     uint64_t i;
5879     uint8_t block_counter[4];
5880 
5881     mac_operation.is_sign = 1;
5882     mac_operation.mac_size = prf_output_length;
5883     MBEDTLS_PUT_UINT32_BE(pbkdf2->block_number, block_counter, 0);
5884 
5885     status = psa_driver_wrapper_mac_sign_setup(&mac_operation,
5886                                                attributes,
5887                                                pbkdf2->password,
5888                                                pbkdf2->password_length,
5889                                                prf_alg);
5890     if (status != PSA_SUCCESS) {
5891         goto cleanup;
5892     }
5893     status = psa_mac_update(&mac_operation, pbkdf2->salt, pbkdf2->salt_length);
5894     if (status != PSA_SUCCESS) {
5895         goto cleanup;
5896     }
5897     status = psa_mac_update(&mac_operation, block_counter, sizeof(block_counter));
5898     if (status != PSA_SUCCESS) {
5899         goto cleanup;
5900     }
5901     status = psa_mac_sign_finish(&mac_operation, U_i, sizeof(U_i),
5902                                  &mac_output_length);
5903     if (status != PSA_SUCCESS) {
5904         goto cleanup;
5905     }
5906 
5907     if (mac_output_length != prf_output_length) {
5908         status = PSA_ERROR_CORRUPTION_DETECTED;
5909         goto cleanup;
5910     }
5911 
5912     memcpy(U_accumulator, U_i, prf_output_length);
5913 
5914     for (i = 1; i < pbkdf2->input_cost; i++) {
5915         /* We are passing prf_output_length as mac_size because the driver
5916          * function directly sets mac_output_length as mac_size upon success.
5917          * See https://github.com/Mbed-TLS/mbedtls/issues/7801 */
5918         status = psa_driver_wrapper_mac_compute(attributes,
5919                                                 pbkdf2->password,
5920                                                 pbkdf2->password_length,
5921                                                 prf_alg, U_i, prf_output_length,
5922                                                 U_i, prf_output_length,
5923                                                 &mac_output_length);
5924         if (status != PSA_SUCCESS) {
5925             goto cleanup;
5926         }
5927 
5928         mbedtls_xor(U_accumulator, U_accumulator, U_i, prf_output_length);
5929     }
5930 
5931 cleanup:
5932     /* Zeroise buffers to clear sensitive data from memory. */
5933     mbedtls_platform_zeroize(U_i, PSA_MAC_MAX_SIZE);
5934     return status;
5935 }
5936 
psa_key_derivation_pbkdf2_read(psa_pbkdf2_key_derivation_t * pbkdf2,psa_algorithm_t kdf_alg,uint8_t * output,size_t output_length)5937 static psa_status_t psa_key_derivation_pbkdf2_read(
5938     psa_pbkdf2_key_derivation_t *pbkdf2,
5939     psa_algorithm_t kdf_alg,
5940     uint8_t *output,
5941     size_t output_length)
5942 {
5943     psa_status_t status;
5944     psa_algorithm_t prf_alg;
5945     uint8_t prf_output_length;
5946     psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
5947     psa_set_key_bits(&attributes, PSA_BYTES_TO_BITS(pbkdf2->password_length));
5948     psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_MESSAGE);
5949 
5950     if (PSA_ALG_IS_PBKDF2_HMAC(kdf_alg)) {
5951         prf_alg = PSA_ALG_HMAC(PSA_ALG_PBKDF2_HMAC_GET_HASH(kdf_alg));
5952         prf_output_length = PSA_HASH_LENGTH(prf_alg);
5953         psa_set_key_type(&attributes, PSA_KEY_TYPE_HMAC);
5954     } else if (kdf_alg == PSA_ALG_PBKDF2_AES_CMAC_PRF_128) {
5955         prf_alg = PSA_ALG_CMAC;
5956         prf_output_length = PSA_MAC_LENGTH(PSA_KEY_TYPE_AES, 128U, PSA_ALG_CMAC);
5957         psa_set_key_type(&attributes, PSA_KEY_TYPE_AES);
5958     } else {
5959         return PSA_ERROR_INVALID_ARGUMENT;
5960     }
5961 
5962     switch (pbkdf2->state) {
5963         case PSA_PBKDF2_STATE_PASSWORD_SET:
5964             /* Initially we need a new block so bytes_used is equal to block size*/
5965             pbkdf2->bytes_used = prf_output_length;
5966             pbkdf2->state = PSA_PBKDF2_STATE_OUTPUT;
5967             break;
5968         case PSA_PBKDF2_STATE_OUTPUT:
5969             break;
5970         default:
5971             return PSA_ERROR_BAD_STATE;
5972     }
5973 
5974     while (output_length != 0) {
5975         uint8_t n = prf_output_length - pbkdf2->bytes_used;
5976         if (n > output_length) {
5977             n = (uint8_t) output_length;
5978         }
5979         memcpy(output, pbkdf2->output_block + pbkdf2->bytes_used, n);
5980         output += n;
5981         output_length -= n;
5982         pbkdf2->bytes_used += n;
5983 
5984         if (output_length == 0) {
5985             break;
5986         }
5987 
5988         /* We need a new block */
5989         pbkdf2->bytes_used = 0;
5990         pbkdf2->block_number++;
5991 
5992         status = psa_key_derivation_pbkdf2_generate_block(pbkdf2, prf_alg,
5993                                                           prf_output_length,
5994                                                           &attributes);
5995         if (status != PSA_SUCCESS) {
5996             return status;
5997         }
5998     }
5999 
6000     return PSA_SUCCESS;
6001 }
6002 #endif /* PSA_HAVE_SOFT_PBKDF2 */
6003 
psa_key_derivation_output_bytes(psa_key_derivation_operation_t * operation,uint8_t * output_external,size_t output_length)6004 psa_status_t psa_key_derivation_output_bytes(
6005     psa_key_derivation_operation_t *operation,
6006     uint8_t *output_external,
6007     size_t output_length)
6008 {
6009     psa_status_t status;
6010     LOCAL_OUTPUT_DECLARE(output_external, output);
6011 
6012     psa_algorithm_t kdf_alg = psa_key_derivation_get_kdf_alg(operation);
6013 
6014     if (operation->alg == 0) {
6015         /* This is a blank operation. */
6016         return PSA_ERROR_BAD_STATE;
6017     }
6018 
6019     if (output_length == 0 && operation->capacity == 0) {
6020         /* Edge case: this is a finished operation, and 0 bytes
6021          * were requested. The right error in this case could
6022          * be either INSUFFICIENT_CAPACITY or BAD_STATE. Return
6023          * INSUFFICIENT_CAPACITY, which is right for a finished
6024          * operation, for consistency with the case when
6025          * output_length > 0. */
6026         return PSA_ERROR_INSUFFICIENT_DATA;
6027     }
6028 
6029     LOCAL_OUTPUT_ALLOC(output_external, output_length, output);
6030     if (output_length > operation->capacity) {
6031         operation->capacity = 0;
6032         /* Go through the error path to wipe all confidential data now
6033          * that the operation object is useless. */
6034         status = PSA_ERROR_INSUFFICIENT_DATA;
6035         goto exit;
6036     }
6037 
6038     operation->capacity -= output_length;
6039 
6040 #if defined(BUILTIN_ALG_ANY_HKDF)
6041     if (PSA_ALG_IS_ANY_HKDF(kdf_alg)) {
6042         status = psa_key_derivation_hkdf_read(&operation->ctx.hkdf, kdf_alg,
6043                                               output, output_length);
6044     } else
6045 #endif /* BUILTIN_ALG_ANY_HKDF */
6046 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
6047     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
6048     if (PSA_ALG_IS_TLS12_PRF(kdf_alg) ||
6049         PSA_ALG_IS_TLS12_PSK_TO_MS(kdf_alg)) {
6050         status = psa_key_derivation_tls12_prf_read(&operation->ctx.tls12_prf,
6051                                                    kdf_alg, output,
6052                                                    output_length);
6053     } else
6054 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF ||
6055         * MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
6056 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS)
6057     if (kdf_alg == PSA_ALG_TLS12_ECJPAKE_TO_PMS) {
6058         status = psa_key_derivation_tls12_ecjpake_to_pms_read(
6059             &operation->ctx.tls12_ecjpake_to_pms, output, output_length);
6060     } else
6061 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS */
6062 #if defined(PSA_HAVE_SOFT_PBKDF2)
6063     if (PSA_ALG_IS_PBKDF2(kdf_alg)) {
6064         status = psa_key_derivation_pbkdf2_read(&operation->ctx.pbkdf2, kdf_alg,
6065                                                 output, output_length);
6066     } else
6067 #endif /* PSA_HAVE_SOFT_PBKDF2 */
6068 
6069     {
6070         (void) kdf_alg;
6071         status = PSA_ERROR_BAD_STATE;
6072         LOCAL_OUTPUT_FREE(output_external, output);
6073 
6074         return status;
6075     }
6076 
6077 exit:
6078     if (status != PSA_SUCCESS) {
6079         /* Preserve the algorithm upon errors, but clear all sensitive state.
6080          * This allows us to differentiate between exhausted operations and
6081          * blank operations, so we can return PSA_ERROR_BAD_STATE on blank
6082          * operations. */
6083         psa_algorithm_t alg = operation->alg;
6084         psa_key_derivation_abort(operation);
6085         operation->alg = alg;
6086         if (output != NULL) {
6087             memset(output, '!', output_length);
6088         }
6089     }
6090 
6091     LOCAL_OUTPUT_FREE(output_external, output);
6092     return status;
6093 }
6094 
6095 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES)
psa_des_set_key_parity(uint8_t * data,size_t data_size)6096 static void psa_des_set_key_parity(uint8_t *data, size_t data_size)
6097 {
6098     if (data_size >= 8) {
6099         mbedtls_des_key_set_parity(data);
6100     }
6101     if (data_size >= 16) {
6102         mbedtls_des_key_set_parity(data + 8);
6103     }
6104     if (data_size >= 24) {
6105         mbedtls_des_key_set_parity(data + 16);
6106     }
6107 }
6108 #endif /* MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES */
6109 
6110 /*
6111  * ECC keys on a Weierstrass elliptic curve require the generation
6112  * of a private key which is an integer
6113  * in the range [1, N - 1], where N is the boundary of the private key domain:
6114  * N is the prime p for Diffie-Hellman, or the order of the
6115  * curve’s base point for ECC.
6116  *
6117  * Let m be the bit size of N, such that 2^m > N >= 2^(m-1).
6118  * This function generates the private key using the following process:
6119  *
6120  * 1. Draw a byte string of length ceiling(m/8) bytes.
6121  * 2. If m is not a multiple of 8, set the most significant
6122  *    (8 * ceiling(m/8) - m) bits of the first byte in the string to zero.
6123  * 3. Convert the string to integer k by decoding it as a big-endian byte string.
6124  * 4. If k > N - 2, discard the result and return to step 1.
6125  * 5. Output k + 1 as the private key.
6126  *
6127  * This method allows compliance to NIST standards, specifically the methods titled
6128  * Key-Pair Generation by Testing Candidates in the following publications:
6129  * - NIST Special Publication 800-56A: Recommendation for Pair-Wise Key-Establishment
6130  *   Schemes Using Discrete Logarithm Cryptography [SP800-56A] §5.6.1.1.4 for
6131  *   Diffie-Hellman keys.
6132  *
6133  * - [SP800-56A] §5.6.1.2.2 or FIPS Publication 186-4: Digital Signature
6134  *   Standard (DSS) [FIPS186-4] §B.4.2 for elliptic curve keys.
6135  *
6136  * Note: Function allocates memory for *data buffer, so given *data should be
6137  *       always NULL.
6138  */
6139 #if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE)
6140 #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)6141 static psa_status_t psa_generate_derived_ecc_key_weierstrass_helper(
6142     psa_key_slot_t *slot,
6143     size_t bits,
6144     psa_key_derivation_operation_t *operation,
6145     uint8_t **data
6146     )
6147 {
6148     unsigned key_out_of_range = 1;
6149     mbedtls_mpi k;
6150     mbedtls_mpi diff_N_2;
6151     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
6152     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
6153     size_t m;
6154     size_t m_bytes;
6155 
6156     mbedtls_mpi_init(&k);
6157     mbedtls_mpi_init(&diff_N_2);
6158 
6159     psa_ecc_family_t curve = PSA_KEY_TYPE_ECC_GET_FAMILY(
6160         slot->attr.type);
6161     mbedtls_ecp_group_id grp_id =
6162         mbedtls_ecc_group_from_psa(curve, bits);
6163 
6164     if (grp_id == MBEDTLS_ECP_DP_NONE) {
6165         ret = MBEDTLS_ERR_ASN1_INVALID_DATA;
6166         goto cleanup;
6167     }
6168 
6169     mbedtls_ecp_group ecp_group;
6170     mbedtls_ecp_group_init(&ecp_group);
6171 
6172     MBEDTLS_MPI_CHK(mbedtls_ecp_group_load(&ecp_group, grp_id));
6173 
6174     /* N is the boundary of the private key domain (ecp_group.N). */
6175     /* Let m be the bit size of N. */
6176     m = ecp_group.nbits;
6177 
6178     m_bytes = PSA_BITS_TO_BYTES(m);
6179 
6180     /* Calculate N - 2 - it will be needed later. */
6181     MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&diff_N_2, &ecp_group.N, 2));
6182 
6183     /* Note: This function is always called with *data == NULL and it
6184      * allocates memory for the data buffer. */
6185     *data = mbedtls_calloc(1, m_bytes);
6186     if (*data == NULL) {
6187         ret = MBEDTLS_ERR_ASN1_ALLOC_FAILED;
6188         goto cleanup;
6189     }
6190 
6191     while (key_out_of_range) {
6192         /* 1. Draw a byte string of length ceiling(m/8) bytes. */
6193         if ((status = psa_key_derivation_output_bytes(operation, *data, m_bytes)) != 0) {
6194             goto cleanup;
6195         }
6196 
6197         /* 2. If m is not a multiple of 8 */
6198         if (m % 8 != 0) {
6199             /* Set the most significant
6200              * (8 * ceiling(m/8) - m) bits of the first byte in
6201              * the string to zero.
6202              */
6203             uint8_t clear_bit_mask = (1 << (m % 8)) - 1;
6204             (*data)[0] &= clear_bit_mask;
6205         }
6206 
6207         /* 3. Convert the string to integer k by decoding it as a
6208          *    big-endian byte string.
6209          */
6210         MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&k, *data, m_bytes));
6211 
6212         /* 4. If k > N - 2, discard the result and return to step 1.
6213          *    Result of comparison is returned. When it indicates error
6214          *    then this function is called again.
6215          */
6216         MBEDTLS_MPI_CHK(mbedtls_mpi_lt_mpi_ct(&diff_N_2, &k, &key_out_of_range));
6217     }
6218 
6219     /* 5. Output k + 1 as the private key. */
6220     MBEDTLS_MPI_CHK(mbedtls_mpi_add_int(&k, &k, 1));
6221     MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&k, *data, m_bytes));
6222 cleanup:
6223     if (ret != 0) {
6224         status = mbedtls_to_psa_error(ret);
6225     }
6226     if (status != PSA_SUCCESS) {
6227         mbedtls_free(*data);
6228         *data = NULL;
6229     }
6230     mbedtls_mpi_free(&k);
6231     mbedtls_mpi_free(&diff_N_2);
6232     return status;
6233 }
6234 
6235 /* ECC keys on a Montgomery elliptic curve draws a byte string whose length
6236  * is determined by the curve, and sets the mandatory bits accordingly. That is:
6237  *
6238  * - Curve25519 (PSA_ECC_FAMILY_MONTGOMERY, 255 bits):
6239  *   draw a 32-byte string and process it as specified in
6240  *   Elliptic Curves for Security [RFC7748] §5.
6241  *
6242  * - Curve448 (PSA_ECC_FAMILY_MONTGOMERY, 448 bits):
6243  *   draw a 56-byte string and process it as specified in [RFC7748] §5.
6244  *
6245  * Note: Function allocates memory for *data buffer, so given *data should be
6246  *       always NULL.
6247  */
6248 
psa_generate_derived_ecc_key_montgomery_helper(size_t bits,psa_key_derivation_operation_t * operation,uint8_t ** data)6249 static psa_status_t psa_generate_derived_ecc_key_montgomery_helper(
6250     size_t bits,
6251     psa_key_derivation_operation_t *operation,
6252     uint8_t **data
6253     )
6254 {
6255     size_t output_length;
6256     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
6257 
6258     switch (bits) {
6259         case 255:
6260             output_length = 32;
6261             break;
6262         case 448:
6263             output_length = 56;
6264             break;
6265         default:
6266             return PSA_ERROR_INVALID_ARGUMENT;
6267             break;
6268     }
6269 
6270     *data = mbedtls_calloc(1, output_length);
6271 
6272     if (*data == NULL) {
6273         return PSA_ERROR_INSUFFICIENT_MEMORY;
6274     }
6275 
6276     status = psa_key_derivation_output_bytes(operation, *data, output_length);
6277 
6278     if (status != PSA_SUCCESS) {
6279         return status;
6280     }
6281 
6282     switch (bits) {
6283         case 255:
6284             (*data)[0] &= 248;
6285             (*data)[31] &= 127;
6286             (*data)[31] |= 64;
6287             break;
6288         case 448:
6289             (*data)[0] &= 252;
6290             (*data)[55] |= 128;
6291             break;
6292         default:
6293             return PSA_ERROR_CORRUPTION_DETECTED;
6294             break;
6295     }
6296 
6297     return status;
6298 }
6299 #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)6300 static psa_status_t psa_generate_derived_ecc_key_weierstrass_helper(
6301     psa_key_slot_t *slot, size_t bits,
6302     psa_key_derivation_operation_t *operation, uint8_t **data)
6303 {
6304     (void) slot;
6305     (void) bits;
6306     (void) operation;
6307     (void) data;
6308     return PSA_ERROR_NOT_SUPPORTED;
6309 }
6310 
psa_generate_derived_ecc_key_montgomery_helper(size_t bits,psa_key_derivation_operation_t * operation,uint8_t ** data)6311 static psa_status_t psa_generate_derived_ecc_key_montgomery_helper(
6312     size_t bits, psa_key_derivation_operation_t *operation, uint8_t **data)
6313 {
6314     (void) bits;
6315     (void) operation;
6316     (void) data;
6317     return PSA_ERROR_NOT_SUPPORTED;
6318 }
6319 #endif /* MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_DERIVE */
6320 #endif /* PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE */
6321 
psa_generate_derived_key_internal(psa_key_slot_t * slot,size_t bits,psa_key_derivation_operation_t * operation)6322 static psa_status_t psa_generate_derived_key_internal(
6323     psa_key_slot_t *slot,
6324     size_t bits,
6325     psa_key_derivation_operation_t *operation)
6326 {
6327     uint8_t *data = NULL;
6328     size_t bytes = PSA_BITS_TO_BYTES(bits);
6329     size_t storage_size = bytes;
6330     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
6331 
6332     if (PSA_KEY_TYPE_IS_PUBLIC_KEY(slot->attr.type)) {
6333         return PSA_ERROR_INVALID_ARGUMENT;
6334     }
6335 
6336 #if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE) || \
6337     defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_DERIVE)
6338     if (PSA_KEY_TYPE_IS_ECC(slot->attr.type)) {
6339         psa_ecc_family_t curve = PSA_KEY_TYPE_ECC_GET_FAMILY(slot->attr.type);
6340         if (PSA_ECC_FAMILY_IS_WEIERSTRASS(curve)) {
6341             /* Weierstrass elliptic curve */
6342             status = psa_generate_derived_ecc_key_weierstrass_helper(slot, bits, operation, &data);
6343             if (status != PSA_SUCCESS) {
6344                 goto exit;
6345             }
6346         } else {
6347             /* Montgomery elliptic curve */
6348             status = psa_generate_derived_ecc_key_montgomery_helper(bits, operation, &data);
6349             if (status != PSA_SUCCESS) {
6350                 goto exit;
6351             }
6352         }
6353     } else
6354 #endif /* defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE) ||
6355           defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_DERIVE) */
6356     if (key_type_is_raw_bytes(slot->attr.type)) {
6357         if (bits % 8 != 0) {
6358             return PSA_ERROR_INVALID_ARGUMENT;
6359         }
6360         data = mbedtls_calloc(1, bytes);
6361         if (data == NULL) {
6362             return PSA_ERROR_INSUFFICIENT_MEMORY;
6363         }
6364 
6365         status = psa_key_derivation_output_bytes(operation, data, bytes);
6366         if (status != PSA_SUCCESS) {
6367             goto exit;
6368         }
6369 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES)
6370         if (slot->attr.type == PSA_KEY_TYPE_DES) {
6371             psa_des_set_key_parity(data, bytes);
6372         }
6373 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES) */
6374     } else {
6375         return PSA_ERROR_NOT_SUPPORTED;
6376     }
6377 
6378     slot->attr.bits = (psa_key_bits_t) bits;
6379 
6380     if (psa_key_lifetime_is_external(slot->attr.lifetime)) {
6381         status = psa_driver_wrapper_get_key_buffer_size(&slot->attr,
6382                                                         &storage_size);
6383         if (status != PSA_SUCCESS) {
6384             goto exit;
6385         }
6386     }
6387     status = psa_allocate_buffer_to_slot(slot, storage_size);
6388     if (status != PSA_SUCCESS) {
6389         goto exit;
6390     }
6391 
6392     status = psa_driver_wrapper_import_key(&slot->attr,
6393                                            data, bytes,
6394                                            slot->key.data,
6395                                            slot->key.bytes,
6396                                            &slot->key.bytes, &bits);
6397     if (bits != slot->attr.bits) {
6398         status = PSA_ERROR_INVALID_ARGUMENT;
6399     }
6400 
6401 exit:
6402     mbedtls_free(data);
6403     return status;
6404 }
6405 
6406 static const psa_key_production_parameters_t default_production_parameters =
6407     PSA_KEY_PRODUCTION_PARAMETERS_INIT;
6408 
psa_key_production_parameters_are_default(const psa_key_production_parameters_t * params,size_t params_data_length)6409 int psa_key_production_parameters_are_default(
6410     const psa_key_production_parameters_t *params,
6411     size_t params_data_length)
6412 {
6413     if (params->flags != 0) {
6414         return 0;
6415     }
6416     if (params_data_length != 0) {
6417         return 0;
6418     }
6419     return 1;
6420 }
6421 
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)6422 psa_status_t psa_key_derivation_output_key_ext(
6423     const psa_key_attributes_t *attributes,
6424     psa_key_derivation_operation_t *operation,
6425     const psa_key_production_parameters_t *params,
6426     size_t params_data_length,
6427     mbedtls_svc_key_id_t *key)
6428 {
6429     psa_status_t status;
6430     psa_key_slot_t *slot = NULL;
6431     psa_se_drv_table_entry_t *driver = NULL;
6432 
6433     *key = MBEDTLS_SVC_KEY_ID_INIT;
6434 
6435     /* Reject any attempt to create a zero-length key so that we don't
6436      * risk tripping up later, e.g. on a malloc(0) that returns NULL. */
6437     if (psa_get_key_bits(attributes) == 0) {
6438         return PSA_ERROR_INVALID_ARGUMENT;
6439     }
6440 
6441     if (!psa_key_production_parameters_are_default(params, params_data_length)) {
6442         return PSA_ERROR_INVALID_ARGUMENT;
6443     }
6444 
6445     if (operation->alg == PSA_ALG_NONE) {
6446         return PSA_ERROR_BAD_STATE;
6447     }
6448 
6449     if (!operation->can_output_key) {
6450         return PSA_ERROR_NOT_PERMITTED;
6451     }
6452 
6453     status = psa_start_key_creation(PSA_KEY_CREATION_DERIVE, attributes,
6454                                     &slot, &driver);
6455 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
6456     if (driver != NULL) {
6457         /* Deriving a key in a secure element is not implemented yet. */
6458         status = PSA_ERROR_NOT_SUPPORTED;
6459     }
6460 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
6461     if (status == PSA_SUCCESS) {
6462         status = psa_generate_derived_key_internal(slot,
6463                                                    attributes->bits,
6464                                                    operation);
6465     }
6466     if (status == PSA_SUCCESS) {
6467         status = psa_finish_key_creation(slot, driver, key);
6468     }
6469     if (status != PSA_SUCCESS) {
6470         psa_fail_key_creation(slot, driver);
6471     }
6472 
6473     return status;
6474 }
6475 
psa_key_derivation_output_key(const psa_key_attributes_t * attributes,psa_key_derivation_operation_t * operation,mbedtls_svc_key_id_t * key)6476 psa_status_t psa_key_derivation_output_key(
6477     const psa_key_attributes_t *attributes,
6478     psa_key_derivation_operation_t *operation,
6479     mbedtls_svc_key_id_t *key)
6480 {
6481     return psa_key_derivation_output_key_ext(attributes, operation,
6482                                              &default_production_parameters, 0,
6483                                              key);
6484 }
6485 
6486 
6487 /****************************************************************/
6488 /* Key derivation */
6489 /****************************************************************/
6490 
6491 #if defined(AT_LEAST_ONE_BUILTIN_KDF)
is_kdf_alg_supported(psa_algorithm_t kdf_alg)6492 static int is_kdf_alg_supported(psa_algorithm_t kdf_alg)
6493 {
6494 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF)
6495     if (PSA_ALG_IS_HKDF(kdf_alg)) {
6496         return 1;
6497     }
6498 #endif
6499 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT)
6500     if (PSA_ALG_IS_HKDF_EXTRACT(kdf_alg)) {
6501         return 1;
6502     }
6503 #endif
6504 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXPAND)
6505     if (PSA_ALG_IS_HKDF_EXPAND(kdf_alg)) {
6506         return 1;
6507     }
6508 #endif
6509 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF)
6510     if (PSA_ALG_IS_TLS12_PRF(kdf_alg)) {
6511         return 1;
6512     }
6513 #endif
6514 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
6515     if (PSA_ALG_IS_TLS12_PSK_TO_MS(kdf_alg)) {
6516         return 1;
6517     }
6518 #endif
6519 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS)
6520     if (kdf_alg == PSA_ALG_TLS12_ECJPAKE_TO_PMS) {
6521         return 1;
6522     }
6523 #endif
6524 #if defined(MBEDTLS_PSA_BUILTIN_ALG_PBKDF2_HMAC)
6525     if (PSA_ALG_IS_PBKDF2_HMAC(kdf_alg)) {
6526         return 1;
6527     }
6528 #endif
6529 #if defined(MBEDTLS_PSA_BUILTIN_ALG_PBKDF2_AES_CMAC_PRF_128)
6530     if (kdf_alg == PSA_ALG_PBKDF2_AES_CMAC_PRF_128) {
6531         return 1;
6532     }
6533 #endif
6534     return 0;
6535 }
6536 
psa_hash_try_support(psa_algorithm_t alg)6537 static psa_status_t psa_hash_try_support(psa_algorithm_t alg)
6538 {
6539     psa_hash_operation_t operation = PSA_HASH_OPERATION_INIT;
6540     psa_status_t status = psa_hash_setup(&operation, alg);
6541     psa_hash_abort(&operation);
6542     return status;
6543 }
6544 
psa_key_derivation_set_maximum_capacity(psa_key_derivation_operation_t * operation,psa_algorithm_t kdf_alg)6545 static psa_status_t psa_key_derivation_set_maximum_capacity(
6546     psa_key_derivation_operation_t *operation,
6547     psa_algorithm_t kdf_alg)
6548 {
6549 #if defined(PSA_WANT_ALG_TLS12_ECJPAKE_TO_PMS)
6550     if (kdf_alg == PSA_ALG_TLS12_ECJPAKE_TO_PMS) {
6551         operation->capacity = PSA_HASH_LENGTH(PSA_ALG_SHA_256);
6552         return PSA_SUCCESS;
6553     }
6554 #endif
6555 #if defined(PSA_WANT_ALG_PBKDF2_AES_CMAC_PRF_128)
6556     if (kdf_alg == PSA_ALG_PBKDF2_AES_CMAC_PRF_128) {
6557 #if (SIZE_MAX > UINT32_MAX)
6558         operation->capacity = UINT32_MAX * (size_t) PSA_MAC_LENGTH(
6559             PSA_KEY_TYPE_AES,
6560             128U,
6561             PSA_ALG_CMAC);
6562 #else
6563         operation->capacity = SIZE_MAX;
6564 #endif
6565         return PSA_SUCCESS;
6566     }
6567 #endif /* PSA_WANT_ALG_PBKDF2_AES_CMAC_PRF_128 */
6568 
6569     /* After this point, if kdf_alg is not valid then value of hash_alg may be
6570      * invalid or meaningless but it does not affect this function */
6571     psa_algorithm_t hash_alg = PSA_ALG_GET_HASH(kdf_alg);
6572     size_t hash_size = PSA_HASH_LENGTH(hash_alg);
6573     if (hash_size == 0) {
6574         return PSA_ERROR_NOT_SUPPORTED;
6575     }
6576 
6577     /* Make sure that hash_alg is a supported hash algorithm. Otherwise
6578      * we might fail later, which is somewhat unfriendly and potentially
6579      * risk-prone. */
6580     psa_status_t status = psa_hash_try_support(hash_alg);
6581     if (status != PSA_SUCCESS) {
6582         return status;
6583     }
6584 
6585 #if defined(PSA_WANT_ALG_HKDF)
6586     if (PSA_ALG_IS_HKDF(kdf_alg)) {
6587         operation->capacity = 255 * hash_size;
6588     } else
6589 #endif
6590 #if defined(PSA_WANT_ALG_HKDF_EXTRACT)
6591     if (PSA_ALG_IS_HKDF_EXTRACT(kdf_alg)) {
6592         operation->capacity = hash_size;
6593     } else
6594 #endif
6595 #if defined(PSA_WANT_ALG_HKDF_EXPAND)
6596     if (PSA_ALG_IS_HKDF_EXPAND(kdf_alg)) {
6597         operation->capacity = 255 * hash_size;
6598     } else
6599 #endif
6600 #if defined(PSA_WANT_ALG_TLS12_PRF)
6601     if (PSA_ALG_IS_TLS12_PRF(kdf_alg) &&
6602         (hash_alg == PSA_ALG_SHA_256 || hash_alg == PSA_ALG_SHA_384)) {
6603         operation->capacity = SIZE_MAX;
6604     } else
6605 #endif
6606 #if defined(PSA_WANT_ALG_TLS12_PSK_TO_MS)
6607     if (PSA_ALG_IS_TLS12_PSK_TO_MS(kdf_alg) &&
6608         (hash_alg == PSA_ALG_SHA_256 || hash_alg == PSA_ALG_SHA_384)) {
6609         /* Master Secret is always 48 bytes
6610          * https://datatracker.ietf.org/doc/html/rfc5246.html#section-8.1 */
6611         operation->capacity = 48U;
6612     } else
6613 #endif
6614 #if defined(PSA_WANT_ALG_PBKDF2_HMAC)
6615     if (PSA_ALG_IS_PBKDF2_HMAC(kdf_alg)) {
6616 #if (SIZE_MAX > UINT32_MAX)
6617         operation->capacity = UINT32_MAX * hash_size;
6618 #else
6619         operation->capacity = SIZE_MAX;
6620 #endif
6621     } else
6622 #endif /* PSA_WANT_ALG_PBKDF2_HMAC */
6623     {
6624         (void) hash_size;
6625         status = PSA_ERROR_NOT_SUPPORTED;
6626     }
6627     return status;
6628 }
6629 
psa_key_derivation_setup_kdf(psa_key_derivation_operation_t * operation,psa_algorithm_t kdf_alg)6630 static psa_status_t psa_key_derivation_setup_kdf(
6631     psa_key_derivation_operation_t *operation,
6632     psa_algorithm_t kdf_alg)
6633 {
6634     /* Make sure that operation->ctx is properly zero-initialised. (Macro
6635      * initialisers for this union leave some bytes unspecified.) */
6636     memset(&operation->ctx, 0, sizeof(operation->ctx));
6637 
6638     /* Make sure that kdf_alg is a supported key derivation algorithm. */
6639     if (!is_kdf_alg_supported(kdf_alg)) {
6640         return PSA_ERROR_NOT_SUPPORTED;
6641     }
6642 
6643     psa_status_t status = psa_key_derivation_set_maximum_capacity(operation,
6644                                                                   kdf_alg);
6645     return status;
6646 }
6647 
psa_key_agreement_try_support(psa_algorithm_t alg)6648 static psa_status_t psa_key_agreement_try_support(psa_algorithm_t alg)
6649 {
6650 #if defined(PSA_WANT_ALG_ECDH)
6651     if (alg == PSA_ALG_ECDH) {
6652         return PSA_SUCCESS;
6653     }
6654 #endif
6655 #if defined(PSA_WANT_ALG_FFDH)
6656     if (alg == PSA_ALG_FFDH) {
6657         return PSA_SUCCESS;
6658     }
6659 #endif
6660     (void) alg;
6661     return PSA_ERROR_NOT_SUPPORTED;
6662 }
6663 
psa_key_derivation_allows_free_form_secret_input(psa_algorithm_t kdf_alg)6664 static int psa_key_derivation_allows_free_form_secret_input(
6665     psa_algorithm_t kdf_alg)
6666 {
6667 #if defined(PSA_WANT_ALG_TLS12_ECJPAKE_TO_PMS)
6668     if (kdf_alg == PSA_ALG_TLS12_ECJPAKE_TO_PMS) {
6669         return 0;
6670     }
6671 #endif
6672     (void) kdf_alg;
6673     return 1;
6674 }
6675 #endif /* AT_LEAST_ONE_BUILTIN_KDF */
6676 
psa_key_derivation_setup(psa_key_derivation_operation_t * operation,psa_algorithm_t alg)6677 psa_status_t psa_key_derivation_setup(psa_key_derivation_operation_t *operation,
6678                                       psa_algorithm_t alg)
6679 {
6680     psa_status_t status;
6681 
6682     if (operation->alg != 0) {
6683         return PSA_ERROR_BAD_STATE;
6684     }
6685 
6686     if (PSA_ALG_IS_RAW_KEY_AGREEMENT(alg)) {
6687         return PSA_ERROR_INVALID_ARGUMENT;
6688     } else if (PSA_ALG_IS_KEY_AGREEMENT(alg)) {
6689 #if defined(AT_LEAST_ONE_BUILTIN_KDF)
6690         psa_algorithm_t kdf_alg = PSA_ALG_KEY_AGREEMENT_GET_KDF(alg);
6691         psa_algorithm_t ka_alg = PSA_ALG_KEY_AGREEMENT_GET_BASE(alg);
6692         status = psa_key_agreement_try_support(ka_alg);
6693         if (status != PSA_SUCCESS) {
6694             return status;
6695         }
6696         if (!psa_key_derivation_allows_free_form_secret_input(kdf_alg)) {
6697             return PSA_ERROR_INVALID_ARGUMENT;
6698         }
6699         status = psa_key_derivation_setup_kdf(operation, kdf_alg);
6700 #else
6701         return PSA_ERROR_NOT_SUPPORTED;
6702 #endif /* AT_LEAST_ONE_BUILTIN_KDF */
6703     } else if (PSA_ALG_IS_KEY_DERIVATION(alg)) {
6704 #if defined(AT_LEAST_ONE_BUILTIN_KDF)
6705         status = psa_key_derivation_setup_kdf(operation, alg);
6706 #else
6707         return PSA_ERROR_NOT_SUPPORTED;
6708 #endif /* AT_LEAST_ONE_BUILTIN_KDF */
6709     } else {
6710         return PSA_ERROR_INVALID_ARGUMENT;
6711     }
6712 
6713     if (status == PSA_SUCCESS) {
6714         operation->alg = alg;
6715     }
6716     return status;
6717 }
6718 
6719 #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)6720 static psa_status_t psa_hkdf_input(psa_hkdf_key_derivation_t *hkdf,
6721                                    psa_algorithm_t kdf_alg,
6722                                    psa_key_derivation_step_t step,
6723                                    const uint8_t *data,
6724                                    size_t data_length)
6725 {
6726     psa_algorithm_t hash_alg = PSA_ALG_HKDF_GET_HASH(kdf_alg);
6727     psa_status_t status;
6728     switch (step) {
6729         case PSA_KEY_DERIVATION_INPUT_SALT:
6730 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXPAND)
6731             if (PSA_ALG_IS_HKDF_EXPAND(kdf_alg)) {
6732                 return PSA_ERROR_INVALID_ARGUMENT;
6733             }
6734 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXPAND */
6735             if (hkdf->state != HKDF_STATE_INIT) {
6736                 return PSA_ERROR_BAD_STATE;
6737             } else {
6738                 status = psa_key_derivation_start_hmac(&hkdf->hmac,
6739                                                        hash_alg,
6740                                                        data, data_length);
6741                 if (status != PSA_SUCCESS) {
6742                     return status;
6743                 }
6744                 hkdf->state = HKDF_STATE_STARTED;
6745                 return PSA_SUCCESS;
6746             }
6747         case PSA_KEY_DERIVATION_INPUT_SECRET:
6748 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXPAND)
6749             if (PSA_ALG_IS_HKDF_EXPAND(kdf_alg)) {
6750                 /* We shouldn't be in different state as HKDF_EXPAND only allows
6751                  * two inputs: SECRET (this case) and INFO which does not modify
6752                  * the state. It could happen only if the hkdf
6753                  * object was corrupted. */
6754                 if (hkdf->state != HKDF_STATE_INIT) {
6755                     return PSA_ERROR_BAD_STATE;
6756                 }
6757 
6758                 /* Allow only input that fits expected prk size */
6759                 if (data_length != PSA_HASH_LENGTH(hash_alg)) {
6760                     return PSA_ERROR_INVALID_ARGUMENT;
6761                 }
6762 
6763                 memcpy(hkdf->prk, data, data_length);
6764             } else
6765 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXPAND */
6766             {
6767                 /* HKDF: If no salt was provided, use an empty salt.
6768                  * HKDF-EXTRACT: salt is mandatory. */
6769                 if (hkdf->state == HKDF_STATE_INIT) {
6770 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT)
6771                     if (PSA_ALG_IS_HKDF_EXTRACT(kdf_alg)) {
6772                         return PSA_ERROR_BAD_STATE;
6773                     }
6774 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT */
6775                     status = psa_key_derivation_start_hmac(&hkdf->hmac,
6776                                                            hash_alg,
6777                                                            NULL, 0);
6778                     if (status != PSA_SUCCESS) {
6779                         return status;
6780                     }
6781                     hkdf->state = HKDF_STATE_STARTED;
6782                 }
6783                 if (hkdf->state != HKDF_STATE_STARTED) {
6784                     return PSA_ERROR_BAD_STATE;
6785                 }
6786                 status = psa_mac_update(&hkdf->hmac,
6787                                         data, data_length);
6788                 if (status != PSA_SUCCESS) {
6789                     return status;
6790                 }
6791                 status = psa_mac_sign_finish(&hkdf->hmac,
6792                                              hkdf->prk,
6793                                              sizeof(hkdf->prk),
6794                                              &data_length);
6795                 if (status != PSA_SUCCESS) {
6796                     return status;
6797                 }
6798             }
6799 
6800             hkdf->state = HKDF_STATE_KEYED;
6801             hkdf->block_number = 0;
6802 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT)
6803             if (PSA_ALG_IS_HKDF_EXTRACT(kdf_alg)) {
6804                 /* The only block of output is the PRK. */
6805                 memcpy(hkdf->output_block, hkdf->prk, PSA_HASH_LENGTH(hash_alg));
6806                 hkdf->offset_in_block = 0;
6807             } else
6808 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT */
6809             {
6810                 /* Block 0 is empty, and the next block will be
6811                  * generated by psa_key_derivation_hkdf_read(). */
6812                 hkdf->offset_in_block = PSA_HASH_LENGTH(hash_alg);
6813             }
6814 
6815             return PSA_SUCCESS;
6816         case PSA_KEY_DERIVATION_INPUT_INFO:
6817 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT)
6818             if (PSA_ALG_IS_HKDF_EXTRACT(kdf_alg)) {
6819                 return PSA_ERROR_INVALID_ARGUMENT;
6820             }
6821 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT */
6822 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXPAND)
6823             if (PSA_ALG_IS_HKDF_EXPAND(kdf_alg) &&
6824                 hkdf->state == HKDF_STATE_INIT) {
6825                 return PSA_ERROR_BAD_STATE;
6826             }
6827 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT */
6828             if (hkdf->state == HKDF_STATE_OUTPUT) {
6829                 return PSA_ERROR_BAD_STATE;
6830             }
6831             if (hkdf->info_set) {
6832                 return PSA_ERROR_BAD_STATE;
6833             }
6834             hkdf->info_length = data_length;
6835             if (data_length != 0) {
6836                 hkdf->info = mbedtls_calloc(1, data_length);
6837                 if (hkdf->info == NULL) {
6838                     return PSA_ERROR_INSUFFICIENT_MEMORY;
6839                 }
6840                 memcpy(hkdf->info, data, data_length);
6841             }
6842             hkdf->info_set = 1;
6843             return PSA_SUCCESS;
6844         default:
6845             return PSA_ERROR_INVALID_ARGUMENT;
6846     }
6847 }
6848 #endif /* BUILTIN_ALG_ANY_HKDF */
6849 
6850 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
6851     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)6852 static psa_status_t psa_tls12_prf_set_seed(psa_tls12_prf_key_derivation_t *prf,
6853                                            const uint8_t *data,
6854                                            size_t data_length)
6855 {
6856     if (prf->state != PSA_TLS12_PRF_STATE_INIT) {
6857         return PSA_ERROR_BAD_STATE;
6858     }
6859 
6860     if (data_length != 0) {
6861         prf->seed = mbedtls_calloc(1, data_length);
6862         if (prf->seed == NULL) {
6863             return PSA_ERROR_INSUFFICIENT_MEMORY;
6864         }
6865 
6866         memcpy(prf->seed, data, data_length);
6867         prf->seed_length = data_length;
6868     }
6869 
6870     prf->state = PSA_TLS12_PRF_STATE_SEED_SET;
6871 
6872     return PSA_SUCCESS;
6873 }
6874 
psa_tls12_prf_set_key(psa_tls12_prf_key_derivation_t * prf,const uint8_t * data,size_t data_length)6875 static psa_status_t psa_tls12_prf_set_key(psa_tls12_prf_key_derivation_t *prf,
6876                                           const uint8_t *data,
6877                                           size_t data_length)
6878 {
6879     if (prf->state != PSA_TLS12_PRF_STATE_SEED_SET &&
6880         prf->state != PSA_TLS12_PRF_STATE_OTHER_KEY_SET) {
6881         return PSA_ERROR_BAD_STATE;
6882     }
6883 
6884     if (data_length != 0) {
6885         prf->secret = mbedtls_calloc(1, data_length);
6886         if (prf->secret == NULL) {
6887             return PSA_ERROR_INSUFFICIENT_MEMORY;
6888         }
6889 
6890         memcpy(prf->secret, data, data_length);
6891         prf->secret_length = data_length;
6892     }
6893 
6894     prf->state = PSA_TLS12_PRF_STATE_KEY_SET;
6895 
6896     return PSA_SUCCESS;
6897 }
6898 
psa_tls12_prf_set_label(psa_tls12_prf_key_derivation_t * prf,const uint8_t * data,size_t data_length)6899 static psa_status_t psa_tls12_prf_set_label(psa_tls12_prf_key_derivation_t *prf,
6900                                             const uint8_t *data,
6901                                             size_t data_length)
6902 {
6903     if (prf->state != PSA_TLS12_PRF_STATE_KEY_SET) {
6904         return PSA_ERROR_BAD_STATE;
6905     }
6906 
6907     if (data_length != 0) {
6908         prf->label = mbedtls_calloc(1, data_length);
6909         if (prf->label == NULL) {
6910             return PSA_ERROR_INSUFFICIENT_MEMORY;
6911         }
6912 
6913         memcpy(prf->label, data, data_length);
6914         prf->label_length = data_length;
6915     }
6916 
6917     prf->state = PSA_TLS12_PRF_STATE_LABEL_SET;
6918 
6919     return PSA_SUCCESS;
6920 }
6921 
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)6922 static psa_status_t psa_tls12_prf_input(psa_tls12_prf_key_derivation_t *prf,
6923                                         psa_key_derivation_step_t step,
6924                                         const uint8_t *data,
6925                                         size_t data_length)
6926 {
6927     switch (step) {
6928         case PSA_KEY_DERIVATION_INPUT_SEED:
6929             return psa_tls12_prf_set_seed(prf, data, data_length);
6930         case PSA_KEY_DERIVATION_INPUT_SECRET:
6931             return psa_tls12_prf_set_key(prf, data, data_length);
6932         case PSA_KEY_DERIVATION_INPUT_LABEL:
6933             return psa_tls12_prf_set_label(prf, data, data_length);
6934         default:
6935             return PSA_ERROR_INVALID_ARGUMENT;
6936     }
6937 }
6938 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) ||
6939         * MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
6940 
6941 #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)6942 static psa_status_t psa_tls12_prf_psk_to_ms_set_key(
6943     psa_tls12_prf_key_derivation_t *prf,
6944     const uint8_t *data,
6945     size_t data_length)
6946 {
6947     psa_status_t status;
6948     const size_t pms_len = (prf->state == PSA_TLS12_PRF_STATE_OTHER_KEY_SET ?
6949                             4 + data_length + prf->other_secret_length :
6950                             4 + 2 * data_length);
6951 
6952     if (data_length > PSA_TLS12_PSK_TO_MS_PSK_MAX_SIZE) {
6953         return PSA_ERROR_INVALID_ARGUMENT;
6954     }
6955 
6956     uint8_t *pms = mbedtls_calloc(1, pms_len);
6957     if (pms == NULL) {
6958         return PSA_ERROR_INSUFFICIENT_MEMORY;
6959     }
6960     uint8_t *cur = pms;
6961 
6962     /* pure-PSK:
6963      * Quoting RFC 4279, Section 2:
6964      *
6965      * The premaster secret is formed as follows: if the PSK is N octets
6966      * long, concatenate a uint16 with the value N, N zero octets, a second
6967      * uint16 with the value N, and the PSK itself.
6968      *
6969      * mixed-PSK:
6970      * In a DHE-PSK, RSA-PSK, ECDHE-PSK the premaster secret is formed as
6971      * follows: concatenate a uint16 with the length of the other secret,
6972      * the other secret itself, uint16 with the length of PSK, and the
6973      * PSK itself.
6974      * For details please check:
6975      * - RFC 4279, Section 4 for the definition of RSA-PSK,
6976      * - RFC 4279, Section 3 for the definition of DHE-PSK,
6977      * - RFC 5489 for the definition of ECDHE-PSK.
6978      */
6979 
6980     if (prf->state == PSA_TLS12_PRF_STATE_OTHER_KEY_SET) {
6981         *cur++ = MBEDTLS_BYTE_1(prf->other_secret_length);
6982         *cur++ = MBEDTLS_BYTE_0(prf->other_secret_length);
6983         if (prf->other_secret_length != 0) {
6984             memcpy(cur, prf->other_secret, prf->other_secret_length);
6985             mbedtls_platform_zeroize(prf->other_secret, prf->other_secret_length);
6986             cur += prf->other_secret_length;
6987         }
6988     } else {
6989         *cur++ = MBEDTLS_BYTE_1(data_length);
6990         *cur++ = MBEDTLS_BYTE_0(data_length);
6991         memset(cur, 0, data_length);
6992         cur += data_length;
6993     }
6994 
6995     *cur++ = MBEDTLS_BYTE_1(data_length);
6996     *cur++ = MBEDTLS_BYTE_0(data_length);
6997     memcpy(cur, data, data_length);
6998     cur += data_length;
6999 
7000     status = psa_tls12_prf_set_key(prf, pms, (size_t) (cur - pms));
7001 
7002     mbedtls_zeroize_and_free(pms, pms_len);
7003     return status;
7004 }
7005 
psa_tls12_prf_psk_to_ms_set_other_key(psa_tls12_prf_key_derivation_t * prf,const uint8_t * data,size_t data_length)7006 static psa_status_t psa_tls12_prf_psk_to_ms_set_other_key(
7007     psa_tls12_prf_key_derivation_t *prf,
7008     const uint8_t *data,
7009     size_t data_length)
7010 {
7011     if (prf->state != PSA_TLS12_PRF_STATE_SEED_SET) {
7012         return PSA_ERROR_BAD_STATE;
7013     }
7014 
7015     if (data_length != 0) {
7016         prf->other_secret = mbedtls_calloc(1, data_length);
7017         if (prf->other_secret == NULL) {
7018             return PSA_ERROR_INSUFFICIENT_MEMORY;
7019         }
7020 
7021         memcpy(prf->other_secret, data, data_length);
7022         prf->other_secret_length = data_length;
7023     } else {
7024         prf->other_secret_length = 0;
7025     }
7026 
7027     prf->state = PSA_TLS12_PRF_STATE_OTHER_KEY_SET;
7028 
7029     return PSA_SUCCESS;
7030 }
7031 
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)7032 static psa_status_t psa_tls12_prf_psk_to_ms_input(
7033     psa_tls12_prf_key_derivation_t *prf,
7034     psa_key_derivation_step_t step,
7035     const uint8_t *data,
7036     size_t data_length)
7037 {
7038     switch (step) {
7039         case PSA_KEY_DERIVATION_INPUT_SECRET:
7040             return psa_tls12_prf_psk_to_ms_set_key(prf,
7041                                                    data, data_length);
7042             break;
7043         case PSA_KEY_DERIVATION_INPUT_OTHER_SECRET:
7044             return psa_tls12_prf_psk_to_ms_set_other_key(prf,
7045                                                          data,
7046                                                          data_length);
7047             break;
7048         default:
7049             return psa_tls12_prf_input(prf, step, data, data_length);
7050             break;
7051 
7052     }
7053 }
7054 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
7055 
7056 #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)7057 static psa_status_t psa_tls12_ecjpake_to_pms_input(
7058     psa_tls12_ecjpake_to_pms_t *ecjpake,
7059     psa_key_derivation_step_t step,
7060     const uint8_t *data,
7061     size_t data_length)
7062 {
7063     if (data_length != PSA_TLS12_ECJPAKE_TO_PMS_INPUT_SIZE ||
7064         step != PSA_KEY_DERIVATION_INPUT_SECRET) {
7065         return PSA_ERROR_INVALID_ARGUMENT;
7066     }
7067 
7068     /* Check if the passed point is in an uncompressed form */
7069     if (data[0] != 0x04) {
7070         return PSA_ERROR_INVALID_ARGUMENT;
7071     }
7072 
7073     /* Only K.X has to be extracted - bytes 1 to 32 inclusive. */
7074     memcpy(ecjpake->data, data + 1, PSA_TLS12_ECJPAKE_TO_PMS_DATA_SIZE);
7075 
7076     return PSA_SUCCESS;
7077 }
7078 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS */
7079 
7080 #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)7081 static psa_status_t psa_pbkdf2_set_input_cost(
7082     psa_pbkdf2_key_derivation_t *pbkdf2,
7083     psa_key_derivation_step_t step,
7084     uint64_t data)
7085 {
7086     if (step != PSA_KEY_DERIVATION_INPUT_COST) {
7087         return PSA_ERROR_INVALID_ARGUMENT;
7088     }
7089 
7090     if (pbkdf2->state != PSA_PBKDF2_STATE_INIT) {
7091         return PSA_ERROR_BAD_STATE;
7092     }
7093 
7094     if (data > PSA_VENDOR_PBKDF2_MAX_ITERATIONS) {
7095         return PSA_ERROR_NOT_SUPPORTED;
7096     }
7097 
7098     if (data == 0) {
7099         return PSA_ERROR_INVALID_ARGUMENT;
7100     }
7101 
7102     pbkdf2->input_cost = data;
7103     pbkdf2->state = PSA_PBKDF2_STATE_INPUT_COST_SET;
7104 
7105     return PSA_SUCCESS;
7106 }
7107 
psa_pbkdf2_set_salt(psa_pbkdf2_key_derivation_t * pbkdf2,const uint8_t * data,size_t data_length)7108 static psa_status_t psa_pbkdf2_set_salt(psa_pbkdf2_key_derivation_t *pbkdf2,
7109                                         const uint8_t *data,
7110                                         size_t data_length)
7111 {
7112     if (pbkdf2->state == PSA_PBKDF2_STATE_INPUT_COST_SET) {
7113         pbkdf2->state = PSA_PBKDF2_STATE_SALT_SET;
7114     } else if (pbkdf2->state == PSA_PBKDF2_STATE_SALT_SET) {
7115         /* Appending to existing salt. No state change. */
7116     } else {
7117         return PSA_ERROR_BAD_STATE;
7118     }
7119 
7120     if (data_length == 0) {
7121         /* Appending an empty string, nothing to do. */
7122     } else {
7123         uint8_t *next_salt;
7124 
7125         next_salt = mbedtls_calloc(1, data_length + pbkdf2->salt_length);
7126         if (next_salt == NULL) {
7127             return PSA_ERROR_INSUFFICIENT_MEMORY;
7128         }
7129 
7130         if (pbkdf2->salt_length != 0) {
7131             memcpy(next_salt, pbkdf2->salt, pbkdf2->salt_length);
7132         }
7133         memcpy(next_salt + pbkdf2->salt_length, data, data_length);
7134         pbkdf2->salt_length += data_length;
7135         mbedtls_free(pbkdf2->salt);
7136         pbkdf2->salt = next_salt;
7137     }
7138     return PSA_SUCCESS;
7139 }
7140 
7141 #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)7142 static psa_status_t psa_pbkdf2_hmac_set_password(psa_algorithm_t hash_alg,
7143                                                  const uint8_t *input,
7144                                                  size_t input_len,
7145                                                  uint8_t *output,
7146                                                  size_t *output_len)
7147 {
7148     psa_status_t status = PSA_SUCCESS;
7149     if (input_len > PSA_HASH_BLOCK_LENGTH(hash_alg)) {
7150         return psa_hash_compute(hash_alg, input, input_len, output,
7151                                 PSA_HMAC_MAX_HASH_BLOCK_SIZE, output_len);
7152     } else if (input_len > 0) {
7153         memcpy(output, input, input_len);
7154     }
7155     *output_len = PSA_HASH_BLOCK_LENGTH(hash_alg);
7156     return status;
7157 }
7158 #endif /* MBEDTLS_PSA_BUILTIN_ALG_PBKDF2_HMAC */
7159 
7160 #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)7161 static psa_status_t psa_pbkdf2_cmac_set_password(const uint8_t *input,
7162                                                  size_t input_len,
7163                                                  uint8_t *output,
7164                                                  size_t *output_len)
7165 {
7166     psa_status_t status = PSA_SUCCESS;
7167     if (input_len != PSA_MAC_LENGTH(PSA_KEY_TYPE_AES, 128U, PSA_ALG_CMAC)) {
7168         psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
7169         uint8_t zeros[16] = { 0 };
7170         psa_set_key_type(&attributes, PSA_KEY_TYPE_AES);
7171         psa_set_key_bits(&attributes, PSA_BYTES_TO_BITS(sizeof(zeros)));
7172         psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_MESSAGE);
7173         /* Passing PSA_MAC_LENGTH(PSA_KEY_TYPE_AES, 128U, PSA_ALG_CMAC) as
7174          * mac_size as the driver function sets mac_output_length = mac_size
7175          * on success. See https://github.com/Mbed-TLS/mbedtls/issues/7801 */
7176         status = psa_driver_wrapper_mac_compute(&attributes,
7177                                                 zeros, sizeof(zeros),
7178                                                 PSA_ALG_CMAC, input, input_len,
7179                                                 output,
7180                                                 PSA_MAC_LENGTH(PSA_KEY_TYPE_AES,
7181                                                                128U,
7182                                                                PSA_ALG_CMAC),
7183                                                 output_len);
7184     } else {
7185         memcpy(output, input, input_len);
7186         *output_len = PSA_MAC_LENGTH(PSA_KEY_TYPE_AES, 128U, PSA_ALG_CMAC);
7187     }
7188     return status;
7189 }
7190 #endif /* MBEDTLS_PSA_BUILTIN_ALG_PBKDF2_AES_CMAC_PRF_128 */
7191 
psa_pbkdf2_set_password(psa_pbkdf2_key_derivation_t * pbkdf2,psa_algorithm_t kdf_alg,const uint8_t * data,size_t data_length)7192 static psa_status_t psa_pbkdf2_set_password(psa_pbkdf2_key_derivation_t *pbkdf2,
7193                                             psa_algorithm_t kdf_alg,
7194                                             const uint8_t *data,
7195                                             size_t data_length)
7196 {
7197     psa_status_t status = PSA_SUCCESS;
7198     if (pbkdf2->state != PSA_PBKDF2_STATE_SALT_SET) {
7199         return PSA_ERROR_BAD_STATE;
7200     }
7201 
7202 #if defined(MBEDTLS_PSA_BUILTIN_ALG_PBKDF2_HMAC)
7203     if (PSA_ALG_IS_PBKDF2_HMAC(kdf_alg)) {
7204         psa_algorithm_t hash_alg = PSA_ALG_PBKDF2_HMAC_GET_HASH(kdf_alg);
7205         status = psa_pbkdf2_hmac_set_password(hash_alg, data, data_length,
7206                                               pbkdf2->password,
7207                                               &pbkdf2->password_length);
7208     } else
7209 #endif /* MBEDTLS_PSA_BUILTIN_ALG_PBKDF2_HMAC */
7210 #if defined(MBEDTLS_PSA_BUILTIN_ALG_PBKDF2_AES_CMAC_PRF_128)
7211     if (kdf_alg == PSA_ALG_PBKDF2_AES_CMAC_PRF_128) {
7212         status = psa_pbkdf2_cmac_set_password(data, data_length,
7213                                               pbkdf2->password,
7214                                               &pbkdf2->password_length);
7215     } else
7216 #endif /* MBEDTLS_PSA_BUILTIN_ALG_PBKDF2_AES_CMAC_PRF_128 */
7217     {
7218         return PSA_ERROR_INVALID_ARGUMENT;
7219     }
7220 
7221     pbkdf2->state = PSA_PBKDF2_STATE_PASSWORD_SET;
7222 
7223     return status;
7224 }
7225 
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)7226 static psa_status_t psa_pbkdf2_input(psa_pbkdf2_key_derivation_t *pbkdf2,
7227                                      psa_algorithm_t kdf_alg,
7228                                      psa_key_derivation_step_t step,
7229                                      const uint8_t *data,
7230                                      size_t data_length)
7231 {
7232     switch (step) {
7233         case PSA_KEY_DERIVATION_INPUT_SALT:
7234             return psa_pbkdf2_set_salt(pbkdf2, data, data_length);
7235         case PSA_KEY_DERIVATION_INPUT_PASSWORD:
7236             return psa_pbkdf2_set_password(pbkdf2, kdf_alg, data, data_length);
7237         default:
7238             return PSA_ERROR_INVALID_ARGUMENT;
7239     }
7240 }
7241 #endif /* PSA_HAVE_SOFT_PBKDF2 */
7242 
7243 /** Check whether the given key type is acceptable for the given
7244  * input step of a key derivation.
7245  *
7246  * Secret inputs must have the type #PSA_KEY_TYPE_DERIVE.
7247  * Non-secret inputs must have the type #PSA_KEY_TYPE_RAW_DATA.
7248  * Both secret and non-secret inputs can alternatively have the type
7249  * #PSA_KEY_TYPE_NONE, which is never the type of a key object, meaning
7250  * that the input was passed as a buffer rather than via a key object.
7251  */
psa_key_derivation_check_input_type(psa_key_derivation_step_t step,psa_key_type_t key_type)7252 static int psa_key_derivation_check_input_type(
7253     psa_key_derivation_step_t step,
7254     psa_key_type_t key_type)
7255 {
7256     switch (step) {
7257         case PSA_KEY_DERIVATION_INPUT_SECRET:
7258             if (key_type == PSA_KEY_TYPE_DERIVE) {
7259                 return PSA_SUCCESS;
7260             }
7261             if (key_type == PSA_KEY_TYPE_NONE) {
7262                 return PSA_SUCCESS;
7263             }
7264             break;
7265         case PSA_KEY_DERIVATION_INPUT_OTHER_SECRET:
7266             if (key_type == PSA_KEY_TYPE_DERIVE) {
7267                 return PSA_SUCCESS;
7268             }
7269             if (key_type == PSA_KEY_TYPE_NONE) {
7270                 return PSA_SUCCESS;
7271             }
7272             break;
7273         case PSA_KEY_DERIVATION_INPUT_LABEL:
7274         case PSA_KEY_DERIVATION_INPUT_SALT:
7275         case PSA_KEY_DERIVATION_INPUT_INFO:
7276         case PSA_KEY_DERIVATION_INPUT_SEED:
7277             if (key_type == PSA_KEY_TYPE_RAW_DATA) {
7278                 return PSA_SUCCESS;
7279             }
7280             if (key_type == PSA_KEY_TYPE_NONE) {
7281                 return PSA_SUCCESS;
7282             }
7283             break;
7284         case PSA_KEY_DERIVATION_INPUT_PASSWORD:
7285             if (key_type == PSA_KEY_TYPE_PASSWORD) {
7286                 return PSA_SUCCESS;
7287             }
7288             if (key_type == PSA_KEY_TYPE_DERIVE) {
7289                 return PSA_SUCCESS;
7290             }
7291             if (key_type == PSA_KEY_TYPE_NONE) {
7292                 return PSA_SUCCESS;
7293             }
7294             break;
7295     }
7296     return PSA_ERROR_INVALID_ARGUMENT;
7297 }
7298 
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)7299 static psa_status_t psa_key_derivation_input_internal(
7300     psa_key_derivation_operation_t *operation,
7301     psa_key_derivation_step_t step,
7302     psa_key_type_t key_type,
7303     const uint8_t *data,
7304     size_t data_length)
7305 {
7306     psa_status_t status;
7307     psa_algorithm_t kdf_alg = psa_key_derivation_get_kdf_alg(operation);
7308 
7309     status = psa_key_derivation_check_input_type(step, key_type);
7310     if (status != PSA_SUCCESS) {
7311         goto exit;
7312     }
7313 
7314 #if defined(BUILTIN_ALG_ANY_HKDF)
7315     if (PSA_ALG_IS_ANY_HKDF(kdf_alg)) {
7316         status = psa_hkdf_input(&operation->ctx.hkdf, kdf_alg,
7317                                 step, data, data_length);
7318     } else
7319 #endif /* BUILTIN_ALG_ANY_HKDF */
7320 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF)
7321     if (PSA_ALG_IS_TLS12_PRF(kdf_alg)) {
7322         status = psa_tls12_prf_input(&operation->ctx.tls12_prf,
7323                                      step, data, data_length);
7324     } else
7325 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF */
7326 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
7327     if (PSA_ALG_IS_TLS12_PSK_TO_MS(kdf_alg)) {
7328         status = psa_tls12_prf_psk_to_ms_input(&operation->ctx.tls12_prf,
7329                                                step, data, data_length);
7330     } else
7331 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
7332 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS)
7333     if (kdf_alg == PSA_ALG_TLS12_ECJPAKE_TO_PMS) {
7334         status = psa_tls12_ecjpake_to_pms_input(
7335             &operation->ctx.tls12_ecjpake_to_pms, step, data, data_length);
7336     } else
7337 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS */
7338 #if defined(PSA_HAVE_SOFT_PBKDF2)
7339     if (PSA_ALG_IS_PBKDF2(kdf_alg)) {
7340         status = psa_pbkdf2_input(&operation->ctx.pbkdf2, kdf_alg,
7341                                   step, data, data_length);
7342     } else
7343 #endif /* PSA_HAVE_SOFT_PBKDF2 */
7344     {
7345         /* This can't happen unless the operation object was not initialized */
7346         (void) data;
7347         (void) data_length;
7348         (void) kdf_alg;
7349         return PSA_ERROR_BAD_STATE;
7350     }
7351 
7352 exit:
7353     if (status != PSA_SUCCESS) {
7354         psa_key_derivation_abort(operation);
7355     }
7356     return status;
7357 }
7358 
psa_key_derivation_input_integer_internal(psa_key_derivation_operation_t * operation,psa_key_derivation_step_t step,uint64_t value)7359 static psa_status_t psa_key_derivation_input_integer_internal(
7360     psa_key_derivation_operation_t *operation,
7361     psa_key_derivation_step_t step,
7362     uint64_t value)
7363 {
7364     psa_status_t status;
7365     psa_algorithm_t kdf_alg = psa_key_derivation_get_kdf_alg(operation);
7366 
7367 #if defined(PSA_HAVE_SOFT_PBKDF2)
7368     if (PSA_ALG_IS_PBKDF2(kdf_alg)) {
7369         status = psa_pbkdf2_set_input_cost(
7370             &operation->ctx.pbkdf2, step, value);
7371     } else
7372 #endif /* PSA_HAVE_SOFT_PBKDF2 */
7373     {
7374         (void) step;
7375         (void) value;
7376         (void) kdf_alg;
7377         status = PSA_ERROR_INVALID_ARGUMENT;
7378     }
7379 
7380     if (status != PSA_SUCCESS) {
7381         psa_key_derivation_abort(operation);
7382     }
7383     return status;
7384 }
7385 
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)7386 psa_status_t psa_key_derivation_input_bytes(
7387     psa_key_derivation_operation_t *operation,
7388     psa_key_derivation_step_t step,
7389     const uint8_t *data_external,
7390     size_t data_length)
7391 {
7392     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
7393     LOCAL_INPUT_DECLARE(data_external, data);
7394 
7395     LOCAL_INPUT_ALLOC(data_external, data_length, data);
7396 
7397     status = psa_key_derivation_input_internal(operation, step,
7398                                                PSA_KEY_TYPE_NONE,
7399                                                data, data_length);
7400 #if !defined(MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS)
7401 exit:
7402 #endif
7403     LOCAL_INPUT_FREE(data_external, data);
7404     return status;
7405 }
7406 
psa_key_derivation_input_integer(psa_key_derivation_operation_t * operation,psa_key_derivation_step_t step,uint64_t value)7407 psa_status_t psa_key_derivation_input_integer(
7408     psa_key_derivation_operation_t *operation,
7409     psa_key_derivation_step_t step,
7410     uint64_t value)
7411 {
7412     return psa_key_derivation_input_integer_internal(operation, step, value);
7413 }
7414 
psa_key_derivation_input_key(psa_key_derivation_operation_t * operation,psa_key_derivation_step_t step,mbedtls_svc_key_id_t key)7415 psa_status_t psa_key_derivation_input_key(
7416     psa_key_derivation_operation_t *operation,
7417     psa_key_derivation_step_t step,
7418     mbedtls_svc_key_id_t key)
7419 {
7420     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
7421     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
7422     psa_key_slot_t *slot;
7423 
7424     status = psa_get_and_lock_transparent_key_slot_with_policy(
7425         key, &slot, PSA_KEY_USAGE_DERIVE, operation->alg);
7426     if (status != PSA_SUCCESS) {
7427         psa_key_derivation_abort(operation);
7428         return status;
7429     }
7430 
7431     /* Passing a key object as a SECRET or PASSWORD input unlocks the
7432      * permission to output to a key object. */
7433     if (step == PSA_KEY_DERIVATION_INPUT_SECRET ||
7434         step == PSA_KEY_DERIVATION_INPUT_PASSWORD) {
7435         operation->can_output_key = 1;
7436     }
7437 
7438     status = psa_key_derivation_input_internal(operation,
7439                                                step, slot->attr.type,
7440                                                slot->key.data,
7441                                                slot->key.bytes);
7442 
7443     unlock_status = psa_unregister_read_under_mutex(slot);
7444 
7445     return (status == PSA_SUCCESS) ? unlock_status : status;
7446 }
7447 
7448 
7449 
7450 /****************************************************************/
7451 /* Key agreement */
7452 /****************************************************************/
7453 
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)7454 psa_status_t psa_key_agreement_raw_builtin(const psa_key_attributes_t *attributes,
7455                                            const uint8_t *key_buffer,
7456                                            size_t key_buffer_size,
7457                                            psa_algorithm_t alg,
7458                                            const uint8_t *peer_key,
7459                                            size_t peer_key_length,
7460                                            uint8_t *shared_secret,
7461                                            size_t shared_secret_size,
7462                                            size_t *shared_secret_length)
7463 {
7464     switch (alg) {
7465 #if defined(MBEDTLS_PSA_BUILTIN_ALG_ECDH)
7466         case PSA_ALG_ECDH:
7467             return mbedtls_psa_key_agreement_ecdh(attributes, key_buffer,
7468                                                   key_buffer_size, alg,
7469                                                   peer_key, peer_key_length,
7470                                                   shared_secret,
7471                                                   shared_secret_size,
7472                                                   shared_secret_length);
7473 #endif /* MBEDTLS_PSA_BUILTIN_ALG_ECDH */
7474 
7475 #if defined(MBEDTLS_PSA_BUILTIN_ALG_FFDH)
7476         case PSA_ALG_FFDH:
7477             return mbedtls_psa_ffdh_key_agreement(attributes,
7478                                                   peer_key,
7479                                                   peer_key_length,
7480                                                   key_buffer,
7481                                                   key_buffer_size,
7482                                                   shared_secret,
7483                                                   shared_secret_size,
7484                                                   shared_secret_length);
7485 #endif /* MBEDTLS_PSA_BUILTIN_ALG_FFDH */
7486 
7487         default:
7488             (void) attributes;
7489             (void) key_buffer;
7490             (void) key_buffer_size;
7491             (void) peer_key;
7492             (void) peer_key_length;
7493             (void) shared_secret;
7494             (void) shared_secret_size;
7495             (void) shared_secret_length;
7496             return PSA_ERROR_NOT_SUPPORTED;
7497     }
7498 }
7499 
7500 /** Internal function for raw key agreement
7501  *  Calls the driver wrapper which will hand off key agreement task
7502  *  to the driver's implementation if a driver is present.
7503  *  Fallback specified in the driver wrapper is built-in raw key agreement
7504  *  (psa_key_agreement_raw_builtin).
7505  */
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)7506 static psa_status_t psa_key_agreement_raw_internal(psa_algorithm_t alg,
7507                                                    psa_key_slot_t *private_key,
7508                                                    const uint8_t *peer_key,
7509                                                    size_t peer_key_length,
7510                                                    uint8_t *shared_secret,
7511                                                    size_t shared_secret_size,
7512                                                    size_t *shared_secret_length)
7513 {
7514     if (!PSA_ALG_IS_RAW_KEY_AGREEMENT(alg)) {
7515         return PSA_ERROR_NOT_SUPPORTED;
7516     }
7517 
7518     return psa_driver_wrapper_key_agreement(&private_key->attr,
7519                                             private_key->key.data,
7520                                             private_key->key.bytes, alg,
7521                                             peer_key, peer_key_length,
7522                                             shared_secret,
7523                                             shared_secret_size,
7524                                             shared_secret_length);
7525 }
7526 
7527 /* Note that if this function fails, you must call psa_key_derivation_abort()
7528  * to potentially free embedded data structures and wipe confidential data.
7529  */
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)7530 static psa_status_t psa_key_agreement_internal(psa_key_derivation_operation_t *operation,
7531                                                psa_key_derivation_step_t step,
7532                                                psa_key_slot_t *private_key,
7533                                                const uint8_t *peer_key,
7534                                                size_t peer_key_length)
7535 {
7536     psa_status_t status;
7537     uint8_t shared_secret[PSA_RAW_KEY_AGREEMENT_OUTPUT_MAX_SIZE] = { 0 };
7538     size_t shared_secret_length = 0;
7539     psa_algorithm_t ka_alg = PSA_ALG_KEY_AGREEMENT_GET_BASE(operation->alg);
7540 
7541     /* Step 1: run the secret agreement algorithm to generate the shared
7542      * secret. */
7543     status = psa_key_agreement_raw_internal(ka_alg,
7544                                             private_key,
7545                                             peer_key, peer_key_length,
7546                                             shared_secret,
7547                                             sizeof(shared_secret),
7548                                             &shared_secret_length);
7549     if (status != PSA_SUCCESS) {
7550         goto exit;
7551     }
7552 
7553     /* Step 2: set up the key derivation to generate key material from
7554      * the shared secret. A shared secret is permitted wherever a key
7555      * of type DERIVE is permitted. */
7556     status = psa_key_derivation_input_internal(operation, step,
7557                                                PSA_KEY_TYPE_DERIVE,
7558                                                shared_secret,
7559                                                shared_secret_length);
7560 exit:
7561     mbedtls_platform_zeroize(shared_secret, shared_secret_length);
7562     return status;
7563 }
7564 
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)7565 psa_status_t psa_key_derivation_key_agreement(psa_key_derivation_operation_t *operation,
7566                                               psa_key_derivation_step_t step,
7567                                               mbedtls_svc_key_id_t private_key,
7568                                               const uint8_t *peer_key_external,
7569                                               size_t peer_key_length)
7570 {
7571     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
7572     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
7573     psa_key_slot_t *slot;
7574     LOCAL_INPUT_DECLARE(peer_key_external, peer_key);
7575 
7576     if (!PSA_ALG_IS_KEY_AGREEMENT(operation->alg)) {
7577         return PSA_ERROR_INVALID_ARGUMENT;
7578     }
7579     status = psa_get_and_lock_transparent_key_slot_with_policy(
7580         private_key, &slot, PSA_KEY_USAGE_DERIVE, operation->alg);
7581     if (status != PSA_SUCCESS) {
7582         return status;
7583     }
7584 
7585     LOCAL_INPUT_ALLOC(peer_key_external, peer_key_length, peer_key);
7586     status = psa_key_agreement_internal(operation, step,
7587                                         slot,
7588                                         peer_key, peer_key_length);
7589 
7590 #if !defined(MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS)
7591 exit:
7592 #endif
7593     if (status != PSA_SUCCESS) {
7594         psa_key_derivation_abort(operation);
7595     } else {
7596         /* If a private key has been added as SECRET, we allow the derived
7597          * key material to be used as a key in PSA Crypto. */
7598         if (step == PSA_KEY_DERIVATION_INPUT_SECRET) {
7599             operation->can_output_key = 1;
7600         }
7601     }
7602 
7603     unlock_status = psa_unregister_read_under_mutex(slot);
7604     LOCAL_INPUT_FREE(peer_key_external, peer_key);
7605 
7606     return (status == PSA_SUCCESS) ? unlock_status : status;
7607 }
7608 
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)7609 psa_status_t psa_raw_key_agreement(psa_algorithm_t alg,
7610                                    mbedtls_svc_key_id_t private_key,
7611                                    const uint8_t *peer_key_external,
7612                                    size_t peer_key_length,
7613                                    uint8_t *output_external,
7614                                    size_t output_size,
7615                                    size_t *output_length)
7616 {
7617     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
7618     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
7619     psa_key_slot_t *slot = NULL;
7620     size_t expected_length;
7621     LOCAL_INPUT_DECLARE(peer_key_external, peer_key);
7622     LOCAL_OUTPUT_DECLARE(output_external, output);
7623     LOCAL_OUTPUT_ALLOC(output_external, output_size, output);
7624 
7625     if (!PSA_ALG_IS_KEY_AGREEMENT(alg)) {
7626         status = PSA_ERROR_INVALID_ARGUMENT;
7627         goto exit;
7628     }
7629     status = psa_get_and_lock_transparent_key_slot_with_policy(
7630         private_key, &slot, PSA_KEY_USAGE_DERIVE, alg);
7631     if (status != PSA_SUCCESS) {
7632         goto exit;
7633     }
7634 
7635     /* PSA_RAW_KEY_AGREEMENT_OUTPUT_SIZE() is in general an upper bound
7636      * for the output size. The PSA specification only guarantees that this
7637      * function works if output_size >= PSA_RAW_KEY_AGREEMENT_OUTPUT_SIZE(...),
7638      * but it might be nice to allow smaller buffers if the output fits.
7639      * At the time of writing this comment, with only ECDH implemented,
7640      * PSA_RAW_KEY_AGREEMENT_OUTPUT_SIZE() is exact so the point is moot.
7641      * If FFDH is implemented, PSA_RAW_KEY_AGREEMENT_OUTPUT_SIZE() can easily
7642      * be exact for it as well. */
7643     expected_length =
7644         PSA_RAW_KEY_AGREEMENT_OUTPUT_SIZE(slot->attr.type, slot->attr.bits);
7645     if (output_size < expected_length) {
7646         status = PSA_ERROR_BUFFER_TOO_SMALL;
7647         goto exit;
7648     }
7649 
7650     LOCAL_INPUT_ALLOC(peer_key_external, peer_key_length, peer_key);
7651     status = psa_key_agreement_raw_internal(alg, slot,
7652                                             peer_key, peer_key_length,
7653                                             output, output_size,
7654                                             output_length);
7655 
7656 exit:
7657     /* Check for successful allocation of output,
7658      * with an unsuccessful status. */
7659     if (output != NULL && status != PSA_SUCCESS) {
7660         /* If an error happens and is not handled properly, the output
7661          * may be used as a key to protect sensitive data. Arrange for such
7662          * a key to be random, which is likely to result in decryption or
7663          * verification errors. This is better than filling the buffer with
7664          * some constant data such as zeros, which would result in the data
7665          * being protected with a reproducible, easily knowable key.
7666          */
7667         psa_generate_random_internal(output, output_size);
7668         *output_length = output_size;
7669     }
7670 
7671     if (output == NULL) {
7672         /* output allocation failed. */
7673         *output_length = 0;
7674     }
7675 
7676     unlock_status = psa_unregister_read_under_mutex(slot);
7677 
7678     LOCAL_INPUT_FREE(peer_key_external, peer_key);
7679     LOCAL_OUTPUT_FREE(output_external, output);
7680     return (status == PSA_SUCCESS) ? unlock_status : status;
7681 }
7682 
7683 
7684 /****************************************************************/
7685 /* Random generation */
7686 /****************************************************************/
7687 
7688 #if defined(MBEDTLS_PSA_INJECT_ENTROPY)
7689 #include "entropy_poll.h"
7690 #endif
7691 
7692 /** Initialize the PSA random generator.
7693  *
7694  *  Note: the mbedtls_threading_psa_rngdata_mutex should be held when calling
7695  *  this function if mutexes are enabled.
7696  */
mbedtls_psa_random_init(mbedtls_psa_random_context_t * rng)7697 static void mbedtls_psa_random_init(mbedtls_psa_random_context_t *rng)
7698 {
7699 #if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
7700     memset(rng, 0, sizeof(*rng));
7701 #else /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
7702 
7703     /* Set default configuration if
7704      * mbedtls_psa_crypto_configure_entropy_sources() hasn't been called. */
7705     if (rng->entropy_init == NULL) {
7706         rng->entropy_init = mbedtls_entropy_init;
7707     }
7708     if (rng->entropy_free == NULL) {
7709         rng->entropy_free = mbedtls_entropy_free;
7710     }
7711 
7712     rng->entropy_init(&rng->entropy);
7713 #if defined(MBEDTLS_PSA_INJECT_ENTROPY) && \
7714     defined(MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES)
7715     /* The PSA entropy injection feature depends on using NV seed as an entropy
7716      * source. Add NV seed as an entropy source for PSA entropy injection. */
7717     mbedtls_entropy_add_source(&rng->entropy,
7718                                mbedtls_nv_seed_poll, NULL,
7719                                MBEDTLS_ENTROPY_BLOCK_SIZE,
7720                                MBEDTLS_ENTROPY_SOURCE_STRONG);
7721 #endif
7722 
7723     mbedtls_psa_drbg_init(&rng->drbg);
7724 #endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
7725 }
7726 
7727 /** Deinitialize the PSA random generator.
7728  *
7729  *  Note: the mbedtls_threading_psa_rngdata_mutex should be held when calling
7730  *  this function if mutexes are enabled.
7731  */
mbedtls_psa_random_free(mbedtls_psa_random_context_t * rng)7732 static void mbedtls_psa_random_free(mbedtls_psa_random_context_t *rng)
7733 {
7734 #if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
7735     memset(rng, 0, sizeof(*rng));
7736 #else /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
7737     mbedtls_psa_drbg_free(&rng->drbg);
7738     rng->entropy_free(&rng->entropy);
7739 #endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
7740 }
7741 
7742 /** Seed the PSA random generator.
7743  */
mbedtls_psa_random_seed(mbedtls_psa_random_context_t * rng)7744 static psa_status_t mbedtls_psa_random_seed(mbedtls_psa_random_context_t *rng)
7745 {
7746 #if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
7747     /* Do nothing: the external RNG seeds itself. */
7748     (void) rng;
7749     return PSA_SUCCESS;
7750 #else /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
7751     const unsigned char drbg_seed[] = "PSA";
7752     int ret = mbedtls_psa_drbg_seed(&rng->drbg, &rng->entropy,
7753                                     drbg_seed, sizeof(drbg_seed) - 1);
7754     return mbedtls_to_psa_error(ret);
7755 #endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
7756 }
7757 
psa_generate_random(uint8_t * output_external,size_t output_size)7758 psa_status_t psa_generate_random(uint8_t *output_external,
7759                                  size_t output_size)
7760 {
7761     psa_status_t status;
7762 
7763     LOCAL_OUTPUT_DECLARE(output_external, output);
7764     LOCAL_OUTPUT_ALLOC(output_external, output_size, output);
7765 
7766     status = psa_generate_random_internal(output, output_size);
7767 
7768 #if !defined(MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS)
7769 exit:
7770 #endif
7771     LOCAL_OUTPUT_FREE(output_external, output);
7772     return status;
7773 }
7774 
7775 #if defined(MBEDTLS_PSA_INJECT_ENTROPY)
mbedtls_psa_inject_entropy(const uint8_t * seed,size_t seed_size)7776 psa_status_t mbedtls_psa_inject_entropy(const uint8_t *seed,
7777                                         size_t seed_size)
7778 {
7779     if (psa_get_initialized()) {
7780         return PSA_ERROR_NOT_PERMITTED;
7781     }
7782 
7783     if (((seed_size < MBEDTLS_ENTROPY_MIN_PLATFORM) ||
7784          (seed_size < MBEDTLS_ENTROPY_BLOCK_SIZE)) ||
7785         (seed_size > MBEDTLS_ENTROPY_MAX_SEED_SIZE)) {
7786         return PSA_ERROR_INVALID_ARGUMENT;
7787     }
7788 
7789     return mbedtls_psa_storage_inject_entropy(seed, seed_size);
7790 }
7791 #endif /* MBEDTLS_PSA_INJECT_ENTROPY */
7792 
7793 /** Validate the key type and size for key generation
7794  *
7795  * \param  type  The key type
7796  * \param  bits  The number of bits of the key
7797  *
7798  * \retval #PSA_SUCCESS
7799  *         The key type and size are valid.
7800  * \retval #PSA_ERROR_INVALID_ARGUMENT
7801  *         The size in bits of the key is not valid.
7802  * \retval #PSA_ERROR_NOT_SUPPORTED
7803  *         The type and/or the size in bits of the key or the combination of
7804  *         the two is not supported.
7805  */
psa_validate_key_type_and_size_for_key_generation(psa_key_type_t type,size_t bits)7806 static psa_status_t psa_validate_key_type_and_size_for_key_generation(
7807     psa_key_type_t type, size_t bits)
7808 {
7809     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
7810 
7811     if (key_type_is_raw_bytes(type)) {
7812         status = psa_validate_unstructured_key_bit_size(type, bits);
7813         if (status != PSA_SUCCESS) {
7814             return status;
7815         }
7816     } else
7817 #if defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_GENERATE)
7818     if (PSA_KEY_TYPE_IS_RSA(type) && PSA_KEY_TYPE_IS_KEY_PAIR(type)) {
7819         if (bits > PSA_VENDOR_RSA_MAX_KEY_BITS) {
7820             return PSA_ERROR_NOT_SUPPORTED;
7821         }
7822         if (bits < PSA_VENDOR_RSA_GENERATE_MIN_KEY_BITS) {
7823             return PSA_ERROR_NOT_SUPPORTED;
7824         }
7825 
7826         /* Accept only byte-aligned keys, for the same reasons as
7827          * in psa_import_rsa_key(). */
7828         if (bits % 8 != 0) {
7829             return PSA_ERROR_NOT_SUPPORTED;
7830         }
7831     } else
7832 #endif /* defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_GENERATE) */
7833 
7834 #if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_GENERATE)
7835     if (PSA_KEY_TYPE_IS_ECC(type) && PSA_KEY_TYPE_IS_KEY_PAIR(type)) {
7836         /* To avoid empty block, return successfully here. */
7837         return PSA_SUCCESS;
7838     } else
7839 #endif /* defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_GENERATE) */
7840 
7841 #if defined(PSA_WANT_KEY_TYPE_DH_KEY_PAIR_GENERATE)
7842     if (PSA_KEY_TYPE_IS_DH(type) && PSA_KEY_TYPE_IS_KEY_PAIR(type)) {
7843         if (psa_is_dh_key_size_valid(bits) == 0) {
7844             return PSA_ERROR_NOT_SUPPORTED;
7845         }
7846     } else
7847 #endif /* defined(PSA_WANT_KEY_TYPE_DH_KEY_PAIR_GENERATE) */
7848     {
7849         return PSA_ERROR_NOT_SUPPORTED;
7850     }
7851 
7852     return PSA_SUCCESS;
7853 }
7854 
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)7855 psa_status_t psa_generate_key_internal(
7856     const psa_key_attributes_t *attributes,
7857     const psa_key_production_parameters_t *params, size_t params_data_length,
7858     uint8_t *key_buffer, size_t key_buffer_size, size_t *key_buffer_length)
7859 {
7860     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
7861     psa_key_type_t type = attributes->type;
7862 
7863     /* Only used for RSA */
7864     (void) params;
7865     (void) params_data_length;
7866 
7867     if (key_type_is_raw_bytes(type)) {
7868         status = psa_generate_random_internal(key_buffer, key_buffer_size);
7869         if (status != PSA_SUCCESS) {
7870             return status;
7871         }
7872 
7873 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES)
7874         if (type == PSA_KEY_TYPE_DES) {
7875             psa_des_set_key_parity(key_buffer, key_buffer_size);
7876         }
7877 #endif /* MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES */
7878     } else
7879 
7880 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_GENERATE)
7881     if (type == PSA_KEY_TYPE_RSA_KEY_PAIR) {
7882         return mbedtls_psa_rsa_generate_key(attributes,
7883                                             params, params_data_length,
7884                                             key_buffer,
7885                                             key_buffer_size,
7886                                             key_buffer_length);
7887     } else
7888 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_GENERATE) */
7889 
7890 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_GENERATE)
7891     if (PSA_KEY_TYPE_IS_ECC(type) && PSA_KEY_TYPE_IS_KEY_PAIR(type)) {
7892         return mbedtls_psa_ecp_generate_key(attributes,
7893                                             key_buffer,
7894                                             key_buffer_size,
7895                                             key_buffer_length);
7896     } else
7897 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_GENERATE) */
7898 
7899 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_KEY_PAIR_GENERATE)
7900     if (PSA_KEY_TYPE_IS_DH(type) && PSA_KEY_TYPE_IS_KEY_PAIR(type)) {
7901         return mbedtls_psa_ffdh_generate_key(attributes,
7902                                              key_buffer,
7903                                              key_buffer_size,
7904                                              key_buffer_length);
7905     } else
7906 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_KEY_PAIR_GENERATE) */
7907     {
7908         (void) key_buffer_length;
7909         return PSA_ERROR_NOT_SUPPORTED;
7910     }
7911 
7912     return PSA_SUCCESS;
7913 }
7914 
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)7915 psa_status_t psa_generate_key_ext(const psa_key_attributes_t *attributes,
7916                                   const psa_key_production_parameters_t *params,
7917                                   size_t params_data_length,
7918                                   mbedtls_svc_key_id_t *key)
7919 {
7920     psa_status_t status;
7921     psa_key_slot_t *slot = NULL;
7922     psa_se_drv_table_entry_t *driver = NULL;
7923     size_t key_buffer_size;
7924 
7925     *key = MBEDTLS_SVC_KEY_ID_INIT;
7926 
7927     /* Reject any attempt to create a zero-length key so that we don't
7928      * risk tripping up later, e.g. on a malloc(0) that returns NULL. */
7929     if (psa_get_key_bits(attributes) == 0) {
7930         return PSA_ERROR_INVALID_ARGUMENT;
7931     }
7932 
7933     /* Reject any attempt to create a public key. */
7934     if (PSA_KEY_TYPE_IS_PUBLIC_KEY(attributes->type)) {
7935         return PSA_ERROR_INVALID_ARGUMENT;
7936     }
7937 
7938 #if defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_GENERATE)
7939     if (attributes->type == PSA_KEY_TYPE_RSA_KEY_PAIR) {
7940         if (params->flags != 0) {
7941             return PSA_ERROR_INVALID_ARGUMENT;
7942         }
7943     } else
7944 #endif
7945     if (!psa_key_production_parameters_are_default(params, params_data_length)) {
7946         return PSA_ERROR_INVALID_ARGUMENT;
7947     }
7948 
7949     status = psa_start_key_creation(PSA_KEY_CREATION_GENERATE, attributes,
7950                                     &slot, &driver);
7951     if (status != PSA_SUCCESS) {
7952         goto exit;
7953     }
7954 
7955     /* In the case of a transparent key or an opaque key stored in local
7956      * storage ( thus not in the case of generating a key in a secure element
7957      * with storage ( MBEDTLS_PSA_CRYPTO_SE_C ) ),we have to allocate a
7958      * buffer to hold the generated key material. */
7959     if (slot->key.data == NULL) {
7960         if (PSA_KEY_LIFETIME_GET_LOCATION(attributes->lifetime) ==
7961             PSA_KEY_LOCATION_LOCAL_STORAGE) {
7962             status = psa_validate_key_type_and_size_for_key_generation(
7963                 attributes->type, attributes->bits);
7964             if (status != PSA_SUCCESS) {
7965                 goto exit;
7966             }
7967 
7968             key_buffer_size = PSA_EXPORT_KEY_OUTPUT_SIZE(
7969                 attributes->type,
7970                 attributes->bits);
7971         } else {
7972             status = psa_driver_wrapper_get_key_buffer_size(
7973                 attributes, &key_buffer_size);
7974             if (status != PSA_SUCCESS) {
7975                 goto exit;
7976             }
7977         }
7978 
7979         status = psa_allocate_buffer_to_slot(slot, key_buffer_size);
7980         if (status != PSA_SUCCESS) {
7981             goto exit;
7982         }
7983     }
7984 
7985     status = psa_driver_wrapper_generate_key(attributes,
7986                                              params, params_data_length,
7987                                              slot->key.data, slot->key.bytes,
7988                                              &slot->key.bytes);
7989     if (status != PSA_SUCCESS) {
7990         psa_remove_key_data_from_memory(slot);
7991     }
7992 
7993 exit:
7994     if (status == PSA_SUCCESS) {
7995         status = psa_finish_key_creation(slot, driver, key);
7996     }
7997     if (status != PSA_SUCCESS) {
7998         psa_fail_key_creation(slot, driver);
7999     }
8000 
8001     return status;
8002 }
8003 
psa_generate_key(const psa_key_attributes_t * attributes,mbedtls_svc_key_id_t * key)8004 psa_status_t psa_generate_key(const psa_key_attributes_t *attributes,
8005                               mbedtls_svc_key_id_t *key)
8006 {
8007     return psa_generate_key_ext(attributes,
8008                                 &default_production_parameters, 0,
8009                                 key);
8010 }
8011 
8012 /****************************************************************/
8013 /* Module setup */
8014 /****************************************************************/
8015 
8016 #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))8017 psa_status_t mbedtls_psa_crypto_configure_entropy_sources(
8018     void (* entropy_init)(mbedtls_entropy_context *ctx),
8019     void (* entropy_free)(mbedtls_entropy_context *ctx))
8020 {
8021     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
8022 
8023 #if defined(MBEDTLS_THREADING_C)
8024     mbedtls_mutex_lock(&mbedtls_threading_psa_rngdata_mutex);
8025 #endif /* defined(MBEDTLS_THREADING_C) */
8026 
8027     if (global_data.rng_state != RNG_NOT_INITIALIZED) {
8028         status = PSA_ERROR_BAD_STATE;
8029     } else {
8030         global_data.rng.entropy_init = entropy_init;
8031         global_data.rng.entropy_free = entropy_free;
8032         status = PSA_SUCCESS;
8033     }
8034 
8035 #if defined(MBEDTLS_THREADING_C)
8036     mbedtls_mutex_unlock(&mbedtls_threading_psa_rngdata_mutex);
8037 #endif /* defined(MBEDTLS_THREADING_C) */
8038 
8039     return status;
8040 }
8041 #endif /* !defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG) */
8042 
mbedtls_psa_crypto_free(void)8043 void mbedtls_psa_crypto_free(void)
8044 {
8045 
8046 #if defined(MBEDTLS_THREADING_C)
8047     mbedtls_mutex_lock(&mbedtls_threading_psa_globaldata_mutex);
8048 #endif /* defined(MBEDTLS_THREADING_C) */
8049 
8050     /* Nothing to do to free transaction. */
8051     if (global_data.initialized & PSA_CRYPTO_SUBSYSTEM_TRANSACTION_INITIALIZED) {
8052         global_data.initialized &= ~PSA_CRYPTO_SUBSYSTEM_TRANSACTION_INITIALIZED;
8053     }
8054 
8055     if (global_data.initialized & PSA_CRYPTO_SUBSYSTEM_KEY_SLOTS_INITIALIZED) {
8056         psa_wipe_all_key_slots();
8057         global_data.initialized &= ~PSA_CRYPTO_SUBSYSTEM_KEY_SLOTS_INITIALIZED;
8058     }
8059 
8060 #if defined(MBEDTLS_THREADING_C)
8061     mbedtls_mutex_unlock(&mbedtls_threading_psa_globaldata_mutex);
8062 #endif /* defined(MBEDTLS_THREADING_C) */
8063 
8064 #if defined(MBEDTLS_THREADING_C)
8065     mbedtls_mutex_lock(&mbedtls_threading_psa_rngdata_mutex);
8066 #endif /* defined(MBEDTLS_THREADING_C) */
8067 
8068     if (global_data.rng_state != RNG_NOT_INITIALIZED) {
8069         mbedtls_psa_random_free(&global_data.rng);
8070     }
8071     global_data.rng_state = RNG_NOT_INITIALIZED;
8072     mbedtls_platform_zeroize(&global_data.rng, sizeof(global_data.rng));
8073 
8074 #if defined(MBEDTLS_THREADING_C)
8075     mbedtls_mutex_unlock(&mbedtls_threading_psa_rngdata_mutex);
8076 #endif /* defined(MBEDTLS_THREADING_C) */
8077 
8078 #if defined(MBEDTLS_THREADING_C)
8079     mbedtls_mutex_lock(&mbedtls_threading_psa_globaldata_mutex);
8080 #endif /* defined(MBEDTLS_THREADING_C) */
8081 
8082     /* Terminate drivers */
8083     if (global_data.initialized & PSA_CRYPTO_SUBSYSTEM_DRIVER_WRAPPERS_INITIALIZED) {
8084         psa_driver_wrapper_free();
8085         global_data.initialized &= ~PSA_CRYPTO_SUBSYSTEM_DRIVER_WRAPPERS_INITIALIZED;
8086     }
8087 
8088 #if defined(MBEDTLS_THREADING_C)
8089     mbedtls_mutex_unlock(&mbedtls_threading_psa_globaldata_mutex);
8090 #endif /* defined(MBEDTLS_THREADING_C) */
8091 
8092 }
8093 
8094 #if defined(PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS)
8095 /** Recover a transaction that was interrupted by a power failure.
8096  *
8097  * This function is called during initialization, before psa_crypto_init()
8098  * returns. If this function returns a failure status, the initialization
8099  * fails.
8100  */
psa_crypto_recover_transaction(const psa_crypto_transaction_t * transaction)8101 static psa_status_t psa_crypto_recover_transaction(
8102     const psa_crypto_transaction_t *transaction)
8103 {
8104     switch (transaction->unknown.type) {
8105         case PSA_CRYPTO_TRANSACTION_CREATE_KEY:
8106         case PSA_CRYPTO_TRANSACTION_DESTROY_KEY:
8107         /* TODO - fall through to the failure case until this
8108          * is implemented.
8109          * https://github.com/ARMmbed/mbed-crypto/issues/218
8110          */
8111         default:
8112             /* We found an unsupported transaction in the storage.
8113              * We don't know what state the storage is in. Give up. */
8114             return PSA_ERROR_DATA_INVALID;
8115     }
8116 }
8117 #endif /* PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS */
8118 
mbedtls_psa_crypto_init_subsystem(mbedtls_psa_crypto_subsystem subsystem)8119 static psa_status_t mbedtls_psa_crypto_init_subsystem(mbedtls_psa_crypto_subsystem subsystem)
8120 {
8121     psa_status_t status = PSA_SUCCESS;
8122     uint8_t driver_wrappers_initialized = 0;
8123 
8124     switch (subsystem) {
8125         case PSA_CRYPTO_SUBSYSTEM_DRIVER_WRAPPERS:
8126 
8127 #if defined(MBEDTLS_THREADING_C)
8128             PSA_THREADING_CHK_GOTO_EXIT(mbedtls_mutex_lock(&mbedtls_threading_psa_globaldata_mutex));
8129 #endif /* defined(MBEDTLS_THREADING_C) */
8130 
8131             if (!(global_data.initialized & PSA_CRYPTO_SUBSYSTEM_DRIVER_WRAPPERS_INITIALIZED)) {
8132                 /* Init drivers */
8133                 status = psa_driver_wrapper_init();
8134 
8135                 /* Drivers need shutdown regardless of startup errors. */
8136                 global_data.initialized |= PSA_CRYPTO_SUBSYSTEM_DRIVER_WRAPPERS_INITIALIZED;
8137 
8138 
8139             }
8140 #if defined(MBEDTLS_THREADING_C)
8141             PSA_THREADING_CHK_GOTO_EXIT(mbedtls_mutex_unlock(
8142                                             &mbedtls_threading_psa_globaldata_mutex));
8143 #endif /* defined(MBEDTLS_THREADING_C) */
8144 
8145             break;
8146 
8147         case PSA_CRYPTO_SUBSYSTEM_KEY_SLOTS:
8148 
8149 #if defined(MBEDTLS_THREADING_C)
8150             PSA_THREADING_CHK_GOTO_EXIT(mbedtls_mutex_lock(&mbedtls_threading_psa_globaldata_mutex));
8151 #endif /* defined(MBEDTLS_THREADING_C) */
8152 
8153             if (!(global_data.initialized & PSA_CRYPTO_SUBSYSTEM_KEY_SLOTS_INITIALIZED)) {
8154                 status = psa_initialize_key_slots();
8155 
8156                 /* Need to wipe keys even if initialization fails. */
8157                 global_data.initialized |= PSA_CRYPTO_SUBSYSTEM_KEY_SLOTS_INITIALIZED;
8158 
8159             }
8160 #if defined(MBEDTLS_THREADING_C)
8161             PSA_THREADING_CHK_GOTO_EXIT(mbedtls_mutex_unlock(
8162                                             &mbedtls_threading_psa_globaldata_mutex));
8163 #endif /* defined(MBEDTLS_THREADING_C) */
8164 
8165             break;
8166 
8167         case PSA_CRYPTO_SUBSYSTEM_RNG:
8168 
8169 #if defined(MBEDTLS_THREADING_C)
8170             PSA_THREADING_CHK_GOTO_EXIT(mbedtls_mutex_lock(&mbedtls_threading_psa_globaldata_mutex));
8171 #endif /* defined(MBEDTLS_THREADING_C) */
8172 
8173             driver_wrappers_initialized =
8174                 (global_data.initialized & PSA_CRYPTO_SUBSYSTEM_DRIVER_WRAPPERS_INITIALIZED);
8175 
8176 #if defined(MBEDTLS_THREADING_C)
8177             PSA_THREADING_CHK_GOTO_EXIT(mbedtls_mutex_unlock(
8178                                             &mbedtls_threading_psa_globaldata_mutex));
8179 #endif /* defined(MBEDTLS_THREADING_C) */
8180 
8181             /* Need to use separate mutex here, as initialisation can require
8182              * testing of init flags, which requires locking the global data
8183              * mutex. */
8184 #if defined(MBEDTLS_THREADING_C)
8185             PSA_THREADING_CHK_GOTO_EXIT(mbedtls_mutex_lock(&mbedtls_threading_psa_rngdata_mutex));
8186 #endif /* defined(MBEDTLS_THREADING_C) */
8187 
8188             /* Initialize and seed the random generator. */
8189             if (global_data.rng_state == RNG_NOT_INITIALIZED && driver_wrappers_initialized) {
8190                 mbedtls_psa_random_init(&global_data.rng);
8191                 global_data.rng_state = RNG_INITIALIZED;
8192 
8193                 status = mbedtls_psa_random_seed(&global_data.rng);
8194                 if (status == PSA_SUCCESS) {
8195                     global_data.rng_state = RNG_SEEDED;
8196                 }
8197             }
8198 
8199 #if defined(MBEDTLS_THREADING_C)
8200             PSA_THREADING_CHK_GOTO_EXIT(mbedtls_mutex_unlock(
8201                                             &mbedtls_threading_psa_rngdata_mutex));
8202 #endif /* defined(MBEDTLS_THREADING_C) */
8203 
8204             break;
8205 
8206         case PSA_CRYPTO_SUBSYSTEM_TRANSACTION:
8207 
8208 #if defined(MBEDTLS_THREADING_C)
8209             PSA_THREADING_CHK_GOTO_EXIT(mbedtls_mutex_lock(&mbedtls_threading_psa_globaldata_mutex));
8210 #endif /* defined(MBEDTLS_THREADING_C) */
8211 
8212             if (!(global_data.initialized & PSA_CRYPTO_SUBSYSTEM_TRANSACTION_INITIALIZED)) {
8213 #if defined(PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS)
8214                 status = psa_crypto_load_transaction();
8215                 if (status == PSA_SUCCESS) {
8216                     status = psa_crypto_recover_transaction(&psa_crypto_transaction);
8217                     if (status == PSA_SUCCESS) {
8218                         global_data.initialized |= PSA_CRYPTO_SUBSYSTEM_TRANSACTION_INITIALIZED;
8219                     }
8220                     status = psa_crypto_stop_transaction();
8221                 } else if (status == PSA_ERROR_DOES_NOT_EXIST) {
8222                     /* There's no transaction to complete. It's all good. */
8223                     global_data.initialized |= PSA_CRYPTO_SUBSYSTEM_TRANSACTION_INITIALIZED;
8224                     status = PSA_SUCCESS;
8225                 }
8226 #else /* defined(PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS) */
8227                 global_data.initialized |= PSA_CRYPTO_SUBSYSTEM_TRANSACTION_INITIALIZED;
8228                 status = PSA_SUCCESS;
8229 #endif /* defined(PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS) */
8230             }
8231 
8232 #if defined(MBEDTLS_THREADING_C)
8233             PSA_THREADING_CHK_GOTO_EXIT(mbedtls_mutex_unlock(
8234                                             &mbedtls_threading_psa_globaldata_mutex));
8235 #endif /* defined(MBEDTLS_THREADING_C) */
8236 
8237             break;
8238 
8239         default:
8240             status = PSA_ERROR_CORRUPTION_DETECTED;
8241     }
8242 
8243     /* Exit label only required when using threading macros. */
8244 #if defined(MBEDTLS_THREADING_C)
8245 exit:
8246 #endif /* defined(MBEDTLS_THREADING_C) */
8247 
8248     return status;
8249 }
8250 
psa_crypto_init(void)8251 psa_status_t psa_crypto_init(void)
8252 {
8253     psa_status_t status;
8254 
8255     /* Double initialization is explicitly allowed. Early out if everything is
8256      * done. */
8257     if (psa_get_initialized()) {
8258         return PSA_SUCCESS;
8259     }
8260 
8261     status = mbedtls_psa_crypto_init_subsystem(PSA_CRYPTO_SUBSYSTEM_DRIVER_WRAPPERS);
8262     if (status != PSA_SUCCESS) {
8263         goto exit;
8264     }
8265 
8266     status = mbedtls_psa_crypto_init_subsystem(PSA_CRYPTO_SUBSYSTEM_KEY_SLOTS);
8267     if (status != PSA_SUCCESS) {
8268         goto exit;
8269     }
8270 
8271     status = mbedtls_psa_crypto_init_subsystem(PSA_CRYPTO_SUBSYSTEM_RNG);
8272     if (status != PSA_SUCCESS) {
8273         goto exit;
8274     }
8275 
8276     status = mbedtls_psa_crypto_init_subsystem(PSA_CRYPTO_SUBSYSTEM_TRANSACTION);
8277 
8278 exit:
8279 
8280     if (status != PSA_SUCCESS) {
8281         mbedtls_psa_crypto_free();
8282     }
8283 
8284     return status;
8285 }
8286 
8287 #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)8288 psa_status_t psa_crypto_driver_pake_get_password_len(
8289     const psa_crypto_driver_pake_inputs_t *inputs,
8290     size_t *password_len)
8291 {
8292     if (inputs->password_len == 0) {
8293         return PSA_ERROR_BAD_STATE;
8294     }
8295 
8296     *password_len = inputs->password_len;
8297 
8298     return PSA_SUCCESS;
8299 }
8300 
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)8301 psa_status_t psa_crypto_driver_pake_get_password(
8302     const psa_crypto_driver_pake_inputs_t *inputs,
8303     uint8_t *buffer, size_t buffer_size, size_t *buffer_length)
8304 {
8305     if (inputs->password_len == 0) {
8306         return PSA_ERROR_BAD_STATE;
8307     }
8308 
8309     if (buffer_size < inputs->password_len) {
8310         return PSA_ERROR_BUFFER_TOO_SMALL;
8311     }
8312 
8313     memcpy(buffer, inputs->password, inputs->password_len);
8314     *buffer_length = inputs->password_len;
8315 
8316     return PSA_SUCCESS;
8317 }
8318 
psa_crypto_driver_pake_get_user_len(const psa_crypto_driver_pake_inputs_t * inputs,size_t * user_len)8319 psa_status_t psa_crypto_driver_pake_get_user_len(
8320     const psa_crypto_driver_pake_inputs_t *inputs,
8321     size_t *user_len)
8322 {
8323     if (inputs->user_len == 0) {
8324         return PSA_ERROR_BAD_STATE;
8325     }
8326 
8327     *user_len = inputs->user_len;
8328 
8329     return PSA_SUCCESS;
8330 }
8331 
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)8332 psa_status_t psa_crypto_driver_pake_get_user(
8333     const psa_crypto_driver_pake_inputs_t *inputs,
8334     uint8_t *user_id, size_t user_id_size, size_t *user_id_len)
8335 {
8336     if (inputs->user_len == 0) {
8337         return PSA_ERROR_BAD_STATE;
8338     }
8339 
8340     if (user_id_size < inputs->user_len) {
8341         return PSA_ERROR_BUFFER_TOO_SMALL;
8342     }
8343 
8344     memcpy(user_id, inputs->user, inputs->user_len);
8345     *user_id_len = inputs->user_len;
8346 
8347     return PSA_SUCCESS;
8348 }
8349 
psa_crypto_driver_pake_get_peer_len(const psa_crypto_driver_pake_inputs_t * inputs,size_t * peer_len)8350 psa_status_t psa_crypto_driver_pake_get_peer_len(
8351     const psa_crypto_driver_pake_inputs_t *inputs,
8352     size_t *peer_len)
8353 {
8354     if (inputs->peer_len == 0) {
8355         return PSA_ERROR_BAD_STATE;
8356     }
8357 
8358     *peer_len = inputs->peer_len;
8359 
8360     return PSA_SUCCESS;
8361 }
8362 
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)8363 psa_status_t psa_crypto_driver_pake_get_peer(
8364     const psa_crypto_driver_pake_inputs_t *inputs,
8365     uint8_t *peer_id, size_t peer_id_size, size_t *peer_id_length)
8366 {
8367     if (inputs->peer_len == 0) {
8368         return PSA_ERROR_BAD_STATE;
8369     }
8370 
8371     if (peer_id_size < inputs->peer_len) {
8372         return PSA_ERROR_BUFFER_TOO_SMALL;
8373     }
8374 
8375     memcpy(peer_id, inputs->peer, inputs->peer_len);
8376     *peer_id_length = inputs->peer_len;
8377 
8378     return PSA_SUCCESS;
8379 }
8380 
psa_crypto_driver_pake_get_cipher_suite(const psa_crypto_driver_pake_inputs_t * inputs,psa_pake_cipher_suite_t * cipher_suite)8381 psa_status_t psa_crypto_driver_pake_get_cipher_suite(
8382     const psa_crypto_driver_pake_inputs_t *inputs,
8383     psa_pake_cipher_suite_t *cipher_suite)
8384 {
8385     if (inputs->cipher_suite.algorithm == PSA_ALG_NONE) {
8386         return PSA_ERROR_BAD_STATE;
8387     }
8388 
8389     *cipher_suite = inputs->cipher_suite;
8390 
8391     return PSA_SUCCESS;
8392 }
8393 
psa_pake_setup(psa_pake_operation_t * operation,const psa_pake_cipher_suite_t * cipher_suite)8394 psa_status_t psa_pake_setup(
8395     psa_pake_operation_t *operation,
8396     const psa_pake_cipher_suite_t *cipher_suite)
8397 {
8398     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
8399 
8400     if (operation->stage != PSA_PAKE_OPERATION_STAGE_SETUP) {
8401         status = PSA_ERROR_BAD_STATE;
8402         goto exit;
8403     }
8404 
8405     if (PSA_ALG_IS_PAKE(cipher_suite->algorithm) == 0 ||
8406         PSA_ALG_IS_HASH(cipher_suite->hash) == 0) {
8407         status = PSA_ERROR_INVALID_ARGUMENT;
8408         goto exit;
8409     }
8410 
8411     memset(&operation->data.inputs, 0, sizeof(operation->data.inputs));
8412 
8413     operation->alg = cipher_suite->algorithm;
8414     operation->primitive = PSA_PAKE_PRIMITIVE(cipher_suite->type,
8415                                               cipher_suite->family, cipher_suite->bits);
8416     operation->data.inputs.cipher_suite = *cipher_suite;
8417 
8418 #if defined(PSA_WANT_ALG_JPAKE)
8419     if (operation->alg == PSA_ALG_JPAKE) {
8420         psa_jpake_computation_stage_t *computation_stage =
8421             &operation->computation_stage.jpake;
8422 
8423         memset(computation_stage, 0, sizeof(*computation_stage));
8424         computation_stage->step = PSA_PAKE_STEP_KEY_SHARE;
8425     } else
8426 #endif /* PSA_WANT_ALG_JPAKE */
8427     {
8428         status = PSA_ERROR_NOT_SUPPORTED;
8429         goto exit;
8430     }
8431 
8432     operation->stage = PSA_PAKE_OPERATION_STAGE_COLLECT_INPUTS;
8433 
8434     return PSA_SUCCESS;
8435 exit:
8436     psa_pake_abort(operation);
8437     return status;
8438 }
8439 
psa_pake_set_password_key(psa_pake_operation_t * operation,mbedtls_svc_key_id_t password)8440 psa_status_t psa_pake_set_password_key(
8441     psa_pake_operation_t *operation,
8442     mbedtls_svc_key_id_t password)
8443 {
8444     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
8445     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
8446     psa_key_slot_t *slot = NULL;
8447     psa_key_type_t type;
8448 
8449     if (operation->stage != PSA_PAKE_OPERATION_STAGE_COLLECT_INPUTS) {
8450         status = PSA_ERROR_BAD_STATE;
8451         goto exit;
8452     }
8453 
8454     status = psa_get_and_lock_key_slot_with_policy(password, &slot,
8455                                                    PSA_KEY_USAGE_DERIVE,
8456                                                    operation->alg);
8457     if (status != PSA_SUCCESS) {
8458         goto exit;
8459     }
8460 
8461     type = psa_get_key_type(&slot->attr);
8462 
8463     if (type != PSA_KEY_TYPE_PASSWORD &&
8464         type != PSA_KEY_TYPE_PASSWORD_HASH) {
8465         status = PSA_ERROR_INVALID_ARGUMENT;
8466         goto exit;
8467     }
8468 
8469     operation->data.inputs.password = mbedtls_calloc(1, slot->key.bytes);
8470     if (operation->data.inputs.password == NULL) {
8471         status = PSA_ERROR_INSUFFICIENT_MEMORY;
8472         goto exit;
8473     }
8474 
8475     memcpy(operation->data.inputs.password, slot->key.data, slot->key.bytes);
8476     operation->data.inputs.password_len = slot->key.bytes;
8477     operation->data.inputs.attributes = slot->attr;
8478 
8479 exit:
8480     if (status != PSA_SUCCESS) {
8481         psa_pake_abort(operation);
8482     }
8483     unlock_status = psa_unregister_read_under_mutex(slot);
8484     return (status == PSA_SUCCESS) ? unlock_status : status;
8485 }
8486 
psa_pake_set_user(psa_pake_operation_t * operation,const uint8_t * user_id_external,size_t user_id_len)8487 psa_status_t psa_pake_set_user(
8488     psa_pake_operation_t *operation,
8489     const uint8_t *user_id_external,
8490     size_t user_id_len)
8491 {
8492     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
8493     LOCAL_INPUT_DECLARE(user_id_external, user_id);
8494 
8495     if (operation->stage != PSA_PAKE_OPERATION_STAGE_COLLECT_INPUTS) {
8496         status = PSA_ERROR_BAD_STATE;
8497         goto exit;
8498     }
8499 
8500     if (user_id_len == 0) {
8501         status = PSA_ERROR_INVALID_ARGUMENT;
8502         goto exit;
8503     }
8504 
8505     if (operation->data.inputs.user_len != 0) {
8506         status = PSA_ERROR_BAD_STATE;
8507         goto exit;
8508     }
8509 
8510     operation->data.inputs.user = mbedtls_calloc(1, user_id_len);
8511     if (operation->data.inputs.user == NULL) {
8512         status = PSA_ERROR_INSUFFICIENT_MEMORY;
8513         goto exit;
8514     }
8515 
8516     LOCAL_INPUT_ALLOC(user_id_external, user_id_len, user_id);
8517 
8518     memcpy(operation->data.inputs.user, user_id, user_id_len);
8519     operation->data.inputs.user_len = user_id_len;
8520 
8521     status = PSA_SUCCESS;
8522 
8523 exit:
8524     LOCAL_INPUT_FREE(user_id_external, user_id);
8525     if (status != PSA_SUCCESS) {
8526         psa_pake_abort(operation);
8527     }
8528     return status;
8529 }
8530 
psa_pake_set_peer(psa_pake_operation_t * operation,const uint8_t * peer_id_external,size_t peer_id_len)8531 psa_status_t psa_pake_set_peer(
8532     psa_pake_operation_t *operation,
8533     const uint8_t *peer_id_external,
8534     size_t peer_id_len)
8535 {
8536     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
8537     LOCAL_INPUT_DECLARE(peer_id_external, peer_id);
8538 
8539     if (operation->stage != PSA_PAKE_OPERATION_STAGE_COLLECT_INPUTS) {
8540         status = PSA_ERROR_BAD_STATE;
8541         goto exit;
8542     }
8543 
8544     if (peer_id_len == 0) {
8545         status = PSA_ERROR_INVALID_ARGUMENT;
8546         goto exit;
8547     }
8548 
8549     if (operation->data.inputs.peer_len != 0) {
8550         status = PSA_ERROR_BAD_STATE;
8551         goto exit;
8552     }
8553 
8554     operation->data.inputs.peer = mbedtls_calloc(1, peer_id_len);
8555     if (operation->data.inputs.peer == NULL) {
8556         status = PSA_ERROR_INSUFFICIENT_MEMORY;
8557         goto exit;
8558     }
8559 
8560     LOCAL_INPUT_ALLOC(peer_id_external, peer_id_len, peer_id);
8561 
8562     memcpy(operation->data.inputs.peer, peer_id, peer_id_len);
8563     operation->data.inputs.peer_len = peer_id_len;
8564 
8565     status = PSA_SUCCESS;
8566 
8567 exit:
8568     LOCAL_INPUT_FREE(peer_id_external, peer_id);
8569     if (status != PSA_SUCCESS) {
8570         psa_pake_abort(operation);
8571     }
8572     return status;
8573 }
8574 
psa_pake_set_role(psa_pake_operation_t * operation,psa_pake_role_t role)8575 psa_status_t psa_pake_set_role(
8576     psa_pake_operation_t *operation,
8577     psa_pake_role_t role)
8578 {
8579     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
8580 
8581     if (operation->stage != PSA_PAKE_OPERATION_STAGE_COLLECT_INPUTS) {
8582         status = PSA_ERROR_BAD_STATE;
8583         goto exit;
8584     }
8585 
8586     switch (operation->alg) {
8587 #if defined(PSA_WANT_ALG_JPAKE)
8588         case PSA_ALG_JPAKE:
8589             if (role == PSA_PAKE_ROLE_NONE) {
8590                 return PSA_SUCCESS;
8591             }
8592             status = PSA_ERROR_INVALID_ARGUMENT;
8593             break;
8594 #endif
8595         default:
8596             (void) role;
8597             status = PSA_ERROR_NOT_SUPPORTED;
8598             goto exit;
8599     }
8600 exit:
8601     psa_pake_abort(operation);
8602     return status;
8603 }
8604 
8605 /* Auxiliary function to convert core computation stage to single driver step. */
8606 #if defined(PSA_WANT_ALG_JPAKE)
convert_jpake_computation_stage_to_driver_step(psa_jpake_computation_stage_t * stage)8607 static psa_crypto_driver_pake_step_t convert_jpake_computation_stage_to_driver_step(
8608     psa_jpake_computation_stage_t *stage)
8609 {
8610     psa_crypto_driver_pake_step_t key_share_step;
8611     if (stage->round == PSA_JPAKE_FIRST) {
8612         int is_x1;
8613 
8614         if (stage->io_mode == PSA_JPAKE_OUTPUT) {
8615             is_x1 = (stage->outputs < 1);
8616         } else {
8617             is_x1 = (stage->inputs < 1);
8618         }
8619 
8620         key_share_step = is_x1 ?
8621                          PSA_JPAKE_X1_STEP_KEY_SHARE :
8622                          PSA_JPAKE_X2_STEP_KEY_SHARE;
8623     } else if (stage->round == PSA_JPAKE_SECOND) {
8624         key_share_step = (stage->io_mode == PSA_JPAKE_OUTPUT) ?
8625                          PSA_JPAKE_X2S_STEP_KEY_SHARE :
8626                          PSA_JPAKE_X4S_STEP_KEY_SHARE;
8627     } else {
8628         return PSA_JPAKE_STEP_INVALID;
8629     }
8630     return (psa_crypto_driver_pake_step_t) (key_share_step + stage->step - PSA_PAKE_STEP_KEY_SHARE);
8631 }
8632 #endif /* PSA_WANT_ALG_JPAKE */
8633 
psa_pake_complete_inputs(psa_pake_operation_t * operation)8634 static psa_status_t psa_pake_complete_inputs(
8635     psa_pake_operation_t *operation)
8636 {
8637     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
8638     /* Create copy of the inputs on stack as inputs share memory
8639        with the driver context which will be setup by the driver. */
8640     psa_crypto_driver_pake_inputs_t inputs = operation->data.inputs;
8641 
8642     if (inputs.password_len == 0) {
8643         return PSA_ERROR_BAD_STATE;
8644     }
8645 
8646     if (operation->alg == PSA_ALG_JPAKE) {
8647         if (inputs.user_len == 0 || inputs.peer_len == 0) {
8648             return PSA_ERROR_BAD_STATE;
8649         }
8650     }
8651 
8652     /* Clear driver context */
8653     mbedtls_platform_zeroize(&operation->data, sizeof(operation->data));
8654 
8655     status = psa_driver_wrapper_pake_setup(operation, &inputs);
8656 
8657     /* Driver is responsible for creating its own copy of the password. */
8658     mbedtls_zeroize_and_free(inputs.password, inputs.password_len);
8659 
8660     /* User and peer are translated to role. */
8661     mbedtls_free(inputs.user);
8662     mbedtls_free(inputs.peer);
8663 
8664     if (status == PSA_SUCCESS) {
8665 #if defined(PSA_WANT_ALG_JPAKE)
8666         if (operation->alg == PSA_ALG_JPAKE) {
8667             operation->stage = PSA_PAKE_OPERATION_STAGE_COMPUTATION;
8668         } else
8669 #endif /* PSA_WANT_ALG_JPAKE */
8670         {
8671             status = PSA_ERROR_NOT_SUPPORTED;
8672         }
8673     }
8674     return status;
8675 }
8676 
8677 #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)8678 static psa_status_t psa_jpake_prologue(
8679     psa_pake_operation_t *operation,
8680     psa_pake_step_t step,
8681     psa_jpake_io_mode_t io_mode)
8682 {
8683     if (step != PSA_PAKE_STEP_KEY_SHARE &&
8684         step != PSA_PAKE_STEP_ZK_PUBLIC &&
8685         step != PSA_PAKE_STEP_ZK_PROOF) {
8686         return PSA_ERROR_INVALID_ARGUMENT;
8687     }
8688 
8689     psa_jpake_computation_stage_t *computation_stage =
8690         &operation->computation_stage.jpake;
8691 
8692     if (computation_stage->round != PSA_JPAKE_FIRST &&
8693         computation_stage->round != PSA_JPAKE_SECOND) {
8694         return PSA_ERROR_BAD_STATE;
8695     }
8696 
8697     /* Check that the step we are given is the one we were expecting */
8698     if (step != computation_stage->step) {
8699         return PSA_ERROR_BAD_STATE;
8700     }
8701 
8702     if (step == PSA_PAKE_STEP_KEY_SHARE &&
8703         computation_stage->inputs == 0 &&
8704         computation_stage->outputs == 0) {
8705         /* Start of the round, so function decides whether we are inputting
8706          * or outputting */
8707         computation_stage->io_mode = io_mode;
8708     } else if (computation_stage->io_mode != io_mode) {
8709         /* Middle of the round so the mode we are in must match the function
8710          * called by the user */
8711         return PSA_ERROR_BAD_STATE;
8712     }
8713 
8714     return PSA_SUCCESS;
8715 }
8716 
psa_jpake_epilogue(psa_pake_operation_t * operation,psa_jpake_io_mode_t io_mode)8717 static psa_status_t psa_jpake_epilogue(
8718     psa_pake_operation_t *operation,
8719     psa_jpake_io_mode_t io_mode)
8720 {
8721     psa_jpake_computation_stage_t *stage =
8722         &operation->computation_stage.jpake;
8723 
8724     if (stage->step == PSA_PAKE_STEP_ZK_PROOF) {
8725         /* End of an input/output */
8726         if (io_mode == PSA_JPAKE_INPUT) {
8727             stage->inputs++;
8728             if (stage->inputs == PSA_JPAKE_EXPECTED_INPUTS(stage->round)) {
8729                 stage->io_mode = PSA_JPAKE_OUTPUT;
8730             }
8731         }
8732         if (io_mode == PSA_JPAKE_OUTPUT) {
8733             stage->outputs++;
8734             if (stage->outputs == PSA_JPAKE_EXPECTED_OUTPUTS(stage->round)) {
8735                 stage->io_mode = PSA_JPAKE_INPUT;
8736             }
8737         }
8738         if (stage->inputs == PSA_JPAKE_EXPECTED_INPUTS(stage->round) &&
8739             stage->outputs == PSA_JPAKE_EXPECTED_OUTPUTS(stage->round)) {
8740             /* End of a round, move to the next round */
8741             stage->inputs = 0;
8742             stage->outputs = 0;
8743             stage->round++;
8744         }
8745         stage->step = PSA_PAKE_STEP_KEY_SHARE;
8746     } else {
8747         stage->step++;
8748     }
8749     return PSA_SUCCESS;
8750 }
8751 
8752 #endif /* PSA_WANT_ALG_JPAKE */
8753 
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)8754 psa_status_t psa_pake_output(
8755     psa_pake_operation_t *operation,
8756     psa_pake_step_t step,
8757     uint8_t *output_external,
8758     size_t output_size,
8759     size_t *output_length)
8760 {
8761     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
8762     psa_crypto_driver_pake_step_t driver_step = PSA_JPAKE_STEP_INVALID;
8763     LOCAL_OUTPUT_DECLARE(output_external, output);
8764     *output_length = 0;
8765 
8766     if (operation->stage == PSA_PAKE_OPERATION_STAGE_COLLECT_INPUTS) {
8767         status = psa_pake_complete_inputs(operation);
8768         if (status != PSA_SUCCESS) {
8769             goto exit;
8770         }
8771     }
8772 
8773     if (operation->stage != PSA_PAKE_OPERATION_STAGE_COMPUTATION) {
8774         status = PSA_ERROR_BAD_STATE;
8775         goto exit;
8776     }
8777 
8778     if (output_size == 0) {
8779         status = PSA_ERROR_INVALID_ARGUMENT;
8780         goto exit;
8781     }
8782 
8783     switch (operation->alg) {
8784 #if defined(PSA_WANT_ALG_JPAKE)
8785         case PSA_ALG_JPAKE:
8786             status = psa_jpake_prologue(operation, step, PSA_JPAKE_OUTPUT);
8787             if (status != PSA_SUCCESS) {
8788                 goto exit;
8789             }
8790             driver_step = convert_jpake_computation_stage_to_driver_step(
8791                 &operation->computation_stage.jpake);
8792             break;
8793 #endif /* PSA_WANT_ALG_JPAKE */
8794         default:
8795             (void) step;
8796             status = PSA_ERROR_NOT_SUPPORTED;
8797             goto exit;
8798     }
8799 
8800     LOCAL_OUTPUT_ALLOC(output_external, output_size, output);
8801 
8802     status = psa_driver_wrapper_pake_output(operation, driver_step,
8803                                             output, output_size, output_length);
8804 
8805     if (status != PSA_SUCCESS) {
8806         goto exit;
8807     }
8808 
8809     switch (operation->alg) {
8810 #if defined(PSA_WANT_ALG_JPAKE)
8811         case PSA_ALG_JPAKE:
8812             status = psa_jpake_epilogue(operation, PSA_JPAKE_OUTPUT);
8813             if (status != PSA_SUCCESS) {
8814                 goto exit;
8815             }
8816             break;
8817 #endif /* PSA_WANT_ALG_JPAKE */
8818         default:
8819             status = PSA_ERROR_NOT_SUPPORTED;
8820             goto exit;
8821     }
8822 
8823 exit:
8824     LOCAL_OUTPUT_FREE(output_external, output);
8825     if (status != PSA_SUCCESS) {
8826         psa_pake_abort(operation);
8827     }
8828     return status;
8829 }
8830 
psa_pake_input(psa_pake_operation_t * operation,psa_pake_step_t step,const uint8_t * input_external,size_t input_length)8831 psa_status_t psa_pake_input(
8832     psa_pake_operation_t *operation,
8833     psa_pake_step_t step,
8834     const uint8_t *input_external,
8835     size_t input_length)
8836 {
8837     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
8838     psa_crypto_driver_pake_step_t driver_step = PSA_JPAKE_STEP_INVALID;
8839     const size_t max_input_length = (size_t) PSA_PAKE_INPUT_SIZE(operation->alg,
8840                                                                  operation->primitive,
8841                                                                  step);
8842     LOCAL_INPUT_DECLARE(input_external, input);
8843 
8844     if (operation->stage == PSA_PAKE_OPERATION_STAGE_COLLECT_INPUTS) {
8845         status = psa_pake_complete_inputs(operation);
8846         if (status != PSA_SUCCESS) {
8847             goto exit;
8848         }
8849     }
8850 
8851     if (operation->stage != PSA_PAKE_OPERATION_STAGE_COMPUTATION) {
8852         status =  PSA_ERROR_BAD_STATE;
8853         goto exit;
8854     }
8855 
8856     if (input_length == 0 || input_length > max_input_length) {
8857         status = PSA_ERROR_INVALID_ARGUMENT;
8858         goto exit;
8859     }
8860 
8861     switch (operation->alg) {
8862 #if defined(PSA_WANT_ALG_JPAKE)
8863         case PSA_ALG_JPAKE:
8864             status = psa_jpake_prologue(operation, step, PSA_JPAKE_INPUT);
8865             if (status != PSA_SUCCESS) {
8866                 goto exit;
8867             }
8868             driver_step = convert_jpake_computation_stage_to_driver_step(
8869                 &operation->computation_stage.jpake);
8870             break;
8871 #endif /* PSA_WANT_ALG_JPAKE */
8872         default:
8873             (void) step;
8874             status = PSA_ERROR_NOT_SUPPORTED;
8875             goto exit;
8876     }
8877 
8878     LOCAL_INPUT_ALLOC(input_external, input_length, input);
8879     status = psa_driver_wrapper_pake_input(operation, driver_step,
8880                                            input, input_length);
8881 
8882     if (status != PSA_SUCCESS) {
8883         goto exit;
8884     }
8885 
8886     switch (operation->alg) {
8887 #if defined(PSA_WANT_ALG_JPAKE)
8888         case PSA_ALG_JPAKE:
8889             status = psa_jpake_epilogue(operation, PSA_JPAKE_INPUT);
8890             if (status != PSA_SUCCESS) {
8891                 goto exit;
8892             }
8893             break;
8894 #endif /* PSA_WANT_ALG_JPAKE */
8895         default:
8896             status = PSA_ERROR_NOT_SUPPORTED;
8897             goto exit;
8898     }
8899 
8900 exit:
8901     LOCAL_INPUT_FREE(input_external, input);
8902     if (status != PSA_SUCCESS) {
8903         psa_pake_abort(operation);
8904     }
8905     return status;
8906 }
8907 
psa_pake_get_implicit_key(psa_pake_operation_t * operation,psa_key_derivation_operation_t * output)8908 psa_status_t psa_pake_get_implicit_key(
8909     psa_pake_operation_t *operation,
8910     psa_key_derivation_operation_t *output)
8911 {
8912     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
8913     psa_status_t abort_status = PSA_ERROR_CORRUPTION_DETECTED;
8914     uint8_t shared_key[MBEDTLS_PSA_JPAKE_BUFFER_SIZE];
8915     size_t shared_key_len = 0;
8916 
8917     if (operation->stage != PSA_PAKE_OPERATION_STAGE_COMPUTATION) {
8918         status = PSA_ERROR_BAD_STATE;
8919         goto exit;
8920     }
8921 
8922 #if defined(PSA_WANT_ALG_JPAKE)
8923     if (operation->alg == PSA_ALG_JPAKE) {
8924         psa_jpake_computation_stage_t *computation_stage =
8925             &operation->computation_stage.jpake;
8926         if (computation_stage->round != PSA_JPAKE_FINISHED) {
8927             status = PSA_ERROR_BAD_STATE;
8928             goto exit;
8929         }
8930     } else
8931 #endif /* PSA_WANT_ALG_JPAKE */
8932     {
8933         status = PSA_ERROR_NOT_SUPPORTED;
8934         goto exit;
8935     }
8936 
8937     status = psa_driver_wrapper_pake_get_implicit_key(operation,
8938                                                       shared_key,
8939                                                       sizeof(shared_key),
8940                                                       &shared_key_len);
8941 
8942     if (status != PSA_SUCCESS) {
8943         goto exit;
8944     }
8945 
8946     status = psa_key_derivation_input_bytes(output,
8947                                             PSA_KEY_DERIVATION_INPUT_SECRET,
8948                                             shared_key,
8949                                             shared_key_len);
8950 
8951     mbedtls_platform_zeroize(shared_key, sizeof(shared_key));
8952 exit:
8953     abort_status = psa_pake_abort(operation);
8954     return status == PSA_SUCCESS ? abort_status : status;
8955 }
8956 
psa_pake_abort(psa_pake_operation_t * operation)8957 psa_status_t psa_pake_abort(
8958     psa_pake_operation_t *operation)
8959 {
8960     psa_status_t status = PSA_SUCCESS;
8961 
8962     if (operation->stage == PSA_PAKE_OPERATION_STAGE_COMPUTATION) {
8963         status = psa_driver_wrapper_pake_abort(operation);
8964     }
8965 
8966     if (operation->stage == PSA_PAKE_OPERATION_STAGE_COLLECT_INPUTS) {
8967         if (operation->data.inputs.password != NULL) {
8968             mbedtls_zeroize_and_free(operation->data.inputs.password,
8969                                      operation->data.inputs.password_len);
8970         }
8971         if (operation->data.inputs.user != NULL) {
8972             mbedtls_free(operation->data.inputs.user);
8973         }
8974         if (operation->data.inputs.peer != NULL) {
8975             mbedtls_free(operation->data.inputs.peer);
8976         }
8977     }
8978     memset(operation, 0, sizeof(psa_pake_operation_t));
8979 
8980     return status;
8981 }
8982 #endif /* PSA_WANT_ALG_SOME_PAKE */
8983 
8984 /* Memory copying test hooks. These are called before input copy, after input
8985  * copy, before output copy and after output copy, respectively.
8986  * They are used by memory-poisoning tests to temporarily unpoison buffers
8987  * while they are copied. */
8988 #if defined(MBEDTLS_TEST_HOOKS)
8989 void (*psa_input_pre_copy_hook)(const uint8_t *input, size_t input_len) = NULL;
8990 void (*psa_input_post_copy_hook)(const uint8_t *input, size_t input_len) = NULL;
8991 void (*psa_output_pre_copy_hook)(const uint8_t *output, size_t output_len) = NULL;
8992 void (*psa_output_post_copy_hook)(const uint8_t *output, size_t output_len) = NULL;
8993 #endif
8994 
8995 /** Copy from an input buffer to a local copy.
8996  *
8997  * \param[in] input             Pointer to input buffer.
8998  * \param[in] input_len         Length of the input buffer.
8999  * \param[out] input_copy       Pointer to a local copy in which to store the input data.
9000  * \param[out] input_copy_len   Length of the local copy buffer.
9001  * \return                      #PSA_SUCCESS, if the buffer was successfully
9002  *                              copied.
9003  * \return                      #PSA_ERROR_CORRUPTION_DETECTED, if the local
9004  *                              copy is too small to hold contents of the
9005  *                              input buffer.
9006  */
9007 MBEDTLS_STATIC_TESTABLE
psa_crypto_copy_input(const uint8_t * input,size_t input_len,uint8_t * input_copy,size_t input_copy_len)9008 psa_status_t psa_crypto_copy_input(const uint8_t *input, size_t input_len,
9009                                    uint8_t *input_copy, size_t input_copy_len)
9010 {
9011     if (input_len > input_copy_len) {
9012         return PSA_ERROR_CORRUPTION_DETECTED;
9013     }
9014 
9015 #if defined(MBEDTLS_TEST_HOOKS)
9016     if (psa_input_pre_copy_hook != NULL) {
9017         psa_input_pre_copy_hook(input, input_len);
9018     }
9019 #endif
9020 
9021     if (input_len > 0) {
9022         memcpy(input_copy, input, input_len);
9023     }
9024 
9025 #if defined(MBEDTLS_TEST_HOOKS)
9026     if (psa_input_post_copy_hook != NULL) {
9027         psa_input_post_copy_hook(input, input_len);
9028     }
9029 #endif
9030 
9031     return PSA_SUCCESS;
9032 }
9033 
9034 /** Copy from a local output buffer into a user-supplied one.
9035  *
9036  * \param[in] output_copy       Pointer to a local buffer containing the output.
9037  * \param[in] output_copy_len   Length of the local buffer.
9038  * \param[out] output           Pointer to user-supplied output buffer.
9039  * \param[out] output_len       Length of the user-supplied output buffer.
9040  * \return                      #PSA_SUCCESS, if the buffer was successfully
9041  *                              copied.
9042  * \return                      #PSA_ERROR_BUFFER_TOO_SMALL, if the
9043  *                              user-supplied output buffer is too small to
9044  *                              hold the contents of the local buffer.
9045  */
9046 MBEDTLS_STATIC_TESTABLE
psa_crypto_copy_output(const uint8_t * output_copy,size_t output_copy_len,uint8_t * output,size_t output_len)9047 psa_status_t psa_crypto_copy_output(const uint8_t *output_copy, size_t output_copy_len,
9048                                     uint8_t *output, size_t output_len)
9049 {
9050     if (output_len < output_copy_len) {
9051         return PSA_ERROR_BUFFER_TOO_SMALL;
9052     }
9053 
9054 #if defined(MBEDTLS_TEST_HOOKS)
9055     if (psa_output_pre_copy_hook != NULL) {
9056         psa_output_pre_copy_hook(output, output_len);
9057     }
9058 #endif
9059 
9060     if (output_copy_len > 0) {
9061         memcpy(output, output_copy, output_copy_len);
9062     }
9063 
9064 #if defined(MBEDTLS_TEST_HOOKS)
9065     if (psa_output_post_copy_hook != NULL) {
9066         psa_output_post_copy_hook(output, output_len);
9067     }
9068 #endif
9069 
9070     return PSA_SUCCESS;
9071 }
9072 
psa_crypto_local_input_alloc(const uint8_t * input,size_t input_len,psa_crypto_local_input_t * local_input)9073 psa_status_t psa_crypto_local_input_alloc(const uint8_t *input, size_t input_len,
9074                                           psa_crypto_local_input_t *local_input)
9075 {
9076     psa_status_t status;
9077 
9078     *local_input = PSA_CRYPTO_LOCAL_INPUT_INIT;
9079 
9080     if (input_len == 0) {
9081         return PSA_SUCCESS;
9082     }
9083 
9084     local_input->buffer = mbedtls_calloc(input_len, 1);
9085     if (local_input->buffer == NULL) {
9086         /* Since we dealt with the zero-length case above, we know that
9087          * a NULL return value means a failure of allocation. */
9088         return PSA_ERROR_INSUFFICIENT_MEMORY;
9089     }
9090     /* From now on, we must free local_input->buffer on error. */
9091 
9092     local_input->length = input_len;
9093 
9094     status = psa_crypto_copy_input(input, input_len,
9095                                    local_input->buffer, local_input->length);
9096     if (status != PSA_SUCCESS) {
9097         goto error;
9098     }
9099 
9100     return PSA_SUCCESS;
9101 
9102 error:
9103     mbedtls_free(local_input->buffer);
9104     local_input->buffer = NULL;
9105     local_input->length = 0;
9106     return status;
9107 }
9108 
psa_crypto_local_input_free(psa_crypto_local_input_t * local_input)9109 void psa_crypto_local_input_free(psa_crypto_local_input_t *local_input)
9110 {
9111     mbedtls_free(local_input->buffer);
9112     local_input->buffer = NULL;
9113     local_input->length = 0;
9114 }
9115 
psa_crypto_local_output_alloc(uint8_t * output,size_t output_len,psa_crypto_local_output_t * local_output)9116 psa_status_t psa_crypto_local_output_alloc(uint8_t *output, size_t output_len,
9117                                            psa_crypto_local_output_t *local_output)
9118 {
9119     *local_output = PSA_CRYPTO_LOCAL_OUTPUT_INIT;
9120 
9121     if (output_len == 0) {
9122         return PSA_SUCCESS;
9123     }
9124     local_output->buffer = mbedtls_calloc(output_len, 1);
9125     if (local_output->buffer == NULL) {
9126         /* Since we dealt with the zero-length case above, we know that
9127          * a NULL return value means a failure of allocation. */
9128         return PSA_ERROR_INSUFFICIENT_MEMORY;
9129     }
9130     local_output->length = output_len;
9131     local_output->original = output;
9132 
9133     return PSA_SUCCESS;
9134 }
9135 
psa_crypto_local_output_free(psa_crypto_local_output_t * local_output)9136 psa_status_t psa_crypto_local_output_free(psa_crypto_local_output_t *local_output)
9137 {
9138     psa_status_t status;
9139 
9140     if (local_output->buffer == NULL) {
9141         local_output->length = 0;
9142         return PSA_SUCCESS;
9143     }
9144     if (local_output->original == NULL) {
9145         /* We have an internal copy but nothing to copy back to. */
9146         return PSA_ERROR_CORRUPTION_DETECTED;
9147     }
9148 
9149     status = psa_crypto_copy_output(local_output->buffer, local_output->length,
9150                                     local_output->original, local_output->length);
9151     if (status != PSA_SUCCESS) {
9152         return status;
9153     }
9154 
9155     mbedtls_free(local_output->buffer);
9156     local_output->buffer = NULL;
9157     local_output->length = 0;
9158 
9159     return PSA_SUCCESS;
9160 }
9161 
9162 #endif /* MBEDTLS_PSA_CRYPTO_C */
9163