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