Coverage Report

Created: 2024-11-21 07:03

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