Coverage Report

Created: 2026-10-17 06:10

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