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