Merge pull request #2735 from jareckib/master
[RRG-proxmark3.git] / common / mbedtls / psa_crypto.c
blobd5905dc4b4a1000d9d22794f58b2bfb877c6855c
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
8 * Licensed under the Apache License, Version 2.0 (the "License"); you may
9 * not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
21 #include "common.h"
23 #if defined(MBEDTLS_PSA_CRYPTO_C)
25 #if defined(MBEDTLS_PSA_CRYPTO_CONFIG)
26 #include "check_crypto_config.h"
27 #endif
29 #include "psa_crypto_service_integration.h"
30 #include "psa/crypto.h"
32 #include "psa_crypto_core.h"
33 #include "psa_crypto_invasive.h"
34 #include "psa_crypto_driver_wrappers.h"
35 #include "psa_crypto_ecp.h"
36 #include "psa_crypto_rsa.h"
37 #include "psa_crypto_ecp.h"
38 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
39 #include "psa_crypto_se.h"
40 #endif
41 #include "psa_crypto_slot_management.h"
42 /* Include internal declarations that are useful for implementing persistently
43 * stored keys. */
44 #include "psa_crypto_storage.h"
46 #include "psa_crypto_random_impl.h"
48 #include <assert.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include "mbedtls/platform.h"
52 #if !defined(MBEDTLS_PLATFORM_C)
53 #define mbedtls_calloc calloc
54 #define mbedtls_free free
55 #endif
57 #include "mbedtls/aes.h"
58 #include "mbedtls/arc4.h"
59 #include "mbedtls/asn1.h"
60 #include "mbedtls/asn1write.h"
61 #include "mbedtls/bignum.h"
62 #include "mbedtls/blowfish.h"
63 #include "mbedtls/camellia.h"
64 #include "mbedtls/chacha20.h"
65 #include "mbedtls/chachapoly.h"
66 #include "mbedtls/cipher.h"
67 #include "mbedtls/ccm.h"
68 #include "mbedtls/cmac.h"
69 #include "mbedtls/des.h"
70 #include "mbedtls/ecdh.h"
71 #include "mbedtls/ecp.h"
72 #include "mbedtls/entropy.h"
73 #include "mbedtls/error.h"
74 #include "mbedtls/gcm.h"
75 #include "mbedtls/md2.h"
76 #include "mbedtls/md4.h"
77 #include "mbedtls/md5.h"
78 #include "mbedtls/md.h"
79 #include "mbedtls/md_internal.h"
80 #include "mbedtls/pk.h"
81 #include "mbedtls/pk_internal.h"
82 #include "mbedtls/platform_util.h"
83 #include "mbedtls/error.h"
84 #include "mbedtls/ripemd160.h"
85 #include "mbedtls/rsa.h"
86 #include "mbedtls/sha1.h"
87 #include "mbedtls/sha256.h"
88 #include "mbedtls/sha512.h"
89 #include "mbedtls/xtea.h"
91 #define ARRAY_LENGTH( array ) ( sizeof( array ) / sizeof( *( array ) ) )
93 /* constant-time buffer comparison */
94 static inline int safer_memcmp(const uint8_t *a, const uint8_t *b, size_t n) {
95 size_t i;
96 unsigned char diff = 0;
98 for (i = 0; i < n; i++)
99 diff |= a[i] ^ b[i];
101 return (diff);
106 /****************************************************************/
107 /* Global data, support functions and library management */
108 /****************************************************************/
110 static int key_type_is_raw_bytes(psa_key_type_t type) {
111 return (PSA_KEY_TYPE_IS_UNSTRUCTURED(type));
114 /* Values for psa_global_data_t::rng_state */
115 #define RNG_NOT_INITIALIZED 0
116 #define RNG_INITIALIZED 1
117 #define RNG_SEEDED 2
119 typedef struct {
120 mbedtls_psa_random_context_t rng;
121 unsigned initialized : 1;
122 unsigned rng_state : 2;
123 } psa_global_data_t;
125 static psa_global_data_t global_data;
127 #if !defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
128 mbedtls_psa_drbg_context_t *const mbedtls_psa_random_state =
129 &global_data.rng.drbg;
130 #endif
132 #define GUARD_MODULE_INITIALIZED \
133 if( global_data.initialized == 0 ) \
134 return( PSA_ERROR_BAD_STATE );
136 psa_status_t mbedtls_to_psa_error(int ret) {
137 /* Mbed TLS error codes can combine a high-level error code and a
138 * low-level error code. The low-level error usually reflects the
139 * root cause better, so dispatch on that preferably. */
140 int low_level_ret = - (-ret & 0x007f);
141 switch (low_level_ret != 0 ? low_level_ret : ret) {
142 case 0:
143 return (PSA_SUCCESS);
145 case MBEDTLS_ERR_AES_INVALID_KEY_LENGTH:
146 case MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH:
147 case MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE:
148 return (PSA_ERROR_NOT_SUPPORTED);
149 case MBEDTLS_ERR_AES_HW_ACCEL_FAILED:
150 return (PSA_ERROR_HARDWARE_FAILURE);
152 case MBEDTLS_ERR_ARC4_HW_ACCEL_FAILED:
153 return (PSA_ERROR_HARDWARE_FAILURE);
155 case MBEDTLS_ERR_ASN1_OUT_OF_DATA:
156 case MBEDTLS_ERR_ASN1_UNEXPECTED_TAG:
157 case MBEDTLS_ERR_ASN1_INVALID_LENGTH:
158 case MBEDTLS_ERR_ASN1_LENGTH_MISMATCH:
159 case MBEDTLS_ERR_ASN1_INVALID_DATA:
160 return (PSA_ERROR_INVALID_ARGUMENT);
161 case MBEDTLS_ERR_ASN1_ALLOC_FAILED:
162 return (PSA_ERROR_INSUFFICIENT_MEMORY);
163 case MBEDTLS_ERR_ASN1_BUF_TOO_SMALL:
164 return (PSA_ERROR_BUFFER_TOO_SMALL);
166 #if defined(MBEDTLS_ERR_BLOWFISH_BAD_INPUT_DATA)
167 case MBEDTLS_ERR_BLOWFISH_BAD_INPUT_DATA:
168 #elif defined(MBEDTLS_ERR_BLOWFISH_INVALID_KEY_LENGTH)
169 case MBEDTLS_ERR_BLOWFISH_INVALID_KEY_LENGTH:
170 #endif
171 case MBEDTLS_ERR_BLOWFISH_INVALID_INPUT_LENGTH:
172 return (PSA_ERROR_NOT_SUPPORTED);
173 case MBEDTLS_ERR_BLOWFISH_HW_ACCEL_FAILED:
174 return (PSA_ERROR_HARDWARE_FAILURE);
176 #if defined(MBEDTLS_ERR_CAMELLIA_BAD_INPUT_DATA)
177 case MBEDTLS_ERR_CAMELLIA_BAD_INPUT_DATA:
178 #elif defined(MBEDTLS_ERR_CAMELLIA_INVALID_KEY_LENGTH)
179 case MBEDTLS_ERR_CAMELLIA_INVALID_KEY_LENGTH:
180 #endif
181 case MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH:
182 return (PSA_ERROR_NOT_SUPPORTED);
183 case MBEDTLS_ERR_CAMELLIA_HW_ACCEL_FAILED:
184 return (PSA_ERROR_HARDWARE_FAILURE);
186 case MBEDTLS_ERR_CCM_BAD_INPUT:
187 return (PSA_ERROR_INVALID_ARGUMENT);
188 case MBEDTLS_ERR_CCM_AUTH_FAILED:
189 return (PSA_ERROR_INVALID_SIGNATURE);
190 case MBEDTLS_ERR_CCM_HW_ACCEL_FAILED:
191 return (PSA_ERROR_HARDWARE_FAILURE);
193 case MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA:
194 return (PSA_ERROR_INVALID_ARGUMENT);
196 case MBEDTLS_ERR_CHACHAPOLY_BAD_STATE:
197 return (PSA_ERROR_BAD_STATE);
198 case MBEDTLS_ERR_CHACHAPOLY_AUTH_FAILED:
199 return (PSA_ERROR_INVALID_SIGNATURE);
201 case MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE:
202 return (PSA_ERROR_NOT_SUPPORTED);
203 case MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA:
204 return (PSA_ERROR_INVALID_ARGUMENT);
205 case MBEDTLS_ERR_CIPHER_ALLOC_FAILED:
206 return (PSA_ERROR_INSUFFICIENT_MEMORY);
207 case MBEDTLS_ERR_CIPHER_INVALID_PADDING:
208 return (PSA_ERROR_INVALID_PADDING);
209 case MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED:
210 return (PSA_ERROR_INVALID_ARGUMENT);
211 case MBEDTLS_ERR_CIPHER_AUTH_FAILED:
212 return (PSA_ERROR_INVALID_SIGNATURE);
213 case MBEDTLS_ERR_CIPHER_INVALID_CONTEXT:
214 return (PSA_ERROR_CORRUPTION_DETECTED);
215 case MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED:
216 return (PSA_ERROR_HARDWARE_FAILURE);
218 case MBEDTLS_ERR_CMAC_HW_ACCEL_FAILED:
219 return (PSA_ERROR_HARDWARE_FAILURE);
221 #if !( defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG) || \
222 defined(MBEDTLS_PSA_HMAC_DRBG_MD_TYPE) )
223 /* Only check CTR_DRBG error codes if underlying mbedtls_xxx
224 * functions are passed a CTR_DRBG instance. */
225 case MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED:
226 return (PSA_ERROR_INSUFFICIENT_ENTROPY);
227 case MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG:
228 case MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG:
229 return (PSA_ERROR_NOT_SUPPORTED);
230 case MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR:
231 return (PSA_ERROR_INSUFFICIENT_ENTROPY);
232 #endif
234 case MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH:
235 return (PSA_ERROR_NOT_SUPPORTED);
236 case MBEDTLS_ERR_DES_HW_ACCEL_FAILED:
237 return (PSA_ERROR_HARDWARE_FAILURE);
239 case MBEDTLS_ERR_ENTROPY_NO_SOURCES_DEFINED:
240 case MBEDTLS_ERR_ENTROPY_NO_STRONG_SOURCE:
241 case MBEDTLS_ERR_ENTROPY_SOURCE_FAILED:
242 return (PSA_ERROR_INSUFFICIENT_ENTROPY);
244 case MBEDTLS_ERR_GCM_AUTH_FAILED:
245 return (PSA_ERROR_INVALID_SIGNATURE);
246 case MBEDTLS_ERR_GCM_BAD_INPUT:
247 return (PSA_ERROR_INVALID_ARGUMENT);
248 case MBEDTLS_ERR_GCM_HW_ACCEL_FAILED:
249 return (PSA_ERROR_HARDWARE_FAILURE);
251 #if !defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG) && \
252 defined(MBEDTLS_PSA_HMAC_DRBG_MD_TYPE)
253 /* Only check HMAC_DRBG error codes if underlying mbedtls_xxx
254 * functions are passed a HMAC_DRBG instance. */
255 case MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED:
256 return (PSA_ERROR_INSUFFICIENT_ENTROPY);
257 case MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG:
258 case MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG:
259 return (PSA_ERROR_NOT_SUPPORTED);
260 case MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR:
261 return (PSA_ERROR_INSUFFICIENT_ENTROPY);
262 #endif
264 case MBEDTLS_ERR_MD2_HW_ACCEL_FAILED:
265 case MBEDTLS_ERR_MD4_HW_ACCEL_FAILED:
266 case MBEDTLS_ERR_MD5_HW_ACCEL_FAILED:
267 return (PSA_ERROR_HARDWARE_FAILURE);
269 case MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE:
270 return (PSA_ERROR_NOT_SUPPORTED);
271 case MBEDTLS_ERR_MD_BAD_INPUT_DATA:
272 return (PSA_ERROR_INVALID_ARGUMENT);
273 case MBEDTLS_ERR_MD_ALLOC_FAILED:
274 return (PSA_ERROR_INSUFFICIENT_MEMORY);
275 case MBEDTLS_ERR_MD_FILE_IO_ERROR:
276 return (PSA_ERROR_STORAGE_FAILURE);
277 case MBEDTLS_ERR_MD_HW_ACCEL_FAILED:
278 return (PSA_ERROR_HARDWARE_FAILURE);
280 case MBEDTLS_ERR_MPI_FILE_IO_ERROR:
281 return (PSA_ERROR_STORAGE_FAILURE);
282 case MBEDTLS_ERR_MPI_BAD_INPUT_DATA:
283 return (PSA_ERROR_INVALID_ARGUMENT);
284 case MBEDTLS_ERR_MPI_INVALID_CHARACTER:
285 return (PSA_ERROR_INVALID_ARGUMENT);
286 case MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL:
287 return (PSA_ERROR_BUFFER_TOO_SMALL);
288 case MBEDTLS_ERR_MPI_NEGATIVE_VALUE:
289 return (PSA_ERROR_INVALID_ARGUMENT);
290 case MBEDTLS_ERR_MPI_DIVISION_BY_ZERO:
291 return (PSA_ERROR_INVALID_ARGUMENT);
292 case MBEDTLS_ERR_MPI_NOT_ACCEPTABLE:
293 return (PSA_ERROR_INVALID_ARGUMENT);
294 case MBEDTLS_ERR_MPI_ALLOC_FAILED:
295 return (PSA_ERROR_INSUFFICIENT_MEMORY);
297 case MBEDTLS_ERR_PK_ALLOC_FAILED:
298 return (PSA_ERROR_INSUFFICIENT_MEMORY);
299 case MBEDTLS_ERR_PK_TYPE_MISMATCH:
300 case MBEDTLS_ERR_PK_BAD_INPUT_DATA:
301 return (PSA_ERROR_INVALID_ARGUMENT);
302 case MBEDTLS_ERR_PK_FILE_IO_ERROR:
303 return (PSA_ERROR_STORAGE_FAILURE);
304 case MBEDTLS_ERR_PK_KEY_INVALID_VERSION:
305 case MBEDTLS_ERR_PK_KEY_INVALID_FORMAT:
306 return (PSA_ERROR_INVALID_ARGUMENT);
307 case MBEDTLS_ERR_PK_UNKNOWN_PK_ALG:
308 return (PSA_ERROR_NOT_SUPPORTED);
309 case MBEDTLS_ERR_PK_PASSWORD_REQUIRED:
310 case MBEDTLS_ERR_PK_PASSWORD_MISMATCH:
311 return (PSA_ERROR_NOT_PERMITTED);
312 case MBEDTLS_ERR_PK_INVALID_PUBKEY:
313 return (PSA_ERROR_INVALID_ARGUMENT);
314 case MBEDTLS_ERR_PK_INVALID_ALG:
315 case MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE:
316 case MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE:
317 return (PSA_ERROR_NOT_SUPPORTED);
318 case MBEDTLS_ERR_PK_SIG_LEN_MISMATCH:
319 return (PSA_ERROR_INVALID_SIGNATURE);
320 case MBEDTLS_ERR_PK_HW_ACCEL_FAILED:
321 return (PSA_ERROR_HARDWARE_FAILURE);
323 case MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED:
324 return (PSA_ERROR_HARDWARE_FAILURE);
325 case MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED:
326 return (PSA_ERROR_NOT_SUPPORTED);
328 case MBEDTLS_ERR_RIPEMD160_HW_ACCEL_FAILED:
329 return (PSA_ERROR_HARDWARE_FAILURE);
331 case MBEDTLS_ERR_RSA_BAD_INPUT_DATA:
332 return (PSA_ERROR_INVALID_ARGUMENT);
333 case MBEDTLS_ERR_RSA_INVALID_PADDING:
334 return (PSA_ERROR_INVALID_PADDING);
335 case MBEDTLS_ERR_RSA_KEY_GEN_FAILED:
336 return (PSA_ERROR_HARDWARE_FAILURE);
337 case MBEDTLS_ERR_RSA_KEY_CHECK_FAILED:
338 return (PSA_ERROR_INVALID_ARGUMENT);
339 case MBEDTLS_ERR_RSA_PUBLIC_FAILED:
340 case MBEDTLS_ERR_RSA_PRIVATE_FAILED:
341 return (PSA_ERROR_CORRUPTION_DETECTED);
342 case MBEDTLS_ERR_RSA_VERIFY_FAILED:
343 return (PSA_ERROR_INVALID_SIGNATURE);
344 case MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE:
345 return (PSA_ERROR_BUFFER_TOO_SMALL);
346 case MBEDTLS_ERR_RSA_RNG_FAILED:
347 return (PSA_ERROR_INSUFFICIENT_ENTROPY);
348 case MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION:
349 return (PSA_ERROR_NOT_SUPPORTED);
350 case MBEDTLS_ERR_RSA_HW_ACCEL_FAILED:
351 return (PSA_ERROR_HARDWARE_FAILURE);
353 case MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED:
354 case MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED:
355 case MBEDTLS_ERR_SHA512_HW_ACCEL_FAILED:
356 return (PSA_ERROR_HARDWARE_FAILURE);
358 case MBEDTLS_ERR_XTEA_INVALID_INPUT_LENGTH:
359 return (PSA_ERROR_INVALID_ARGUMENT);
360 case MBEDTLS_ERR_XTEA_HW_ACCEL_FAILED:
361 return (PSA_ERROR_HARDWARE_FAILURE);
363 case MBEDTLS_ERR_ECP_BAD_INPUT_DATA:
364 case MBEDTLS_ERR_ECP_INVALID_KEY:
365 return (PSA_ERROR_INVALID_ARGUMENT);
366 case MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL:
367 return (PSA_ERROR_BUFFER_TOO_SMALL);
368 case MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE:
369 return (PSA_ERROR_NOT_SUPPORTED);
370 case MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH:
371 case MBEDTLS_ERR_ECP_VERIFY_FAILED:
372 return (PSA_ERROR_INVALID_SIGNATURE);
373 case MBEDTLS_ERR_ECP_ALLOC_FAILED:
374 return (PSA_ERROR_INSUFFICIENT_MEMORY);
375 case MBEDTLS_ERR_ECP_RANDOM_FAILED:
376 return (PSA_ERROR_INSUFFICIENT_ENTROPY);
377 case MBEDTLS_ERR_ECP_HW_ACCEL_FAILED:
378 return (PSA_ERROR_HARDWARE_FAILURE);
380 case MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED:
381 return (PSA_ERROR_CORRUPTION_DETECTED);
383 default:
384 return (PSA_ERROR_GENERIC_ERROR);
391 /****************************************************************/
392 /* Key management */
393 /****************************************************************/
395 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
396 static inline int psa_key_slot_is_external(const psa_key_slot_t *slot) {
397 return (psa_key_lifetime_is_external(slot->attr.lifetime));
399 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
401 /* For now the MBEDTLS_PSA_ACCEL_ guards are also used here since the
402 * current test driver in key_management.c is using this function
403 * when accelerators are used for ECC key pair and public key.
404 * Once that dependency is resolved these guards can be removed.
406 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) || \
407 defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY) || \
408 defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR) || \
409 defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_PUBLIC_KEY)
410 mbedtls_ecp_group_id mbedtls_ecc_group_of_psa(psa_ecc_family_t curve,
411 size_t bits,
412 int bits_is_sloppy) {
413 switch (curve) {
414 case PSA_ECC_FAMILY_SECP_R1:
415 switch (bits) {
416 case 192:
417 return (MBEDTLS_ECP_DP_SECP192R1);
418 case 224:
419 return (MBEDTLS_ECP_DP_SECP224R1);
420 case 256:
421 return (MBEDTLS_ECP_DP_SECP256R1);
422 case 384:
423 return (MBEDTLS_ECP_DP_SECP384R1);
424 case 521:
425 return (MBEDTLS_ECP_DP_SECP521R1);
426 case 528:
427 if (bits_is_sloppy)
428 return (MBEDTLS_ECP_DP_SECP521R1);
429 break;
431 break;
433 case PSA_ECC_FAMILY_BRAINPOOL_P_R1:
434 switch (bits) {
435 case 256:
436 return (MBEDTLS_ECP_DP_BP256R1);
437 case 384:
438 return (MBEDTLS_ECP_DP_BP384R1);
439 case 512:
440 return (MBEDTLS_ECP_DP_BP512R1);
442 break;
444 case PSA_ECC_FAMILY_MONTGOMERY:
445 switch (bits) {
446 case 255:
447 return (MBEDTLS_ECP_DP_CURVE25519);
448 case 256:
449 if (bits_is_sloppy)
450 return (MBEDTLS_ECP_DP_CURVE25519);
451 break;
452 case 448:
453 return (MBEDTLS_ECP_DP_CURVE448);
455 break;
457 case PSA_ECC_FAMILY_SECP_K1:
458 switch (bits) {
459 case 192:
460 return (MBEDTLS_ECP_DP_SECP192K1);
461 case 224:
462 return (MBEDTLS_ECP_DP_SECP224K1);
463 case 256:
464 return (MBEDTLS_ECP_DP_SECP256K1);
466 break;
469 return (MBEDTLS_ECP_DP_NONE);
471 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) ||
472 * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY) ||
473 * defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR) ||
474 * defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_PUBLIC_KEY) */
476 static psa_status_t validate_unstructured_key_bit_size(psa_key_type_t type,
477 size_t bits) {
478 /* Check that the bit size is acceptable for the key type */
479 switch (type) {
480 case PSA_KEY_TYPE_RAW_DATA:
481 case PSA_KEY_TYPE_HMAC:
482 case PSA_KEY_TYPE_DERIVE:
483 break;
484 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_AES)
485 case PSA_KEY_TYPE_AES:
486 if (bits != 128 && bits != 192 && bits != 256)
487 return (PSA_ERROR_INVALID_ARGUMENT);
488 break;
489 #endif
490 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_CAMELLIA)
491 case PSA_KEY_TYPE_CAMELLIA:
492 if (bits != 128 && bits != 192 && bits != 256)
493 return (PSA_ERROR_INVALID_ARGUMENT);
494 break;
495 #endif
496 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES)
497 case PSA_KEY_TYPE_DES:
498 if (bits != 64 && bits != 128 && bits != 192)
499 return (PSA_ERROR_INVALID_ARGUMENT);
500 break;
501 #endif
502 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ARC4)
503 case PSA_KEY_TYPE_ARC4:
504 if (bits < 8 || bits > 2048)
505 return (PSA_ERROR_INVALID_ARGUMENT);
506 break;
507 #endif
508 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_CHACHA20)
509 case PSA_KEY_TYPE_CHACHA20:
510 if (bits != 256)
511 return (PSA_ERROR_INVALID_ARGUMENT);
512 break;
513 #endif
514 default:
515 return (PSA_ERROR_NOT_SUPPORTED);
517 if (bits % 8 != 0)
518 return (PSA_ERROR_INVALID_ARGUMENT);
520 return (PSA_SUCCESS);
523 /** Return the size of the key in the given slot, in bits.
525 * \param[in] slot A key slot.
527 * \return The key size in bits, read from the metadata in the slot.
529 static inline size_t psa_get_key_slot_bits(const psa_key_slot_t *slot) {
530 return (slot->attr.bits);
533 /** Check whether a given key type is valid for use with a given MAC algorithm
535 * Upon successful return of this function, the behavior of #PSA_MAC_LENGTH
536 * when called with the validated \p algorithm and \p key_type is well-defined.
538 * \param[in] algorithm The specific MAC algorithm (can be wildcard).
539 * \param[in] key_type The key type of the key to be used with the
540 * \p algorithm.
542 * \retval #PSA_SUCCESS
543 * The \p key_type is valid for use with the \p algorithm
544 * \retval #PSA_ERROR_INVALID_ARGUMENT
545 * The \p key_type is not valid for use with the \p algorithm
547 MBEDTLS_STATIC_TESTABLE psa_status_t psa_mac_key_can_do(
548 psa_algorithm_t algorithm,
549 psa_key_type_t key_type) {
550 if (PSA_ALG_IS_HMAC(algorithm)) {
551 if (key_type == PSA_KEY_TYPE_HMAC)
552 return (PSA_SUCCESS);
555 if (PSA_ALG_IS_BLOCK_CIPHER_MAC(algorithm)) {
556 /* Check that we're calling PSA_BLOCK_CIPHER_BLOCK_LENGTH with a cipher
557 * key. */
558 if ((key_type & PSA_KEY_TYPE_CATEGORY_MASK) ==
559 PSA_KEY_TYPE_CATEGORY_SYMMETRIC) {
560 /* PSA_BLOCK_CIPHER_BLOCK_LENGTH returns 1 for stream ciphers and
561 * the block length (larger than 1) for block ciphers. */
562 if (PSA_BLOCK_CIPHER_BLOCK_LENGTH(key_type) > 1)
563 return (PSA_SUCCESS);
567 return (PSA_ERROR_INVALID_ARGUMENT);
570 /** Try to allocate a buffer to an empty key slot.
572 * \param[in,out] slot Key slot to attach buffer to.
573 * \param[in] buffer_length Requested size of the buffer.
575 * \retval #PSA_SUCCESS
576 * The buffer has been successfully allocated.
577 * \retval #PSA_ERROR_INSUFFICIENT_MEMORY
578 * Not enough memory was available for allocation.
579 * \retval #PSA_ERROR_ALREADY_EXISTS
580 * Trying to allocate a buffer to a non-empty key slot.
582 static psa_status_t psa_allocate_buffer_to_slot(psa_key_slot_t *slot,
583 size_t buffer_length) {
584 if (slot->key.data != NULL)
585 return (PSA_ERROR_ALREADY_EXISTS);
587 slot->key.data = mbedtls_calloc(1, buffer_length);
588 if (slot->key.data == NULL)
589 return (PSA_ERROR_INSUFFICIENT_MEMORY);
591 slot->key.bytes = buffer_length;
592 return (PSA_SUCCESS);
595 psa_status_t psa_copy_key_material_into_slot(psa_key_slot_t *slot,
596 const uint8_t *data,
597 size_t data_length) {
598 psa_status_t status = psa_allocate_buffer_to_slot(slot,
599 data_length);
600 if (status != PSA_SUCCESS)
601 return (status);
603 memcpy(slot->key.data, data, data_length);
604 return (PSA_SUCCESS);
607 psa_status_t psa_import_key_into_slot(
608 const psa_key_attributes_t *attributes,
609 const uint8_t *data, size_t data_length,
610 uint8_t *key_buffer, size_t key_buffer_size,
611 size_t *key_buffer_length, size_t *bits) {
612 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
613 psa_key_type_t type = attributes->core.type;
615 /* zero-length keys are never supported. */
616 if (data_length == 0)
617 return (PSA_ERROR_NOT_SUPPORTED);
619 if (key_type_is_raw_bytes(type)) {
620 *bits = PSA_BYTES_TO_BITS(data_length);
622 /* Ensure that the bytes-to-bits conversion hasn't overflown. */
623 if (data_length > SIZE_MAX / 8)
624 return (PSA_ERROR_NOT_SUPPORTED);
626 /* Enforce a size limit, and in particular ensure that the bit
627 * size fits in its representation type. */
628 if ((*bits) > PSA_MAX_KEY_BITS)
629 return (PSA_ERROR_NOT_SUPPORTED);
631 status = validate_unstructured_key_bit_size(type, *bits);
632 if (status != PSA_SUCCESS)
633 return (status);
635 /* Copy the key material. */
636 memcpy(key_buffer, data, data_length);
637 *key_buffer_length = data_length;
638 (void)key_buffer_size;
640 return (PSA_SUCCESS);
641 } else if (PSA_KEY_TYPE_IS_ASYMMETRIC(type)) {
642 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) || \
643 defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY)
644 if (PSA_KEY_TYPE_IS_ECC(type)) {
645 return (mbedtls_psa_ecp_import_key(attributes,
646 data, data_length,
647 key_buffer, key_buffer_size,
648 key_buffer_length,
649 bits));
651 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) ||
652 * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY) */
653 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) || \
654 defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY)
655 if (PSA_KEY_TYPE_IS_RSA(type)) {
656 return (mbedtls_psa_rsa_import_key(attributes,
657 data, data_length,
658 key_buffer, key_buffer_size,
659 key_buffer_length,
660 bits));
662 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) ||
663 * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY) */
666 return (PSA_ERROR_NOT_SUPPORTED);
669 /** Calculate the intersection of two algorithm usage policies.
671 * Return 0 (which allows no operation) on incompatibility.
673 static psa_algorithm_t psa_key_policy_algorithm_intersection(
674 psa_key_type_t key_type,
675 psa_algorithm_t alg1,
676 psa_algorithm_t alg2) {
677 /* Common case: both sides actually specify the same policy. */
678 if (alg1 == alg2)
679 return (alg1);
680 /* If the policies are from the same hash-and-sign family, check
681 * if one is a wildcard. If so the other has the specific algorithm. */
682 if (PSA_ALG_IS_HASH_AND_SIGN(alg1) &&
683 PSA_ALG_IS_HASH_AND_SIGN(alg2) &&
684 (alg1 & ~PSA_ALG_HASH_MASK) == (alg2 & ~PSA_ALG_HASH_MASK)) {
685 if (PSA_ALG_SIGN_GET_HASH(alg1) == PSA_ALG_ANY_HASH)
686 return (alg2);
687 if (PSA_ALG_SIGN_GET_HASH(alg2) == PSA_ALG_ANY_HASH)
688 return (alg1);
690 /* If the policies are from the same AEAD family, check whether
691 * one of them is a minimum-tag-length wildcard. Calculate the most
692 * restrictive tag length. */
693 if (PSA_ALG_IS_AEAD(alg1) && PSA_ALG_IS_AEAD(alg2) &&
694 (PSA_ALG_AEAD_WITH_SHORTENED_TAG(alg1, 0) ==
695 PSA_ALG_AEAD_WITH_SHORTENED_TAG(alg2, 0))) {
696 size_t alg1_len = PSA_ALG_AEAD_GET_TAG_LENGTH(alg1);
697 size_t alg2_len = PSA_ALG_AEAD_GET_TAG_LENGTH(alg2);
698 size_t restricted_len = alg1_len > alg2_len ? alg1_len : alg2_len;
700 /* If both are wildcards, return most restrictive wildcard */
701 if (((alg1 & PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG) != 0) &&
702 ((alg2 & PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG) != 0)) {
703 return (PSA_ALG_AEAD_WITH_AT_LEAST_THIS_LENGTH_TAG(
704 alg1, restricted_len));
706 /* If only one is a wildcard, return specific algorithm if compatible. */
707 if (((alg1 & PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG) != 0) &&
708 (alg1_len <= alg2_len)) {
709 return (alg2);
711 if (((alg2 & PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG) != 0) &&
712 (alg2_len <= alg1_len)) {
713 return (alg1);
716 /* If the policies are from the same MAC family, check whether one
717 * of them is a minimum-MAC-length policy. Calculate the most
718 * restrictive tag length. */
719 if (PSA_ALG_IS_MAC(alg1) && PSA_ALG_IS_MAC(alg2) &&
720 (PSA_ALG_FULL_LENGTH_MAC(alg1) ==
721 PSA_ALG_FULL_LENGTH_MAC(alg2))) {
722 /* Validate the combination of key type and algorithm. Since the base
723 * algorithm of alg1 and alg2 are the same, we only need this once. */
724 if (PSA_SUCCESS != psa_mac_key_can_do(alg1, key_type))
725 return (0);
727 /* Get the (exact or at-least) output lengths for both sides of the
728 * requested intersection. None of the currently supported algorithms
729 * have an output length dependent on the actual key size, so setting it
730 * to a bogus value of 0 is currently OK.
732 * Note that for at-least-this-length wildcard algorithms, the output
733 * length is set to the shortest allowed length, which allows us to
734 * calculate the most restrictive tag length for the intersection. */
735 size_t alg1_len = PSA_MAC_LENGTH(key_type, 0, alg1);
736 size_t alg2_len = PSA_MAC_LENGTH(key_type, 0, alg2);
737 size_t restricted_len = alg1_len > alg2_len ? alg1_len : alg2_len;
739 /* If both are wildcards, return most restrictive wildcard */
740 if (((alg1 & PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG) != 0) &&
741 ((alg2 & PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG) != 0)) {
742 return (PSA_ALG_AT_LEAST_THIS_LENGTH_MAC(alg1, restricted_len));
745 /* If only one is an at-least-this-length policy, the intersection would
746 * be the other (fixed-length) policy as long as said fixed length is
747 * equal to or larger than the shortest allowed length. */
748 if ((alg1 & PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG) != 0) {
749 return ((alg1_len <= alg2_len) ? alg2 : 0);
751 if ((alg2 & PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG) != 0) {
752 return ((alg2_len <= alg1_len) ? alg1 : 0);
755 /* If none of them are wildcards, check whether they define the same tag
756 * length. This is still possible here when one is default-length and
757 * the other specific-length. Ensure to always return the
758 * specific-length version for the intersection. */
759 if (alg1_len == alg2_len)
760 return (PSA_ALG_TRUNCATED_MAC(alg1, alg1_len));
762 /* If the policies are incompatible, allow nothing. */
763 return (0);
766 static int psa_key_algorithm_permits(psa_key_type_t key_type,
767 psa_algorithm_t policy_alg,
768 psa_algorithm_t requested_alg) {
769 /* Common case: the policy only allows requested_alg. */
770 if (requested_alg == policy_alg)
771 return (1);
772 /* If policy_alg is a hash-and-sign with a wildcard for the hash,
773 * and requested_alg is the same hash-and-sign family with any hash,
774 * then requested_alg is compliant with policy_alg. */
775 if (PSA_ALG_IS_HASH_AND_SIGN(requested_alg) &&
776 PSA_ALG_SIGN_GET_HASH(policy_alg) == PSA_ALG_ANY_HASH) {
777 return ((policy_alg & ~PSA_ALG_HASH_MASK) ==
778 (requested_alg & ~PSA_ALG_HASH_MASK));
780 /* If policy_alg is a wildcard AEAD algorithm of the same base as
781 * the requested algorithm, check the requested tag length to be
782 * equal-length or longer than the wildcard-specified length. */
783 if (PSA_ALG_IS_AEAD(policy_alg) &&
784 PSA_ALG_IS_AEAD(requested_alg) &&
785 (PSA_ALG_AEAD_WITH_SHORTENED_TAG(policy_alg, 0) ==
786 PSA_ALG_AEAD_WITH_SHORTENED_TAG(requested_alg, 0)) &&
787 ((policy_alg & PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG) != 0)) {
788 return (PSA_ALG_AEAD_GET_TAG_LENGTH(policy_alg) <=
789 PSA_ALG_AEAD_GET_TAG_LENGTH(requested_alg));
791 /* If policy_alg is a MAC algorithm of the same base as the requested
792 * algorithm, check whether their MAC lengths are compatible. */
793 if (PSA_ALG_IS_MAC(policy_alg) &&
794 PSA_ALG_IS_MAC(requested_alg) &&
795 (PSA_ALG_FULL_LENGTH_MAC(policy_alg) ==
796 PSA_ALG_FULL_LENGTH_MAC(requested_alg))) {
797 /* Validate the combination of key type and algorithm. Since the policy
798 * and requested algorithms are the same, we only need this once. */
799 if (PSA_SUCCESS != psa_mac_key_can_do(policy_alg, key_type))
800 return (0);
802 /* Get both the requested output length for the algorithm which is to be
803 * verified, and the default output length for the base algorithm.
804 * Note that none of the currently supported algorithms have an output
805 * length dependent on actual key size, so setting it to a bogus value
806 * of 0 is currently OK. */
807 size_t requested_output_length = PSA_MAC_LENGTH(
808 key_type, 0, requested_alg);
809 size_t default_output_length = PSA_MAC_LENGTH(
810 key_type, 0,
811 PSA_ALG_FULL_LENGTH_MAC(requested_alg));
813 /* If the policy is default-length, only allow an algorithm with
814 * a declared exact-length matching the default. */
815 if (PSA_MAC_TRUNCATED_LENGTH(policy_alg) == 0)
816 return (requested_output_length == default_output_length);
818 /* If the requested algorithm is default-length, allow it if the policy
819 * length exactly matches the default length. */
820 if (PSA_MAC_TRUNCATED_LENGTH(requested_alg) == 0 &&
821 PSA_MAC_TRUNCATED_LENGTH(policy_alg) == default_output_length) {
822 return (1);
825 /* If policy_alg is an at-least-this-length wildcard MAC algorithm,
826 * check for the requested MAC length to be equal to or longer than the
827 * minimum allowed length. */
828 if ((policy_alg & PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG) != 0) {
829 return (PSA_MAC_TRUNCATED_LENGTH(policy_alg) <=
830 requested_output_length);
833 /* If policy_alg is a generic key agreement operation, then using it for
834 * a key derivation with that key agreement should also be allowed. This
835 * behaviour is expected to be defined in a future specification version. */
836 if (PSA_ALG_IS_RAW_KEY_AGREEMENT(policy_alg) &&
837 PSA_ALG_IS_KEY_AGREEMENT(requested_alg)) {
838 return (PSA_ALG_KEY_AGREEMENT_GET_BASE(requested_alg) ==
839 policy_alg);
841 /* If it isn't explicitly permitted, it's forbidden. */
842 return (0);
845 /** Test whether a policy permits an algorithm.
847 * The caller must test usage flags separately.
849 * \note This function requires providing the key type for which the policy is
850 * being validated, since some algorithm policy definitions (e.g. MAC)
851 * have different properties depending on what kind of cipher it is
852 * combined with.
854 * \retval PSA_SUCCESS When \p alg is a specific algorithm
855 * allowed by the \p policy.
856 * \retval PSA_ERROR_INVALID_ARGUMENT When \p alg is not a specific algorithm
857 * \retval PSA_ERROR_NOT_PERMITTED When \p alg is a specific algorithm, but
858 * the \p policy does not allow it.
860 static psa_status_t psa_key_policy_permits(const psa_key_policy_t *policy,
861 psa_key_type_t key_type,
862 psa_algorithm_t alg) {
863 /* '0' is not a valid algorithm */
864 if (alg == 0)
865 return (PSA_ERROR_INVALID_ARGUMENT);
867 /* A requested algorithm cannot be a wildcard. */
868 if (PSA_ALG_IS_WILDCARD(alg))
869 return (PSA_ERROR_INVALID_ARGUMENT);
871 if (psa_key_algorithm_permits(key_type, policy->alg, alg) ||
872 psa_key_algorithm_permits(key_type, policy->alg2, alg))
873 return (PSA_SUCCESS);
874 else
875 return (PSA_ERROR_NOT_PERMITTED);
878 /** Restrict a key policy based on a constraint.
880 * \note This function requires providing the key type for which the policy is
881 * being restricted, since some algorithm policy definitions (e.g. MAC)
882 * have different properties depending on what kind of cipher it is
883 * combined with.
885 * \param[in] key_type The key type for which to restrict the policy
886 * \param[in,out] policy The policy to restrict.
887 * \param[in] constraint The policy constraint to apply.
889 * \retval #PSA_SUCCESS
890 * \c *policy contains the intersection of the original value of
891 * \c *policy and \c *constraint.
892 * \retval #PSA_ERROR_INVALID_ARGUMENT
893 * \c key_type, \c *policy and \c *constraint are incompatible.
894 * \c *policy is unchanged.
896 static psa_status_t psa_restrict_key_policy(
897 psa_key_type_t key_type,
898 psa_key_policy_t *policy,
899 const psa_key_policy_t *constraint) {
900 psa_algorithm_t intersection_alg =
901 psa_key_policy_algorithm_intersection(key_type, policy->alg,
902 constraint->alg);
903 psa_algorithm_t intersection_alg2 =
904 psa_key_policy_algorithm_intersection(key_type, policy->alg2,
905 constraint->alg2);
906 if (intersection_alg == 0 && policy->alg != 0 && constraint->alg != 0)
907 return (PSA_ERROR_INVALID_ARGUMENT);
908 if (intersection_alg2 == 0 && policy->alg2 != 0 && constraint->alg2 != 0)
909 return (PSA_ERROR_INVALID_ARGUMENT);
910 policy->usage &= constraint->usage;
911 policy->alg = intersection_alg;
912 policy->alg2 = intersection_alg2;
913 return (PSA_SUCCESS);
916 /** Get the description of a key given its identifier and policy constraints
917 * and lock it.
919 * The key must have allow all the usage flags set in \p usage. If \p alg is
920 * nonzero, the key must allow operations with this algorithm. If \p alg is
921 * zero, the algorithm is not checked.
923 * In case of a persistent key, the function loads the description of the key
924 * into a key slot if not already done.
926 * On success, the returned key slot is locked. It is the responsibility of
927 * the caller to unlock the key slot when it does not access it anymore.
929 static psa_status_t psa_get_and_lock_key_slot_with_policy(
930 mbedtls_svc_key_id_t key,
931 psa_key_slot_t **p_slot,
932 psa_key_usage_t usage,
933 psa_algorithm_t alg) {
934 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
935 psa_key_slot_t *slot;
937 status = psa_get_and_lock_key_slot(key, p_slot);
938 if (status != PSA_SUCCESS)
939 return (status);
940 slot = *p_slot;
942 /* Enforce that usage policy for the key slot contains all the flags
943 * required by the usage parameter. There is one exception: public
944 * keys can always be exported, so we treat public key objects as
945 * if they had the export flag. */
946 if (PSA_KEY_TYPE_IS_PUBLIC_KEY(slot->attr.type))
947 usage &= ~PSA_KEY_USAGE_EXPORT;
949 if ((slot->attr.policy.usage & usage) != usage) {
950 status = PSA_ERROR_NOT_PERMITTED;
951 goto error;
954 /* Enforce that the usage policy permits the requested algortihm. */
955 if (alg != 0) {
956 status = psa_key_policy_permits(&slot->attr.policy,
957 slot->attr.type,
958 alg);
959 if (status != PSA_SUCCESS)
960 goto error;
963 return (PSA_SUCCESS);
965 error:
966 *p_slot = NULL;
967 psa_unlock_key_slot(slot);
969 return (status);
972 /** Get a key slot containing a transparent key and lock it.
974 * A transparent key is a key for which the key material is directly
975 * available, as opposed to a key in a secure element.
977 * This is a temporary function to use instead of
978 * psa_get_and_lock_key_slot_with_policy() until secure element support is
979 * fully implemented.
981 * On success, the returned key slot is locked. It is the responsibility of the
982 * caller to unlock the key slot when it does not access it anymore.
984 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
985 static psa_status_t psa_get_and_lock_transparent_key_slot_with_policy(
986 mbedtls_svc_key_id_t key,
987 psa_key_slot_t **p_slot,
988 psa_key_usage_t usage,
989 psa_algorithm_t alg) {
990 psa_status_t status = psa_get_and_lock_key_slot_with_policy(key, p_slot,
991 usage, alg);
992 if (status != PSA_SUCCESS)
993 return (status);
995 if (psa_key_slot_is_external(*p_slot)) {
996 psa_unlock_key_slot(*p_slot);
997 *p_slot = NULL;
998 return (PSA_ERROR_NOT_SUPPORTED);
1001 return (PSA_SUCCESS);
1003 #else /* MBEDTLS_PSA_CRYPTO_SE_C */
1004 /* With no secure element support, all keys are transparent. */
1005 #define psa_get_and_lock_transparent_key_slot_with_policy( key, p_slot, usage, alg ) \
1006 psa_get_and_lock_key_slot_with_policy( key, p_slot, usage, alg )
1007 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1009 /** Wipe key data from a slot. Preserve metadata such as the policy. */
1010 static psa_status_t psa_remove_key_data_from_memory(psa_key_slot_t *slot) {
1011 /* Data pointer will always be either a valid pointer or NULL in an
1012 * initialized slot, so we can just free it. */
1013 if (slot->key.data != NULL)
1014 mbedtls_platform_zeroize(slot->key.data, slot->key.bytes);
1016 mbedtls_free(slot->key.data);
1017 slot->key.data = NULL;
1018 slot->key.bytes = 0;
1020 return (PSA_SUCCESS);
1023 /** Completely wipe a slot in memory, including its policy.
1024 * Persistent storage is not affected. */
1025 psa_status_t psa_wipe_key_slot(psa_key_slot_t *slot) {
1026 psa_status_t status = psa_remove_key_data_from_memory(slot);
1029 * As the return error code may not be handled in case of multiple errors,
1030 * do our best to report an unexpected lock counter: if available
1031 * call MBEDTLS_PARAM_FAILED that may terminate execution (if called as
1032 * part of the execution of a test suite this will stop the test suite
1033 * execution).
1035 if (slot->lock_count != 1) {
1036 #ifdef MBEDTLS_CHECK_PARAMS
1037 MBEDTLS_PARAM_FAILED(slot->lock_count == 1);
1038 #endif
1039 status = PSA_ERROR_CORRUPTION_DETECTED;
1042 /* Multipart operations may still be using the key. This is safe
1043 * because all multipart operation objects are independent from
1044 * the key slot: if they need to access the key after the setup
1045 * phase, they have a copy of the key. Note that this means that
1046 * key material can linger until all operations are completed. */
1047 /* At this point, key material and other type-specific content has
1048 * been wiped. Clear remaining metadata. We can call memset and not
1049 * zeroize because the metadata is not particularly sensitive. */
1050 memset(slot, 0, sizeof(*slot));
1051 return (status);
1054 psa_status_t psa_destroy_key(mbedtls_svc_key_id_t key) {
1055 psa_key_slot_t *slot;
1056 psa_status_t status; /* status of the last operation */
1057 psa_status_t overall_status = PSA_SUCCESS;
1058 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1059 psa_se_drv_table_entry_t *driver;
1060 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1062 if (mbedtls_svc_key_id_is_null(key))
1063 return (PSA_SUCCESS);
1066 * Get the description of the key in a key slot. In case of a persistent
1067 * key, this will load the key description from persistent memory if not
1068 * done yet. We cannot avoid this loading as without it we don't know if
1069 * the key is operated by an SE or not and this information is needed by
1070 * the current implementation.
1072 status = psa_get_and_lock_key_slot(key, &slot);
1073 if (status != PSA_SUCCESS)
1074 return (status);
1077 * If the key slot containing the key description is under access by the
1078 * library (apart from the present access), the key cannot be destroyed
1079 * yet. For the time being, just return in error. Eventually (to be
1080 * implemented), the key should be destroyed when all accesses have
1081 * stopped.
1083 if (slot->lock_count > 1) {
1084 psa_unlock_key_slot(slot);
1085 return (PSA_ERROR_GENERIC_ERROR);
1088 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1089 driver = psa_get_se_driver_entry(slot->attr.lifetime);
1090 if (driver != NULL) {
1091 /* For a key in a secure element, we need to do three things:
1092 * remove the key file in internal storage, destroy the
1093 * key inside the secure element, and update the driver's
1094 * persistent data. Start a transaction that will encompass these
1095 * three actions. */
1096 psa_crypto_prepare_transaction(PSA_CRYPTO_TRANSACTION_DESTROY_KEY);
1097 psa_crypto_transaction.key.lifetime = slot->attr.lifetime;
1098 psa_crypto_transaction.key.slot = psa_key_slot_get_slot_number(slot);
1099 psa_crypto_transaction.key.id = slot->attr.id;
1100 status = psa_crypto_save_transaction();
1101 if (status != PSA_SUCCESS) {
1102 (void) psa_crypto_stop_transaction();
1103 /* We should still try to destroy the key in the secure
1104 * element and the key metadata in storage. This is especially
1105 * important if the error is that the storage is full.
1106 * But how to do it exactly without risking an inconsistent
1107 * state after a reset?
1108 * https://github.com/ARMmbed/mbed-crypto/issues/215
1110 overall_status = status;
1111 goto exit;
1114 status = psa_destroy_se_key(driver,
1115 psa_key_slot_get_slot_number(slot));
1116 if (overall_status == PSA_SUCCESS)
1117 overall_status = status;
1119 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1121 #if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C)
1122 if (! PSA_KEY_LIFETIME_IS_VOLATILE(slot->attr.lifetime)) {
1123 status = psa_destroy_persistent_key(slot->attr.id);
1124 if (overall_status == PSA_SUCCESS)
1125 overall_status = status;
1127 /* TODO: other slots may have a copy of the same key. We should
1128 * invalidate them.
1129 * https://github.com/ARMmbed/mbed-crypto/issues/214
1132 #endif /* defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) */
1134 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1135 if (driver != NULL) {
1136 status = psa_save_se_persistent_data(driver);
1137 if (overall_status == PSA_SUCCESS)
1138 overall_status = status;
1139 status = psa_crypto_stop_transaction();
1140 if (overall_status == PSA_SUCCESS)
1141 overall_status = status;
1143 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1145 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1146 exit:
1147 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1148 status = psa_wipe_key_slot(slot);
1149 /* Prioritize CORRUPTION_DETECTED from wiping over a storage error */
1150 if (overall_status == PSA_SUCCESS)
1151 overall_status = status;
1152 return (overall_status);
1155 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) || \
1156 defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY)
1157 static psa_status_t psa_get_rsa_public_exponent(
1158 const mbedtls_rsa_context *rsa,
1159 psa_key_attributes_t *attributes) {
1160 mbedtls_mpi mpi;
1161 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1162 uint8_t *buffer = NULL;
1163 size_t buflen;
1164 mbedtls_mpi_init(&mpi);
1166 ret = mbedtls_rsa_export(rsa, NULL, NULL, NULL, NULL, &mpi);
1167 if (ret != 0)
1168 goto exit;
1169 if (mbedtls_mpi_cmp_int(&mpi, 65537) == 0) {
1170 /* It's the default value, which is reported as an empty string,
1171 * so there's nothing to do. */
1172 goto exit;
1175 buflen = mbedtls_mpi_size(&mpi);
1176 buffer = mbedtls_calloc(1, buflen);
1177 if (buffer == NULL) {
1178 ret = MBEDTLS_ERR_MPI_ALLOC_FAILED;
1179 goto exit;
1181 ret = mbedtls_mpi_write_binary(&mpi, buffer, buflen);
1182 if (ret != 0)
1183 goto exit;
1184 attributes->domain_parameters = buffer;
1185 attributes->domain_parameters_size = buflen;
1187 exit:
1188 mbedtls_mpi_free(&mpi);
1189 if (ret != 0)
1190 mbedtls_free(buffer);
1191 return (mbedtls_to_psa_error(ret));
1193 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) ||
1194 * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY) */
1196 /** Retrieve all the publicly-accessible attributes of a key.
1198 psa_status_t psa_get_key_attributes(mbedtls_svc_key_id_t key,
1199 psa_key_attributes_t *attributes) {
1200 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
1201 psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
1202 psa_key_slot_t *slot;
1204 psa_reset_key_attributes(attributes);
1206 status = psa_get_and_lock_key_slot_with_policy(key, &slot, 0, 0);
1207 if (status != PSA_SUCCESS)
1208 return (status);
1210 attributes->core = slot->attr;
1211 attributes->core.flags &= (MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY |
1212 MBEDTLS_PSA_KA_MASK_DUAL_USE);
1214 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1215 if (psa_key_slot_is_external(slot))
1216 psa_set_key_slot_number(attributes,
1217 psa_key_slot_get_slot_number(slot));
1218 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1220 switch (slot->attr.type) {
1221 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) || \
1222 defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY)
1223 case PSA_KEY_TYPE_RSA_KEY_PAIR:
1224 case PSA_KEY_TYPE_RSA_PUBLIC_KEY:
1225 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1226 /* TODO: reporting the public exponent for opaque keys
1227 * is not yet implemented.
1228 * https://github.com/ARMmbed/mbed-crypto/issues/216
1230 if (psa_key_slot_is_external(slot))
1231 break;
1232 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1234 mbedtls_rsa_context *rsa = NULL;
1236 status = mbedtls_psa_rsa_load_representation(
1237 slot->attr.type,
1238 slot->key.data,
1239 slot->key.bytes,
1240 &rsa);
1241 if (status != PSA_SUCCESS)
1242 break;
1244 status = psa_get_rsa_public_exponent(rsa,
1245 attributes);
1246 mbedtls_rsa_free(rsa);
1247 mbedtls_free(rsa);
1249 break;
1250 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) ||
1251 * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY) */
1252 default:
1253 /* Nothing else to do. */
1254 break;
1257 if (status != PSA_SUCCESS)
1258 psa_reset_key_attributes(attributes);
1260 unlock_status = psa_unlock_key_slot(slot);
1262 return ((status == PSA_SUCCESS) ? unlock_status : status);
1265 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1266 psa_status_t psa_get_key_slot_number(
1267 const psa_key_attributes_t *attributes,
1268 psa_key_slot_number_t *slot_number) {
1269 if (attributes->core.flags & MBEDTLS_PSA_KA_FLAG_HAS_SLOT_NUMBER) {
1270 *slot_number = attributes->slot_number;
1271 return (PSA_SUCCESS);
1272 } else
1273 return (PSA_ERROR_INVALID_ARGUMENT);
1275 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1277 static psa_status_t psa_export_key_buffer_internal(const uint8_t *key_buffer,
1278 size_t key_buffer_size,
1279 uint8_t *data,
1280 size_t data_size,
1281 size_t *data_length) {
1282 if (key_buffer_size > data_size)
1283 return (PSA_ERROR_BUFFER_TOO_SMALL);
1284 memcpy(data, key_buffer, key_buffer_size);
1285 memset(data + key_buffer_size, 0,
1286 data_size - key_buffer_size);
1287 *data_length = key_buffer_size;
1288 return (PSA_SUCCESS);
1291 psa_status_t psa_export_key_internal(
1292 const psa_key_attributes_t *attributes,
1293 const uint8_t *key_buffer, size_t key_buffer_size,
1294 uint8_t *data, size_t data_size, size_t *data_length) {
1295 psa_key_type_t type = attributes->core.type;
1297 if (key_type_is_raw_bytes(type) ||
1298 PSA_KEY_TYPE_IS_RSA(type) ||
1299 PSA_KEY_TYPE_IS_ECC(type)) {
1300 return (psa_export_key_buffer_internal(
1301 key_buffer, key_buffer_size,
1302 data, data_size, data_length));
1303 } else {
1304 /* This shouldn't happen in the reference implementation, but
1305 it is valid for a special-purpose implementation to omit
1306 support for exporting certain key types. */
1307 return (PSA_ERROR_NOT_SUPPORTED);
1311 psa_status_t psa_export_key(mbedtls_svc_key_id_t key,
1312 uint8_t *data,
1313 size_t data_size,
1314 size_t *data_length) {
1315 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
1316 psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
1317 psa_key_slot_t *slot;
1319 /* Reject a zero-length output buffer now, since this can never be a
1320 * valid key representation. This way we know that data must be a valid
1321 * pointer and we can do things like memset(data, ..., data_size). */
1322 if (data_size == 0)
1323 return (PSA_ERROR_BUFFER_TOO_SMALL);
1325 /* Set the key to empty now, so that even when there are errors, we always
1326 * set data_length to a value between 0 and data_size. On error, setting
1327 * the key to empty is a good choice because an empty key representation is
1328 * unlikely to be accepted anywhere. */
1329 *data_length = 0;
1331 /* Export requires the EXPORT flag. There is an exception for public keys,
1332 * which don't require any flag, but
1333 * psa_get_and_lock_key_slot_with_policy() takes care of this.
1335 status = psa_get_and_lock_key_slot_with_policy(key, &slot,
1336 PSA_KEY_USAGE_EXPORT, 0);
1337 if (status != PSA_SUCCESS)
1338 return (status);
1340 psa_key_attributes_t attributes = {
1341 .core = slot->attr
1343 status = psa_driver_wrapper_export_key(&attributes,
1344 slot->key.data, slot->key.bytes,
1345 data, data_size, data_length);
1347 unlock_status = psa_unlock_key_slot(slot);
1349 return ((status == PSA_SUCCESS) ? unlock_status : status);
1352 psa_status_t psa_export_public_key_internal(
1353 const psa_key_attributes_t *attributes,
1354 const uint8_t *key_buffer,
1355 size_t key_buffer_size,
1356 uint8_t *data,
1357 size_t data_size,
1358 size_t *data_length) {
1359 psa_key_type_t type = attributes->core.type;
1361 if (PSA_KEY_TYPE_IS_RSA(type) || PSA_KEY_TYPE_IS_ECC(type)) {
1362 if (PSA_KEY_TYPE_IS_PUBLIC_KEY(type)) {
1363 /* Exporting public -> public */
1364 return (psa_export_key_buffer_internal(
1365 key_buffer, key_buffer_size,
1366 data, data_size, data_length));
1369 if (PSA_KEY_TYPE_IS_RSA(type)) {
1370 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) || \
1371 defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY)
1372 return (mbedtls_psa_rsa_export_public_key(attributes,
1373 key_buffer,
1374 key_buffer_size,
1375 data,
1376 data_size,
1377 data_length));
1378 #else
1379 /* We don't know how to convert a private RSA key to public. */
1380 return (PSA_ERROR_NOT_SUPPORTED);
1381 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) ||
1382 * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY) */
1383 } else {
1384 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) || \
1385 defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY)
1386 return (mbedtls_psa_ecp_export_public_key(attributes,
1387 key_buffer,
1388 key_buffer_size,
1389 data,
1390 data_size,
1391 data_length));
1392 #else
1393 /* We don't know how to convert a private ECC key to public */
1394 return (PSA_ERROR_NOT_SUPPORTED);
1395 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) ||
1396 * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY) */
1398 } else {
1399 /* This shouldn't happen in the reference implementation, but
1400 it is valid for a special-purpose implementation to omit
1401 support for exporting certain key types. */
1402 return (PSA_ERROR_NOT_SUPPORTED);
1406 psa_status_t psa_export_public_key(mbedtls_svc_key_id_t key,
1407 uint8_t *data,
1408 size_t data_size,
1409 size_t *data_length) {
1410 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
1411 psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
1412 psa_key_slot_t *slot;
1414 /* Reject a zero-length output buffer now, since this can never be a
1415 * valid key representation. This way we know that data must be a valid
1416 * pointer and we can do things like memset(data, ..., data_size). */
1417 if (data_size == 0)
1418 return (PSA_ERROR_BUFFER_TOO_SMALL);
1420 /* Set the key to empty now, so that even when there are errors, we always
1421 * set data_length to a value between 0 and data_size. On error, setting
1422 * the key to empty is a good choice because an empty key representation is
1423 * unlikely to be accepted anywhere. */
1424 *data_length = 0;
1426 /* Exporting a public key doesn't require a usage flag. */
1427 status = psa_get_and_lock_key_slot_with_policy(key, &slot, 0, 0);
1428 if (status != PSA_SUCCESS)
1429 return (status);
1431 if (! PSA_KEY_TYPE_IS_ASYMMETRIC(slot->attr.type)) {
1432 status = PSA_ERROR_INVALID_ARGUMENT;
1433 goto exit;
1436 psa_key_attributes_t attributes = {
1437 .core = slot->attr
1439 status = psa_driver_wrapper_export_public_key(
1440 &attributes, slot->key.data, slot->key.bytes,
1441 data, data_size, data_length);
1443 exit:
1444 unlock_status = psa_unlock_key_slot(slot);
1446 return ((status == PSA_SUCCESS) ? unlock_status : status);
1449 #if defined(static_assert)
1450 static_assert((MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY &MBEDTLS_PSA_KA_MASK_DUAL_USE) == 0,
1451 "One or more key attribute flag is listed as both external-only and dual-use");
1452 static_assert((PSA_KA_MASK_INTERNAL_ONLY &MBEDTLS_PSA_KA_MASK_DUAL_USE) == 0,
1453 "One or more key attribute flag is listed as both internal-only and dual-use");
1454 static_assert((PSA_KA_MASK_INTERNAL_ONLY &MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY) == 0,
1455 "One or more key attribute flag is listed as both internal-only and external-only");
1456 #endif
1458 /** Validate that a key policy is internally well-formed.
1460 * This function only rejects invalid policies. It does not validate the
1461 * consistency of the policy with respect to other attributes of the key
1462 * such as the key type.
1464 static psa_status_t psa_validate_key_policy(const psa_key_policy_t *policy) {
1465 if ((policy->usage & ~(PSA_KEY_USAGE_EXPORT |
1466 PSA_KEY_USAGE_COPY |
1467 PSA_KEY_USAGE_ENCRYPT |
1468 PSA_KEY_USAGE_DECRYPT |
1469 PSA_KEY_USAGE_SIGN_HASH |
1470 PSA_KEY_USAGE_VERIFY_HASH |
1471 PSA_KEY_USAGE_DERIVE)) != 0)
1472 return (PSA_ERROR_INVALID_ARGUMENT);
1474 return (PSA_SUCCESS);
1477 /** Validate the internal consistency of key attributes.
1479 * This function only rejects invalid attribute values. If does not
1480 * validate the consistency of the attributes with any key data that may
1481 * be involved in the creation of the key.
1483 * Call this function early in the key creation process.
1485 * \param[in] attributes Key attributes for the new key.
1486 * \param[out] p_drv On any return, the driver for the key, if any.
1487 * NULL for a transparent key.
1490 static psa_status_t psa_validate_key_attributes(
1491 const psa_key_attributes_t *attributes,
1492 psa_se_drv_table_entry_t **p_drv) {
1493 psa_status_t status = PSA_ERROR_INVALID_ARGUMENT;
1494 psa_key_lifetime_t lifetime = psa_get_key_lifetime(attributes);
1495 mbedtls_svc_key_id_t key = psa_get_key_id(attributes);
1497 status = psa_validate_key_location(lifetime, p_drv);
1498 if (status != PSA_SUCCESS)
1499 return (status);
1501 status = psa_validate_key_persistence(lifetime);
1502 if (status != PSA_SUCCESS)
1503 return (status);
1505 if (PSA_KEY_LIFETIME_IS_VOLATILE(lifetime)) {
1506 if (MBEDTLS_SVC_KEY_ID_GET_KEY_ID(key) != 0)
1507 return (PSA_ERROR_INVALID_ARGUMENT);
1508 } else {
1509 status = psa_validate_key_id(psa_get_key_id(attributes), 0);
1510 if (status != PSA_SUCCESS)
1511 return (status);
1514 status = psa_validate_key_policy(&attributes->core.policy);
1515 if (status != PSA_SUCCESS)
1516 return (status);
1518 /* Refuse to create overly large keys.
1519 * Note that this doesn't trigger on import if the attributes don't
1520 * explicitly specify a size (so psa_get_key_bits returns 0), so
1521 * psa_import_key() needs its own checks. */
1522 if (psa_get_key_bits(attributes) > PSA_MAX_KEY_BITS)
1523 return (PSA_ERROR_NOT_SUPPORTED);
1525 /* Reject invalid flags. These should not be reachable through the API. */
1526 if (attributes->core.flags & ~(MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY |
1527 MBEDTLS_PSA_KA_MASK_DUAL_USE))
1528 return (PSA_ERROR_INVALID_ARGUMENT);
1530 return (PSA_SUCCESS);
1533 /** Prepare a key slot to receive key material.
1535 * This function allocates a key slot and sets its metadata.
1537 * If this function fails, call psa_fail_key_creation().
1539 * This function is intended to be used as follows:
1540 * -# Call psa_start_key_creation() to allocate a key slot, prepare
1541 * it with the specified attributes, and in case of a volatile key assign it
1542 * a volatile key identifier.
1543 * -# Populate the slot with the key material.
1544 * -# Call psa_finish_key_creation() to finalize the creation of the slot.
1545 * In case of failure at any step, stop the sequence and call
1546 * psa_fail_key_creation().
1548 * On success, the key slot is locked. It is the responsibility of the caller
1549 * to unlock the key slot when it does not access it anymore.
1551 * \param method An identification of the calling function.
1552 * \param[in] attributes Key attributes for the new key.
1553 * \param[out] p_slot On success, a pointer to the prepared slot.
1554 * \param[out] p_drv On any return, the driver for the key, if any.
1555 * NULL for a transparent key.
1557 * \retval #PSA_SUCCESS
1558 * The key slot is ready to receive key material.
1559 * \return If this function fails, the key slot is an invalid state.
1560 * You must call psa_fail_key_creation() to wipe and free the slot.
1562 static psa_status_t psa_start_key_creation(
1563 psa_key_creation_method_t method,
1564 const psa_key_attributes_t *attributes,
1565 psa_key_slot_t **p_slot,
1566 psa_se_drv_table_entry_t **p_drv) {
1567 psa_status_t status;
1568 psa_key_id_t volatile_key_id;
1569 psa_key_slot_t *slot;
1571 (void) method;
1572 *p_drv = NULL;
1574 status = psa_validate_key_attributes(attributes, p_drv);
1575 if (status != PSA_SUCCESS)
1576 return (status);
1578 status = psa_get_empty_key_slot(&volatile_key_id, p_slot);
1579 if (status != PSA_SUCCESS)
1580 return (status);
1581 slot = *p_slot;
1583 /* We're storing the declared bit-size of the key. It's up to each
1584 * creation mechanism to verify that this information is correct.
1585 * It's automatically correct for mechanisms that use the bit-size as
1586 * an input (generate, device) but not for those where the bit-size
1587 * is optional (import, copy). In case of a volatile key, assign it the
1588 * volatile key identifier associated to the slot returned to contain its
1589 * definition. */
1591 slot->attr = attributes->core;
1592 if (PSA_KEY_LIFETIME_IS_VOLATILE(slot->attr.lifetime)) {
1593 #if !defined(MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER)
1594 slot->attr.id = volatile_key_id;
1595 #else
1596 slot->attr.id.key_id = volatile_key_id;
1597 #endif
1600 /* Erase external-only flags from the internal copy. To access
1601 * external-only flags, query `attributes`. Thanks to the check
1602 * in psa_validate_key_attributes(), this leaves the dual-use
1603 * flags and any internal flag that psa_get_empty_key_slot()
1604 * may have set. */
1605 slot->attr.flags &= ~MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY;
1607 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1608 /* For a key in a secure element, we need to do three things
1609 * when creating or registering a persistent key:
1610 * create the key file in internal storage, create the
1611 * key inside the secure element, and update the driver's
1612 * persistent data. This is done by starting a transaction that will
1613 * encompass these three actions.
1614 * For registering a volatile key, we just need to find an appropriate
1615 * slot number inside the SE. Since the key is designated volatile, creating
1616 * a transaction is not required. */
1617 /* The first thing to do is to find a slot number for the new key.
1618 * We save the slot number in persistent storage as part of the
1619 * transaction data. It will be needed to recover if the power
1620 * fails during the key creation process, to clean up on the secure
1621 * element side after restarting. Obtaining a slot number from the
1622 * secure element driver updates its persistent state, but we do not yet
1623 * save the driver's persistent state, so that if the power fails,
1624 * we can roll back to a state where the key doesn't exist. */
1625 if (*p_drv != NULL) {
1626 psa_key_slot_number_t slot_number;
1627 status = psa_find_se_slot_for_key(attributes, method, *p_drv,
1628 &slot_number);
1629 if (status != PSA_SUCCESS)
1630 return (status);
1632 if (! PSA_KEY_LIFETIME_IS_VOLATILE(attributes->core.lifetime)) {
1633 psa_crypto_prepare_transaction(PSA_CRYPTO_TRANSACTION_CREATE_KEY);
1634 psa_crypto_transaction.key.lifetime = slot->attr.lifetime;
1635 psa_crypto_transaction.key.slot = slot_number;
1636 psa_crypto_transaction.key.id = slot->attr.id;
1637 status = psa_crypto_save_transaction();
1638 if (status != PSA_SUCCESS) {
1639 (void) psa_crypto_stop_transaction();
1640 return (status);
1644 status = psa_copy_key_material_into_slot(
1645 slot, (uint8_t *)(&slot_number), sizeof(slot_number));
1648 if (*p_drv == NULL && method == PSA_KEY_CREATION_REGISTER) {
1649 /* Key registration only makes sense with a secure element. */
1650 return (PSA_ERROR_INVALID_ARGUMENT);
1652 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1654 return (PSA_SUCCESS);
1657 /** Finalize the creation of a key once its key material has been set.
1659 * This entails writing the key to persistent storage.
1661 * If this function fails, call psa_fail_key_creation().
1662 * See the documentation of psa_start_key_creation() for the intended use
1663 * of this function.
1665 * If the finalization succeeds, the function unlocks the key slot (it was
1666 * locked by psa_start_key_creation()) and the key slot cannot be accessed
1667 * anymore as part of the key creation process.
1669 * \param[in,out] slot Pointer to the slot with key material.
1670 * \param[in] driver The secure element driver for the key,
1671 * or NULL for a transparent key.
1672 * \param[out] key On success, identifier of the key. Note that the
1673 * key identifier is also stored in the key slot.
1675 * \retval #PSA_SUCCESS
1676 * The key was successfully created.
1677 * \retval #PSA_ERROR_INSUFFICIENT_MEMORY
1678 * \retval #PSA_ERROR_INSUFFICIENT_STORAGE
1679 * \retval #PSA_ERROR_ALREADY_EXISTS
1680 * \retval #PSA_ERROR_DATA_INVALID
1681 * \retval #PSA_ERROR_DATA_CORRUPT
1682 * \retval #PSA_ERROR_STORAGE_FAILURE
1684 * \return If this function fails, the key slot is an invalid state.
1685 * You must call psa_fail_key_creation() to wipe and free the slot.
1687 static psa_status_t psa_finish_key_creation(
1688 psa_key_slot_t *slot,
1689 psa_se_drv_table_entry_t *driver,
1690 mbedtls_svc_key_id_t *key) {
1691 psa_status_t status = PSA_SUCCESS;
1692 (void) slot;
1693 (void) driver;
1695 #if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C)
1696 if (! PSA_KEY_LIFETIME_IS_VOLATILE(slot->attr.lifetime)) {
1697 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1698 if (driver != NULL) {
1699 psa_se_key_data_storage_t data;
1700 psa_key_slot_number_t slot_number =
1701 psa_key_slot_get_slot_number(slot) ;
1703 #if defined(static_assert)
1704 static_assert(sizeof(slot_number) ==
1705 sizeof(data.slot_number),
1706 "Slot number size does not match psa_se_key_data_storage_t");
1707 #endif
1708 memcpy(&data.slot_number, &slot_number, sizeof(slot_number));
1709 status = psa_save_persistent_key(&slot->attr,
1710 (uint8_t *) &data,
1711 sizeof(data));
1712 } else
1713 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1715 /* Key material is saved in export representation in the slot, so
1716 * just pass the slot buffer for storage. */
1717 status = psa_save_persistent_key(&slot->attr,
1718 slot->key.data,
1719 slot->key.bytes);
1722 #endif /* defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) */
1724 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1725 /* Finish the transaction for a key creation. This does not
1726 * happen when registering an existing key. Detect this case
1727 * by checking whether a transaction is in progress (actual
1728 * creation of a persistent key in a secure element requires a transaction,
1729 * but registration or volatile key creation doesn't use one). */
1730 if (driver != NULL &&
1731 psa_crypto_transaction.unknown.type == PSA_CRYPTO_TRANSACTION_CREATE_KEY) {
1732 status = psa_save_se_persistent_data(driver);
1733 if (status != PSA_SUCCESS) {
1734 psa_destroy_persistent_key(slot->attr.id);
1735 return (status);
1737 status = psa_crypto_stop_transaction();
1739 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1741 if (status == PSA_SUCCESS) {
1742 *key = slot->attr.id;
1743 status = psa_unlock_key_slot(slot);
1744 if (status != PSA_SUCCESS)
1745 *key = MBEDTLS_SVC_KEY_ID_INIT;
1748 return (status);
1751 /** Abort the creation of a key.
1753 * You may call this function after calling psa_start_key_creation(),
1754 * or after psa_finish_key_creation() fails. In other circumstances, this
1755 * function may not clean up persistent storage.
1756 * See the documentation of psa_start_key_creation() for the intended use
1757 * of this function.
1759 * \param[in,out] slot Pointer to the slot with key material.
1760 * \param[in] driver The secure element driver for the key,
1761 * or NULL for a transparent key.
1763 static void psa_fail_key_creation(psa_key_slot_t *slot,
1764 psa_se_drv_table_entry_t *driver) {
1765 (void) driver;
1767 if (slot == NULL)
1768 return;
1770 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1771 /* TODO: If the key has already been created in the secure
1772 * element, and the failure happened later (when saving metadata
1773 * to internal storage), we need to destroy the key in the secure
1774 * element.
1775 * https://github.com/ARMmbed/mbed-crypto/issues/217
1778 /* Abort the ongoing transaction if any (there may not be one if
1779 * the creation process failed before starting one, or if the
1780 * key creation is a registration of a key in a secure element).
1781 * Earlier functions must already have done what it takes to undo any
1782 * partial creation. All that's left is to update the transaction data
1783 * itself. */
1784 (void) psa_crypto_stop_transaction();
1785 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1787 psa_wipe_key_slot(slot);
1790 /** Validate optional attributes during key creation.
1792 * Some key attributes are optional during key creation. If they are
1793 * specified in the attributes structure, check that they are consistent
1794 * with the data in the slot.
1796 * This function should be called near the end of key creation, after
1797 * the slot in memory is fully populated but before saving persistent data.
1799 static psa_status_t psa_validate_optional_attributes(
1800 const psa_key_slot_t *slot,
1801 const psa_key_attributes_t *attributes) {
1802 if (attributes->core.type != 0) {
1803 if (attributes->core.type != slot->attr.type)
1804 return (PSA_ERROR_INVALID_ARGUMENT);
1807 if (attributes->domain_parameters_size != 0) {
1808 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) || \
1809 defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY)
1810 if (PSA_KEY_TYPE_IS_RSA(slot->attr.type)) {
1811 mbedtls_rsa_context *rsa = NULL;
1812 mbedtls_mpi actual, required;
1813 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1815 psa_status_t status = mbedtls_psa_rsa_load_representation(
1816 slot->attr.type,
1817 slot->key.data,
1818 slot->key.bytes,
1819 &rsa);
1820 if (status != PSA_SUCCESS)
1821 return (status);
1823 mbedtls_mpi_init(&actual);
1824 mbedtls_mpi_init(&required);
1825 ret = mbedtls_rsa_export(rsa,
1826 NULL, NULL, NULL, NULL, &actual);
1827 mbedtls_rsa_free(rsa);
1828 mbedtls_free(rsa);
1829 if (ret != 0)
1830 goto rsa_exit;
1831 ret = mbedtls_mpi_read_binary(&required,
1832 attributes->domain_parameters,
1833 attributes->domain_parameters_size);
1834 if (ret != 0)
1835 goto rsa_exit;
1836 if (mbedtls_mpi_cmp_mpi(&actual, &required) != 0)
1837 ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1838 rsa_exit:
1839 mbedtls_mpi_free(&actual);
1840 mbedtls_mpi_free(&required);
1841 if (ret != 0)
1842 return (mbedtls_to_psa_error(ret));
1843 } else
1844 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) ||
1845 * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY) */
1847 return (PSA_ERROR_INVALID_ARGUMENT);
1851 if (attributes->core.bits != 0) {
1852 if (attributes->core.bits != slot->attr.bits)
1853 return (PSA_ERROR_INVALID_ARGUMENT);
1856 return (PSA_SUCCESS);
1859 psa_status_t psa_import_key(const psa_key_attributes_t *attributes,
1860 const uint8_t *data,
1861 size_t data_length,
1862 mbedtls_svc_key_id_t *key) {
1863 psa_status_t status;
1864 psa_key_slot_t *slot = NULL;
1865 psa_se_drv_table_entry_t *driver = NULL;
1866 size_t bits;
1868 *key = MBEDTLS_SVC_KEY_ID_INIT;
1870 /* Reject zero-length symmetric keys (including raw data key objects).
1871 * This also rejects any key which might be encoded as an empty string,
1872 * which is never valid. */
1873 if (data_length == 0)
1874 return (PSA_ERROR_INVALID_ARGUMENT);
1876 status = psa_start_key_creation(PSA_KEY_CREATION_IMPORT, attributes,
1877 &slot, &driver);
1878 if (status != PSA_SUCCESS)
1879 goto exit;
1881 /* In the case of a transparent key or an opaque key stored in local
1882 * storage (thus not in the case of generating a key in a secure element
1883 * or cryptoprocessor with storage), we have to allocate a buffer to
1884 * hold the generated key material. */
1885 if (slot->key.data == NULL) {
1886 status = psa_allocate_buffer_to_slot(slot, data_length);
1887 if (status != PSA_SUCCESS)
1888 goto exit;
1891 bits = slot->attr.bits;
1892 status = psa_driver_wrapper_import_key(attributes,
1893 data, data_length,
1894 slot->key.data,
1895 slot->key.bytes,
1896 &slot->key.bytes, &bits);
1897 if (status != PSA_SUCCESS)
1898 goto exit;
1900 if (slot->attr.bits == 0)
1901 slot->attr.bits = (psa_key_bits_t) bits;
1902 else if (bits != slot->attr.bits) {
1903 status = PSA_ERROR_INVALID_ARGUMENT;
1904 goto exit;
1907 status = psa_validate_optional_attributes(slot, attributes);
1908 if (status != PSA_SUCCESS)
1909 goto exit;
1911 status = psa_finish_key_creation(slot, driver, key);
1912 exit:
1913 if (status != PSA_SUCCESS)
1914 psa_fail_key_creation(slot, driver);
1916 return (status);
1919 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1920 psa_status_t mbedtls_psa_register_se_key(
1921 const psa_key_attributes_t *attributes) {
1922 psa_status_t status;
1923 psa_key_slot_t *slot = NULL;
1924 psa_se_drv_table_entry_t *driver = NULL;
1925 mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
1927 /* Leaving attributes unspecified is not currently supported.
1928 * It could make sense to query the key type and size from the
1929 * secure element, but not all secure elements support this
1930 * and the driver HAL doesn't currently support it. */
1931 if (psa_get_key_type(attributes) == PSA_KEY_TYPE_NONE)
1932 return (PSA_ERROR_NOT_SUPPORTED);
1933 if (psa_get_key_bits(attributes) == 0)
1934 return (PSA_ERROR_NOT_SUPPORTED);
1936 status = psa_start_key_creation(PSA_KEY_CREATION_REGISTER, attributes,
1937 &slot, &driver);
1938 if (status != PSA_SUCCESS)
1939 goto exit;
1941 status = psa_finish_key_creation(slot, driver, &key);
1943 exit:
1944 if (status != PSA_SUCCESS)
1945 psa_fail_key_creation(slot, driver);
1947 /* Registration doesn't keep the key in RAM. */
1948 psa_close_key(key);
1949 return (status);
1951 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1953 static psa_status_t psa_copy_key_material(const psa_key_slot_t *source,
1954 psa_key_slot_t *target) {
1955 psa_status_t status = psa_copy_key_material_into_slot(target,
1956 source->key.data,
1957 source->key.bytes);
1958 if (status != PSA_SUCCESS)
1959 return (status);
1961 target->attr.type = source->attr.type;
1962 target->attr.bits = source->attr.bits;
1964 return (PSA_SUCCESS);
1967 psa_status_t psa_copy_key(mbedtls_svc_key_id_t source_key,
1968 const psa_key_attributes_t *specified_attributes,
1969 mbedtls_svc_key_id_t *target_key) {
1970 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
1971 psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
1972 psa_key_slot_t *source_slot = NULL;
1973 psa_key_slot_t *target_slot = NULL;
1974 psa_key_attributes_t actual_attributes = *specified_attributes;
1975 psa_se_drv_table_entry_t *driver = NULL;
1977 *target_key = MBEDTLS_SVC_KEY_ID_INIT;
1979 status = psa_get_and_lock_transparent_key_slot_with_policy(
1980 source_key, &source_slot, PSA_KEY_USAGE_COPY, 0);
1981 if (status != PSA_SUCCESS)
1982 goto exit;
1984 status = psa_validate_optional_attributes(source_slot,
1985 specified_attributes);
1986 if (status != PSA_SUCCESS)
1987 goto exit;
1989 status = psa_restrict_key_policy(source_slot->attr.type,
1990 &actual_attributes.core.policy,
1991 &source_slot->attr.policy);
1992 if (status != PSA_SUCCESS)
1993 goto exit;
1995 status = psa_start_key_creation(PSA_KEY_CREATION_COPY, &actual_attributes,
1996 &target_slot, &driver);
1997 if (status != PSA_SUCCESS)
1998 goto exit;
2000 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
2001 if (driver != NULL) {
2002 /* Copying to a secure element is not implemented yet. */
2003 status = PSA_ERROR_NOT_SUPPORTED;
2004 goto exit;
2006 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
2008 status = psa_copy_key_material(source_slot, target_slot);
2009 if (status != PSA_SUCCESS)
2010 goto exit;
2012 status = psa_finish_key_creation(target_slot, driver, target_key);
2013 exit:
2014 if (status != PSA_SUCCESS)
2015 psa_fail_key_creation(target_slot, driver);
2017 unlock_status = psa_unlock_key_slot(source_slot);
2019 return ((status == PSA_SUCCESS) ? unlock_status : status);
2024 /****************************************************************/
2025 /* Message digests */
2026 /****************************************************************/
2028 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) || \
2029 defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP) || \
2030 defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS) || \
2031 defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)
2032 const mbedtls_md_info_t *mbedtls_md_info_from_psa(psa_algorithm_t alg) {
2033 switch (alg) {
2034 #if defined(MBEDTLS_PSA_BUILTIN_ALG_MD2)
2035 case PSA_ALG_MD2:
2036 return (&mbedtls_md2_info);
2037 #endif
2038 #if defined(MBEDTLS_PSA_BUILTIN_ALG_MD4)
2039 case PSA_ALG_MD4:
2040 return (&mbedtls_md4_info);
2041 #endif
2042 #if defined(MBEDTLS_PSA_BUILTIN_ALG_MD5)
2043 case PSA_ALG_MD5:
2044 return (&mbedtls_md5_info);
2045 #endif
2046 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RIPEMD160)
2047 case PSA_ALG_RIPEMD160:
2048 return (&mbedtls_ripemd160_info);
2049 #endif
2050 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_1)
2051 case PSA_ALG_SHA_1:
2052 return (&mbedtls_sha1_info);
2053 #endif
2054 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_224)
2055 case PSA_ALG_SHA_224:
2056 return (&mbedtls_sha224_info);
2057 #endif
2058 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_256)
2059 case PSA_ALG_SHA_256:
2060 return (&mbedtls_sha256_info);
2061 #endif
2062 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_384)
2063 case PSA_ALG_SHA_384:
2064 return (&mbedtls_sha384_info);
2065 #endif
2066 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_512)
2067 case PSA_ALG_SHA_512:
2068 return (&mbedtls_sha512_info);
2069 #endif
2070 default:
2071 return (NULL);
2074 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) ||
2075 * defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP) ||
2076 * defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS) ||
2077 * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) */
2079 psa_status_t psa_hash_abort(psa_hash_operation_t *operation) {
2080 switch (operation->alg) {
2081 case 0:
2082 /* The object has (apparently) been initialized but it is not
2083 * in use. It's ok to call abort on such an object, and there's
2084 * nothing to do. */
2085 break;
2086 #if defined(MBEDTLS_PSA_BUILTIN_ALG_MD2)
2087 case PSA_ALG_MD2:
2088 mbedtls_md2_free(&operation->ctx.md2);
2089 break;
2090 #endif
2091 #if defined(MBEDTLS_PSA_BUILTIN_ALG_MD4)
2092 case PSA_ALG_MD4:
2093 mbedtls_md4_free(&operation->ctx.md4);
2094 break;
2095 #endif
2096 #if defined(MBEDTLS_PSA_BUILTIN_ALG_MD5)
2097 case PSA_ALG_MD5:
2098 mbedtls_md5_free(&operation->ctx.md5);
2099 break;
2100 #endif
2101 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RIPEMD160)
2102 case PSA_ALG_RIPEMD160:
2103 mbedtls_ripemd160_free(&operation->ctx.ripemd160);
2104 break;
2105 #endif
2106 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_1)
2107 case PSA_ALG_SHA_1:
2108 mbedtls_sha1_free(&operation->ctx.sha1);
2109 break;
2110 #endif
2111 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_224)
2112 case PSA_ALG_SHA_224:
2113 mbedtls_sha256_free(&operation->ctx.sha256);
2114 break;
2115 #endif
2116 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_256)
2117 case PSA_ALG_SHA_256:
2118 mbedtls_sha256_free(&operation->ctx.sha256);
2119 break;
2120 #endif
2121 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_384)
2122 case PSA_ALG_SHA_384:
2123 mbedtls_sha512_free(&operation->ctx.sha512);
2124 break;
2125 #endif
2126 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_512)
2127 case PSA_ALG_SHA_512:
2128 mbedtls_sha512_free(&operation->ctx.sha512);
2129 break;
2130 #endif
2131 default:
2132 return (PSA_ERROR_BAD_STATE);
2134 operation->alg = 0;
2135 return (PSA_SUCCESS);
2138 psa_status_t psa_hash_setup(psa_hash_operation_t *operation,
2139 psa_algorithm_t alg) {
2140 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2142 /* A context must be freshly initialized before it can be set up. */
2143 if (operation->alg != 0) {
2144 return (PSA_ERROR_BAD_STATE);
2147 switch (alg) {
2148 #if defined(MBEDTLS_PSA_BUILTIN_ALG_MD2)
2149 case PSA_ALG_MD2:
2150 mbedtls_md2_init(&operation->ctx.md2);
2151 ret = mbedtls_md2_starts_ret(&operation->ctx.md2);
2152 break;
2153 #endif
2154 #if defined(MBEDTLS_PSA_BUILTIN_ALG_MD4)
2155 case PSA_ALG_MD4:
2156 mbedtls_md4_init(&operation->ctx.md4);
2157 ret = mbedtls_md4_starts_ret(&operation->ctx.md4);
2158 break;
2159 #endif
2160 #if defined(MBEDTLS_PSA_BUILTIN_ALG_MD5)
2161 case PSA_ALG_MD5:
2162 mbedtls_md5_init(&operation->ctx.md5);
2163 ret = mbedtls_md5_starts_ret(&operation->ctx.md5);
2164 break;
2165 #endif
2166 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RIPEMD160)
2167 case PSA_ALG_RIPEMD160:
2168 mbedtls_ripemd160_init(&operation->ctx.ripemd160);
2169 ret = mbedtls_ripemd160_starts_ret(&operation->ctx.ripemd160);
2170 break;
2171 #endif
2172 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_1)
2173 case PSA_ALG_SHA_1:
2174 mbedtls_sha1_init(&operation->ctx.sha1);
2175 ret = mbedtls_sha1_starts_ret(&operation->ctx.sha1);
2176 break;
2177 #endif
2178 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_224)
2179 case PSA_ALG_SHA_224:
2180 mbedtls_sha256_init(&operation->ctx.sha256);
2181 ret = mbedtls_sha256_starts_ret(&operation->ctx.sha256, 1);
2182 break;
2183 #endif
2184 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_256)
2185 case PSA_ALG_SHA_256:
2186 mbedtls_sha256_init(&operation->ctx.sha256);
2187 ret = mbedtls_sha256_starts_ret(&operation->ctx.sha256, 0);
2188 break;
2189 #endif
2190 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_384)
2191 case PSA_ALG_SHA_384:
2192 mbedtls_sha512_init(&operation->ctx.sha512);
2193 ret = mbedtls_sha512_starts_ret(&operation->ctx.sha512, 1);
2194 break;
2195 #endif
2196 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_512)
2197 case PSA_ALG_SHA_512:
2198 mbedtls_sha512_init(&operation->ctx.sha512);
2199 ret = mbedtls_sha512_starts_ret(&operation->ctx.sha512, 0);
2200 break;
2201 #endif
2202 default:
2203 return (PSA_ALG_IS_HASH(alg) ?
2204 PSA_ERROR_NOT_SUPPORTED :
2205 PSA_ERROR_INVALID_ARGUMENT);
2207 if (ret == 0)
2208 operation->alg = alg;
2209 else
2210 psa_hash_abort(operation);
2211 return (mbedtls_to_psa_error(ret));
2214 psa_status_t psa_hash_update(psa_hash_operation_t *operation,
2215 const uint8_t *input,
2216 size_t input_length) {
2217 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2219 /* Don't require hash implementations to behave correctly on a
2220 * zero-length input, which may have an invalid pointer. */
2221 if (input_length == 0)
2222 return (PSA_SUCCESS);
2224 switch (operation->alg) {
2225 #if defined(MBEDTLS_PSA_BUILTIN_ALG_MD2)
2226 case PSA_ALG_MD2:
2227 ret = mbedtls_md2_update_ret(&operation->ctx.md2,
2228 input, input_length);
2229 break;
2230 #endif
2231 #if defined(MBEDTLS_PSA_BUILTIN_ALG_MD4)
2232 case PSA_ALG_MD4:
2233 ret = mbedtls_md4_update_ret(&operation->ctx.md4,
2234 input, input_length);
2235 break;
2236 #endif
2237 #if defined(MBEDTLS_PSA_BUILTIN_ALG_MD5)
2238 case PSA_ALG_MD5:
2239 ret = mbedtls_md5_update_ret(&operation->ctx.md5,
2240 input, input_length);
2241 break;
2242 #endif
2243 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RIPEMD160)
2244 case PSA_ALG_RIPEMD160:
2245 ret = mbedtls_ripemd160_update_ret(&operation->ctx.ripemd160,
2246 input, input_length);
2247 break;
2248 #endif
2249 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_1)
2250 case PSA_ALG_SHA_1:
2251 ret = mbedtls_sha1_update_ret(&operation->ctx.sha1,
2252 input, input_length);
2253 break;
2254 #endif
2255 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_224)
2256 case PSA_ALG_SHA_224:
2257 ret = mbedtls_sha256_update_ret(&operation->ctx.sha256,
2258 input, input_length);
2259 break;
2260 #endif
2261 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_256)
2262 case PSA_ALG_SHA_256:
2263 ret = mbedtls_sha256_update_ret(&operation->ctx.sha256,
2264 input, input_length);
2265 break;
2266 #endif
2267 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_384)
2268 case PSA_ALG_SHA_384:
2269 ret = mbedtls_sha512_update_ret(&operation->ctx.sha512,
2270 input, input_length);
2271 break;
2272 #endif
2273 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_512)
2274 case PSA_ALG_SHA_512:
2275 ret = mbedtls_sha512_update_ret(&operation->ctx.sha512,
2276 input, input_length);
2277 break;
2278 #endif
2279 default:
2280 (void)input;
2281 return (PSA_ERROR_BAD_STATE);
2284 if (ret != 0)
2285 psa_hash_abort(operation);
2286 return (mbedtls_to_psa_error(ret));
2289 psa_status_t psa_hash_finish(psa_hash_operation_t *operation,
2290 uint8_t *hash,
2291 size_t hash_size,
2292 size_t *hash_length) {
2293 psa_status_t status;
2294 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2295 size_t actual_hash_length = PSA_HASH_LENGTH(operation->alg);
2297 /* Fill the output buffer with something that isn't a valid hash
2298 * (barring an attack on the hash and deliberately-crafted input),
2299 * in case the caller doesn't check the return status properly. */
2300 *hash_length = hash_size;
2301 /* If hash_size is 0 then hash may be NULL and then the
2302 * call to memset would have undefined behavior. */
2303 if (hash_size != 0)
2304 memset(hash, '!', hash_size);
2306 if (hash_size < actual_hash_length) {
2307 status = PSA_ERROR_BUFFER_TOO_SMALL;
2308 goto exit;
2311 switch (operation->alg) {
2312 #if defined(MBEDTLS_PSA_BUILTIN_ALG_MD2)
2313 case PSA_ALG_MD2:
2314 ret = mbedtls_md2_finish_ret(&operation->ctx.md2, hash);
2315 break;
2316 #endif
2317 #if defined(MBEDTLS_PSA_BUILTIN_ALG_MD4)
2318 case PSA_ALG_MD4:
2319 ret = mbedtls_md4_finish_ret(&operation->ctx.md4, hash);
2320 break;
2321 #endif
2322 #if defined(MBEDTLS_PSA_BUILTIN_ALG_MD5)
2323 case PSA_ALG_MD5:
2324 ret = mbedtls_md5_finish_ret(&operation->ctx.md5, hash);
2325 break;
2326 #endif
2327 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RIPEMD160)
2328 case PSA_ALG_RIPEMD160:
2329 ret = mbedtls_ripemd160_finish_ret(&operation->ctx.ripemd160, hash);
2330 break;
2331 #endif
2332 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_1)
2333 case PSA_ALG_SHA_1:
2334 ret = mbedtls_sha1_finish_ret(&operation->ctx.sha1, hash);
2335 break;
2336 #endif
2337 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_224)
2338 case PSA_ALG_SHA_224:
2339 ret = mbedtls_sha256_finish_ret(&operation->ctx.sha256, hash);
2340 break;
2341 #endif
2342 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_256)
2343 case PSA_ALG_SHA_256:
2344 ret = mbedtls_sha256_finish_ret(&operation->ctx.sha256, hash);
2345 break;
2346 #endif
2347 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_384)
2348 case PSA_ALG_SHA_384:
2349 ret = mbedtls_sha512_finish_ret(&operation->ctx.sha512, hash);
2350 break;
2351 #endif
2352 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_512)
2353 case PSA_ALG_SHA_512:
2354 ret = mbedtls_sha512_finish_ret(&operation->ctx.sha512, hash);
2355 break;
2356 #endif
2357 default:
2358 return (PSA_ERROR_BAD_STATE);
2360 status = mbedtls_to_psa_error(ret);
2362 exit:
2363 if (status == PSA_SUCCESS) {
2364 *hash_length = actual_hash_length;
2365 return (psa_hash_abort(operation));
2366 } else {
2367 psa_hash_abort(operation);
2368 return (status);
2372 psa_status_t psa_hash_verify(psa_hash_operation_t *operation,
2373 const uint8_t *hash,
2374 size_t hash_length) {
2375 uint8_t actual_hash[MBEDTLS_MD_MAX_SIZE];
2376 size_t actual_hash_length;
2377 psa_status_t status = psa_hash_finish(operation,
2378 actual_hash, sizeof(actual_hash),
2379 &actual_hash_length);
2380 if (status != PSA_SUCCESS)
2381 return (status);
2382 if (actual_hash_length != hash_length)
2383 return (PSA_ERROR_INVALID_SIGNATURE);
2384 if (safer_memcmp(hash, actual_hash, actual_hash_length) != 0)
2385 return (PSA_ERROR_INVALID_SIGNATURE);
2386 return (PSA_SUCCESS);
2389 psa_status_t psa_hash_compute(psa_algorithm_t alg,
2390 const uint8_t *input, size_t input_length,
2391 uint8_t *hash, size_t hash_size,
2392 size_t *hash_length) {
2393 psa_hash_operation_t operation = PSA_HASH_OPERATION_INIT;
2394 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2396 *hash_length = hash_size;
2397 status = psa_hash_setup(&operation, alg);
2398 if (status != PSA_SUCCESS)
2399 goto exit;
2400 status = psa_hash_update(&operation, input, input_length);
2401 if (status != PSA_SUCCESS)
2402 goto exit;
2403 status = psa_hash_finish(&operation, hash, hash_size, hash_length);
2404 if (status != PSA_SUCCESS)
2405 goto exit;
2407 exit:
2408 if (status == PSA_SUCCESS)
2409 status = psa_hash_abort(&operation);
2410 else
2411 psa_hash_abort(&operation);
2412 return (status);
2415 psa_status_t psa_hash_compare(psa_algorithm_t alg,
2416 const uint8_t *input, size_t input_length,
2417 const uint8_t *hash, size_t hash_length) {
2418 psa_hash_operation_t operation = PSA_HASH_OPERATION_INIT;
2419 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2421 status = psa_hash_setup(&operation, alg);
2422 if (status != PSA_SUCCESS)
2423 goto exit;
2424 status = psa_hash_update(&operation, input, input_length);
2425 if (status != PSA_SUCCESS)
2426 goto exit;
2427 status = psa_hash_verify(&operation, hash, hash_length);
2428 if (status != PSA_SUCCESS)
2429 goto exit;
2431 exit:
2432 if (status == PSA_SUCCESS)
2433 status = psa_hash_abort(&operation);
2434 else
2435 psa_hash_abort(&operation);
2436 return (status);
2439 psa_status_t psa_hash_clone(const psa_hash_operation_t *source_operation,
2440 psa_hash_operation_t *target_operation) {
2441 if (target_operation->alg != 0)
2442 return (PSA_ERROR_BAD_STATE);
2444 switch (source_operation->alg) {
2445 case 0:
2446 return (PSA_ERROR_BAD_STATE);
2447 #if defined(MBEDTLS_PSA_BUILTIN_ALG_MD2)
2448 case PSA_ALG_MD2:
2449 mbedtls_md2_clone(&target_operation->ctx.md2,
2450 &source_operation->ctx.md2);
2451 break;
2452 #endif
2453 #if defined(MBEDTLS_PSA_BUILTIN_ALG_MD4)
2454 case PSA_ALG_MD4:
2455 mbedtls_md4_clone(&target_operation->ctx.md4,
2456 &source_operation->ctx.md4);
2457 break;
2458 #endif
2459 #if defined(MBEDTLS_PSA_BUILTIN_ALG_MD5)
2460 case PSA_ALG_MD5:
2461 mbedtls_md5_clone(&target_operation->ctx.md5,
2462 &source_operation->ctx.md5);
2463 break;
2464 #endif
2465 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RIPEMD160)
2466 case PSA_ALG_RIPEMD160:
2467 mbedtls_ripemd160_clone(&target_operation->ctx.ripemd160,
2468 &source_operation->ctx.ripemd160);
2469 break;
2470 #endif
2471 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_1)
2472 case PSA_ALG_SHA_1:
2473 mbedtls_sha1_clone(&target_operation->ctx.sha1,
2474 &source_operation->ctx.sha1);
2475 break;
2476 #endif
2477 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_224)
2478 case PSA_ALG_SHA_224:
2479 mbedtls_sha256_clone(&target_operation->ctx.sha256,
2480 &source_operation->ctx.sha256);
2481 break;
2482 #endif
2483 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_256)
2484 case PSA_ALG_SHA_256:
2485 mbedtls_sha256_clone(&target_operation->ctx.sha256,
2486 &source_operation->ctx.sha256);
2487 break;
2488 #endif
2489 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_384)
2490 case PSA_ALG_SHA_384:
2491 mbedtls_sha512_clone(&target_operation->ctx.sha512,
2492 &source_operation->ctx.sha512);
2493 break;
2494 #endif
2495 #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_512)
2496 case PSA_ALG_SHA_512:
2497 mbedtls_sha512_clone(&target_operation->ctx.sha512,
2498 &source_operation->ctx.sha512);
2499 break;
2500 #endif
2501 default:
2502 return (PSA_ERROR_NOT_SUPPORTED);
2505 target_operation->alg = source_operation->alg;
2506 return (PSA_SUCCESS);
2510 /****************************************************************/
2511 /* MAC */
2512 /****************************************************************/
2514 static const mbedtls_cipher_info_t *mbedtls_cipher_info_from_psa(
2515 psa_algorithm_t alg,
2516 psa_key_type_t key_type,
2517 size_t key_bits,
2518 mbedtls_cipher_id_t *cipher_id) {
2519 mbedtls_cipher_mode_t mode;
2520 mbedtls_cipher_id_t cipher_id_tmp;
2522 if (PSA_ALG_IS_AEAD(alg))
2523 alg = PSA_ALG_AEAD_WITH_SHORTENED_TAG(alg, 0);
2525 if (PSA_ALG_IS_CIPHER(alg) || PSA_ALG_IS_AEAD(alg)) {
2526 switch (alg) {
2527 case PSA_ALG_STREAM_CIPHER:
2528 mode = MBEDTLS_MODE_STREAM;
2529 break;
2530 case PSA_ALG_CTR:
2531 mode = MBEDTLS_MODE_CTR;
2532 break;
2533 case PSA_ALG_CFB:
2534 mode = MBEDTLS_MODE_CFB;
2535 break;
2536 case PSA_ALG_OFB:
2537 mode = MBEDTLS_MODE_OFB;
2538 break;
2539 case PSA_ALG_ECB_NO_PADDING:
2540 mode = MBEDTLS_MODE_ECB;
2541 break;
2542 case PSA_ALG_CBC_NO_PADDING:
2543 mode = MBEDTLS_MODE_CBC;
2544 break;
2545 case PSA_ALG_CBC_PKCS7:
2546 mode = MBEDTLS_MODE_CBC;
2547 break;
2548 case PSA_ALG_AEAD_WITH_SHORTENED_TAG(PSA_ALG_CCM, 0):
2549 mode = MBEDTLS_MODE_CCM;
2550 break;
2551 case PSA_ALG_AEAD_WITH_SHORTENED_TAG(PSA_ALG_GCM, 0):
2552 mode = MBEDTLS_MODE_GCM;
2553 break;
2554 case PSA_ALG_AEAD_WITH_SHORTENED_TAG(PSA_ALG_CHACHA20_POLY1305, 0):
2555 mode = MBEDTLS_MODE_CHACHAPOLY;
2556 break;
2557 default:
2558 return (NULL);
2560 } else if (alg == PSA_ALG_CMAC)
2561 mode = MBEDTLS_MODE_ECB;
2562 else
2563 return (NULL);
2565 switch (key_type) {
2566 case PSA_KEY_TYPE_AES:
2567 cipher_id_tmp = MBEDTLS_CIPHER_ID_AES;
2568 break;
2569 case PSA_KEY_TYPE_DES:
2570 /* key_bits is 64 for Single-DES, 128 for two-key Triple-DES,
2571 * and 192 for three-key Triple-DES. */
2572 if (key_bits == 64)
2573 cipher_id_tmp = MBEDTLS_CIPHER_ID_DES;
2574 else
2575 cipher_id_tmp = MBEDTLS_CIPHER_ID_3DES;
2576 /* mbedtls doesn't recognize two-key Triple-DES as an algorithm,
2577 * but two-key Triple-DES is functionally three-key Triple-DES
2578 * with K1=K3, so that's how we present it to mbedtls. */
2579 if (key_bits == 128)
2580 key_bits = 192;
2581 break;
2582 case PSA_KEY_TYPE_CAMELLIA:
2583 cipher_id_tmp = MBEDTLS_CIPHER_ID_CAMELLIA;
2584 break;
2585 case PSA_KEY_TYPE_ARC4:
2586 cipher_id_tmp = MBEDTLS_CIPHER_ID_ARC4;
2587 break;
2588 case PSA_KEY_TYPE_CHACHA20:
2589 cipher_id_tmp = MBEDTLS_CIPHER_ID_CHACHA20;
2590 break;
2591 default:
2592 return (NULL);
2594 if (cipher_id != NULL)
2595 *cipher_id = cipher_id_tmp;
2597 return (mbedtls_cipher_info_from_values(cipher_id_tmp,
2598 (int) key_bits, mode));
2601 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HMAC)
2602 static size_t psa_get_hash_block_size(psa_algorithm_t alg) {
2603 switch (alg) {
2604 case PSA_ALG_MD2:
2605 return (16);
2606 case PSA_ALG_MD4:
2607 return (64);
2608 case PSA_ALG_MD5:
2609 return (64);
2610 case PSA_ALG_RIPEMD160:
2611 return (64);
2612 case PSA_ALG_SHA_1:
2613 return (64);
2614 case PSA_ALG_SHA_224:
2615 return (64);
2616 case PSA_ALG_SHA_256:
2617 return (64);
2618 case PSA_ALG_SHA_384:
2619 return (128);
2620 case PSA_ALG_SHA_512:
2621 return (128);
2622 default:
2623 return (0);
2626 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_HMAC) */
2628 /* Initialize the MAC operation structure. Once this function has been
2629 * called, psa_mac_abort can run and will do the right thing. */
2630 static psa_status_t psa_mac_init(psa_mac_operation_t *operation,
2631 psa_algorithm_t alg) {
2632 psa_status_t status = PSA_ERROR_NOT_SUPPORTED;
2634 operation->alg = PSA_ALG_FULL_LENGTH_MAC(alg);
2635 operation->key_set = 0;
2636 operation->iv_set = 0;
2637 operation->iv_required = 0;
2638 operation->has_input = 0;
2639 operation->is_sign = 0;
2641 #if defined(MBEDTLS_CMAC_C)
2642 if (operation->alg == PSA_ALG_CMAC) {
2643 operation->iv_required = 0;
2644 mbedtls_cipher_init(&operation->ctx.cmac);
2645 status = PSA_SUCCESS;
2646 } else
2647 #endif /* MBEDTLS_CMAC_C */
2648 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HMAC)
2649 if (PSA_ALG_IS_HMAC(operation->alg)) {
2650 /* We'll set up the hash operation later in psa_hmac_setup_internal. */
2651 operation->ctx.hmac.hash_ctx.alg = 0;
2652 status = PSA_SUCCESS;
2653 } else
2654 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HMAC */
2656 if (! PSA_ALG_IS_MAC(alg))
2657 status = PSA_ERROR_INVALID_ARGUMENT;
2660 if (status != PSA_SUCCESS)
2661 memset(operation, 0, sizeof(*operation));
2662 return (status);
2665 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HMAC)
2666 static psa_status_t psa_hmac_abort_internal(psa_hmac_internal_data *hmac) {
2667 mbedtls_platform_zeroize(hmac->opad, sizeof(hmac->opad));
2668 return (psa_hash_abort(&hmac->hash_ctx));
2670 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HMAC */
2672 psa_status_t psa_mac_abort(psa_mac_operation_t *operation) {
2673 if (operation->alg == 0) {
2674 /* The object has (apparently) been initialized but it is not
2675 * in use. It's ok to call abort on such an object, and there's
2676 * nothing to do. */
2677 return (PSA_SUCCESS);
2678 } else
2679 #if defined(MBEDTLS_CMAC_C)
2680 if (operation->alg == PSA_ALG_CMAC) {
2681 mbedtls_cipher_free(&operation->ctx.cmac);
2682 } else
2683 #endif /* MBEDTLS_CMAC_C */
2684 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HMAC)
2685 if (PSA_ALG_IS_HMAC(operation->alg)) {
2686 psa_hmac_abort_internal(&operation->ctx.hmac);
2687 } else
2688 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HMAC */
2690 /* Sanity check (shouldn't happen: operation->alg should
2691 * always have been initialized to a valid value). */
2692 goto bad_state;
2695 operation->alg = 0;
2696 operation->key_set = 0;
2697 operation->iv_set = 0;
2698 operation->iv_required = 0;
2699 operation->has_input = 0;
2700 operation->is_sign = 0;
2702 return (PSA_SUCCESS);
2704 bad_state:
2705 /* If abort is called on an uninitialized object, we can't trust
2706 * anything. Wipe the object in case it contains confidential data.
2707 * This may result in a memory leak if a pointer gets overwritten,
2708 * but it's too late to do anything about this. */
2709 memset(operation, 0, sizeof(*operation));
2710 return (PSA_ERROR_BAD_STATE);
2713 #if defined(MBEDTLS_CMAC_C)
2714 static psa_status_t psa_cmac_setup(psa_mac_operation_t *operation,
2715 psa_key_slot_t *slot) {
2716 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2717 const mbedtls_cipher_info_t *cipher_info =
2718 mbedtls_cipher_info_from_psa(PSA_ALG_CMAC,
2719 slot->attr.type, slot->attr.bits,
2720 NULL);
2721 if (cipher_info == NULL)
2722 return (PSA_ERROR_NOT_SUPPORTED);
2724 ret = mbedtls_cipher_setup(&operation->ctx.cmac, cipher_info);
2725 if (ret != 0)
2726 goto exit;
2728 ret = mbedtls_cipher_cmac_starts(&operation->ctx.cmac,
2729 slot->key.data,
2730 slot->attr.bits);
2731 exit:
2732 return (mbedtls_to_psa_error(ret));
2734 #endif /* MBEDTLS_CMAC_C */
2736 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HMAC)
2737 static psa_status_t psa_hmac_setup_internal(psa_hmac_internal_data *hmac,
2738 const uint8_t *key,
2739 size_t key_length,
2740 psa_algorithm_t hash_alg) {
2741 uint8_t ipad[PSA_HMAC_MAX_HASH_BLOCK_SIZE];
2742 size_t i;
2743 size_t hash_size = PSA_HASH_LENGTH(hash_alg);
2744 size_t block_size = psa_get_hash_block_size(hash_alg);
2745 psa_status_t status;
2747 /* Sanity checks on block_size, to guarantee that there won't be a buffer
2748 * overflow below. This should never trigger if the hash algorithm
2749 * is implemented correctly. */
2750 /* The size checks against the ipad and opad buffers cannot be written
2751 * `block_size > sizeof( ipad ) || block_size > sizeof( hmac->opad )`
2752 * because that triggers -Wlogical-op on GCC 7.3. */
2753 if (block_size > sizeof(ipad))
2754 return (PSA_ERROR_NOT_SUPPORTED);
2755 if (block_size > sizeof(hmac->opad))
2756 return (PSA_ERROR_NOT_SUPPORTED);
2757 if (block_size < hash_size)
2758 return (PSA_ERROR_NOT_SUPPORTED);
2760 if (key_length > block_size) {
2761 status = psa_hash_compute(hash_alg, key, key_length,
2762 ipad, sizeof(ipad), &key_length);
2763 if (status != PSA_SUCCESS)
2764 goto cleanup;
2766 /* A 0-length key is not commonly used in HMAC when used as a MAC,
2767 * but it is permitted. It is common when HMAC is used in HKDF, for
2768 * example. Don't call `memcpy` in the 0-length because `key` could be
2769 * an invalid pointer which would make the behavior undefined. */
2770 else if (key_length != 0)
2771 memcpy(ipad, key, key_length);
2773 /* ipad contains the key followed by garbage. Xor and fill with 0x36
2774 * to create the ipad value. */
2775 for (i = 0; i < key_length; i++)
2776 ipad[i] ^= 0x36;
2777 memset(ipad + key_length, 0x36, block_size - key_length);
2779 /* Copy the key material from ipad to opad, flipping the requisite bits,
2780 * and filling the rest of opad with the requisite constant. */
2781 for (i = 0; i < key_length; i++)
2782 hmac->opad[i] = ipad[i] ^ 0x36 ^ 0x5C;
2783 memset(hmac->opad + key_length, 0x5C, block_size - key_length);
2785 status = psa_hash_setup(&hmac->hash_ctx, hash_alg);
2786 if (status != PSA_SUCCESS)
2787 goto cleanup;
2789 status = psa_hash_update(&hmac->hash_ctx, ipad, block_size);
2791 cleanup:
2792 mbedtls_platform_zeroize(ipad, sizeof(ipad));
2794 return (status);
2796 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HMAC */
2798 static psa_status_t psa_mac_setup(psa_mac_operation_t *operation,
2799 mbedtls_svc_key_id_t key,
2800 psa_algorithm_t alg,
2801 int is_sign) {
2802 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2803 psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
2804 psa_key_slot_t *slot;
2805 psa_key_usage_t usage =
2806 is_sign ? PSA_KEY_USAGE_SIGN_HASH : PSA_KEY_USAGE_VERIFY_HASH;
2808 /* A context must be freshly initialized before it can be set up. */
2809 if (operation->alg != 0) {
2810 return (PSA_ERROR_BAD_STATE);
2813 status = psa_mac_init(operation, alg);
2814 if (status != PSA_SUCCESS)
2815 return (status);
2816 if (is_sign)
2817 operation->is_sign = 1;
2819 status = psa_get_and_lock_transparent_key_slot_with_policy(
2820 key, &slot, usage, alg);
2821 if (status != PSA_SUCCESS)
2822 goto exit;
2824 /* Validate the combination of key type and algorithm */
2825 status = psa_mac_key_can_do(alg, slot->attr.type);
2826 if (status != PSA_SUCCESS)
2827 goto exit;
2829 /* Get the output length for the algorithm and key combination. None of the
2830 * currently supported algorithms have an output length dependent on actual
2831 * key size, so setting it to a bogus value is currently OK. */
2832 operation->mac_size = PSA_MAC_LENGTH(slot->attr.type, 0, alg);
2834 if (operation->mac_size < 4) {
2835 /* A very short MAC is too short for security since it can be
2836 * brute-forced. Ancient protocols with 32-bit MACs do exist,
2837 * so we make this our minimum, even though 32 bits is still
2838 * too small for security. */
2839 status = PSA_ERROR_NOT_SUPPORTED;
2840 goto exit;
2843 if (operation->mac_size >
2844 PSA_MAC_LENGTH(slot->attr.type, 0, PSA_ALG_FULL_LENGTH_MAC(alg))) {
2845 /* It's impossible to "truncate" to a larger length than the full length
2846 * of the algorithm. */
2847 status = PSA_ERROR_INVALID_ARGUMENT;
2848 goto exit;
2851 #if defined(MBEDTLS_CMAC_C)
2852 if (PSA_ALG_FULL_LENGTH_MAC(alg) == PSA_ALG_CMAC) {
2853 status = psa_cmac_setup(operation, slot);
2854 } else
2855 #endif /* MBEDTLS_CMAC_C */
2856 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HMAC)
2857 if (PSA_ALG_IS_HMAC(alg)) {
2858 /* Sanity check. This shouldn't fail on a valid configuration. */
2859 if (operation->mac_size > sizeof(operation->ctx.hmac.opad)) {
2860 status = PSA_ERROR_NOT_SUPPORTED;
2861 goto exit;
2864 if (slot->attr.type != PSA_KEY_TYPE_HMAC) {
2865 status = PSA_ERROR_INVALID_ARGUMENT;
2866 goto exit;
2869 status = psa_hmac_setup_internal(&operation->ctx.hmac,
2870 slot->key.data,
2871 slot->key.bytes,
2872 PSA_ALG_HMAC_GET_HASH(alg));
2873 } else
2874 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HMAC */
2876 status = PSA_ERROR_NOT_SUPPORTED;
2879 exit:
2880 if (status != PSA_SUCCESS) {
2881 psa_mac_abort(operation);
2882 } else {
2883 operation->key_set = 1;
2886 unlock_status = psa_unlock_key_slot(slot);
2888 return ((status == PSA_SUCCESS) ? unlock_status : status);
2891 psa_status_t psa_mac_sign_setup(psa_mac_operation_t *operation,
2892 mbedtls_svc_key_id_t key,
2893 psa_algorithm_t alg) {
2894 return (psa_mac_setup(operation, key, alg, 1));
2897 psa_status_t psa_mac_verify_setup(psa_mac_operation_t *operation,
2898 mbedtls_svc_key_id_t key,
2899 psa_algorithm_t alg) {
2900 return (psa_mac_setup(operation, key, alg, 0));
2903 psa_status_t psa_mac_update(psa_mac_operation_t *operation,
2904 const uint8_t *input,
2905 size_t input_length) {
2906 psa_status_t status = PSA_ERROR_BAD_STATE;
2907 if (! operation->key_set)
2908 return (PSA_ERROR_BAD_STATE);
2909 if (operation->iv_required && ! operation->iv_set)
2910 return (PSA_ERROR_BAD_STATE);
2911 operation->has_input = 1;
2913 #if defined(MBEDTLS_CMAC_C)
2914 if (operation->alg == PSA_ALG_CMAC) {
2915 int ret = mbedtls_cipher_cmac_update(&operation->ctx.cmac,
2916 input, input_length);
2917 status = mbedtls_to_psa_error(ret);
2918 } else
2919 #endif /* MBEDTLS_CMAC_C */
2920 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HMAC)
2921 if (PSA_ALG_IS_HMAC(operation->alg)) {
2922 status = psa_hash_update(&operation->ctx.hmac.hash_ctx, input,
2923 input_length);
2924 } else
2925 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HMAC */
2927 /* This shouldn't happen if `operation` was initialized by
2928 * a setup function. */
2929 return (PSA_ERROR_BAD_STATE);
2932 if (status != PSA_SUCCESS)
2933 psa_mac_abort(operation);
2934 return (status);
2937 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HMAC)
2938 static psa_status_t psa_hmac_finish_internal(psa_hmac_internal_data *hmac,
2939 uint8_t *mac,
2940 size_t mac_size) {
2941 uint8_t tmp[MBEDTLS_MD_MAX_SIZE];
2942 psa_algorithm_t hash_alg = hmac->hash_ctx.alg;
2943 size_t hash_size = 0;
2944 size_t block_size = psa_get_hash_block_size(hash_alg);
2945 psa_status_t status;
2947 status = psa_hash_finish(&hmac->hash_ctx, tmp, sizeof(tmp), &hash_size);
2948 if (status != PSA_SUCCESS)
2949 return (status);
2950 /* From here on, tmp needs to be wiped. */
2952 status = psa_hash_setup(&hmac->hash_ctx, hash_alg);
2953 if (status != PSA_SUCCESS)
2954 goto exit;
2956 status = psa_hash_update(&hmac->hash_ctx, hmac->opad, block_size);
2957 if (status != PSA_SUCCESS)
2958 goto exit;
2960 status = psa_hash_update(&hmac->hash_ctx, tmp, hash_size);
2961 if (status != PSA_SUCCESS)
2962 goto exit;
2964 status = psa_hash_finish(&hmac->hash_ctx, tmp, sizeof(tmp), &hash_size);
2965 if (status != PSA_SUCCESS)
2966 goto exit;
2968 memcpy(mac, tmp, mac_size);
2970 exit:
2971 mbedtls_platform_zeroize(tmp, hash_size);
2972 return (status);
2974 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HMAC */
2976 static psa_status_t psa_mac_finish_internal(psa_mac_operation_t *operation,
2977 uint8_t *mac,
2978 size_t mac_size) {
2979 if (! operation->key_set)
2980 return (PSA_ERROR_BAD_STATE);
2981 if (operation->iv_required && ! operation->iv_set)
2982 return (PSA_ERROR_BAD_STATE);
2984 if (mac_size < operation->mac_size)
2985 return (PSA_ERROR_BUFFER_TOO_SMALL);
2987 #if defined(MBEDTLS_CMAC_C)
2988 if (operation->alg == PSA_ALG_CMAC) {
2989 uint8_t tmp[PSA_BLOCK_CIPHER_BLOCK_MAX_SIZE];
2990 int ret = mbedtls_cipher_cmac_finish(&operation->ctx.cmac, tmp);
2991 if (ret == 0)
2992 memcpy(mac, tmp, operation->mac_size);
2993 mbedtls_platform_zeroize(tmp, sizeof(tmp));
2994 return (mbedtls_to_psa_error(ret));
2995 } else
2996 #endif /* MBEDTLS_CMAC_C */
2997 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HMAC)
2998 if (PSA_ALG_IS_HMAC(operation->alg)) {
2999 return (psa_hmac_finish_internal(&operation->ctx.hmac,
3000 mac, operation->mac_size));
3001 } else
3002 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HMAC */
3004 /* This shouldn't happen if `operation` was initialized by
3005 * a setup function. */
3006 return (PSA_ERROR_BAD_STATE);
3010 psa_status_t psa_mac_sign_finish(psa_mac_operation_t *operation,
3011 uint8_t *mac,
3012 size_t mac_size,
3013 size_t *mac_length) {
3014 psa_status_t status;
3016 if (operation->alg == 0) {
3017 return (PSA_ERROR_BAD_STATE);
3020 /* Fill the output buffer with something that isn't a valid mac
3021 * (barring an attack on the mac and deliberately-crafted input),
3022 * in case the caller doesn't check the return status properly. */
3023 *mac_length = mac_size;
3024 /* If mac_size is 0 then mac may be NULL and then the
3025 * call to memset would have undefined behavior. */
3026 if (mac_size != 0)
3027 memset(mac, '!', mac_size);
3029 if (! operation->is_sign) {
3030 return (PSA_ERROR_BAD_STATE);
3033 status = psa_mac_finish_internal(operation, mac, mac_size);
3035 if (status == PSA_SUCCESS) {
3036 status = psa_mac_abort(operation);
3037 if (status == PSA_SUCCESS)
3038 *mac_length = operation->mac_size;
3039 else
3040 memset(mac, '!', mac_size);
3041 } else
3042 psa_mac_abort(operation);
3043 return (status);
3046 psa_status_t psa_mac_verify_finish(psa_mac_operation_t *operation,
3047 const uint8_t *mac,
3048 size_t mac_length) {
3049 uint8_t actual_mac[PSA_MAC_MAX_SIZE];
3050 psa_status_t status;
3052 if (operation->alg == 0) {
3053 return (PSA_ERROR_BAD_STATE);
3056 if (operation->is_sign) {
3057 return (PSA_ERROR_BAD_STATE);
3059 if (operation->mac_size != mac_length) {
3060 status = PSA_ERROR_INVALID_SIGNATURE;
3061 goto cleanup;
3064 status = psa_mac_finish_internal(operation,
3065 actual_mac, sizeof(actual_mac));
3066 if (status != PSA_SUCCESS)
3067 goto cleanup;
3069 if (safer_memcmp(mac, actual_mac, mac_length) != 0)
3070 status = PSA_ERROR_INVALID_SIGNATURE;
3072 cleanup:
3073 if (status == PSA_SUCCESS)
3074 status = psa_mac_abort(operation);
3075 else
3076 psa_mac_abort(operation);
3078 mbedtls_platform_zeroize(actual_mac, sizeof(actual_mac));
3080 return (status);
3085 /****************************************************************/
3086 /* Asymmetric cryptography */
3087 /****************************************************************/
3089 psa_status_t psa_sign_hash_internal(
3090 const psa_key_attributes_t *attributes,
3091 const uint8_t *key_buffer, size_t key_buffer_size,
3092 psa_algorithm_t alg, const uint8_t *hash, size_t hash_length,
3093 uint8_t *signature, size_t signature_size, size_t *signature_length) {
3094 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) || \
3095 defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS)
3096 if (attributes->core.type == PSA_KEY_TYPE_RSA_KEY_PAIR) {
3097 return (mbedtls_psa_rsa_sign_hash(
3098 attributes,
3099 key_buffer, key_buffer_size,
3100 alg, hash, hash_length,
3101 signature, signature_size, signature_length));
3102 } else
3103 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) ||
3104 * defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS) */
3105 #if defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
3106 defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)
3107 if (PSA_KEY_TYPE_IS_ECC(attributes->core.type)) {
3108 if (PSA_ALG_IS_ECDSA(alg)) {
3109 return (mbedtls_psa_ecdsa_sign_hash(
3110 attributes,
3111 key_buffer, key_buffer_size,
3112 alg, hash, hash_length,
3113 signature, signature_size, signature_length));
3114 } else {
3115 return (PSA_ERROR_INVALID_ARGUMENT);
3117 } else
3118 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
3119 * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) */
3121 (void)attributes;
3122 (void)key_buffer;
3123 (void)key_buffer_size;
3124 (void)alg;
3125 (void)hash;
3126 (void)hash_length;
3127 (void)signature;
3128 (void)signature_size;
3129 (void)signature_length;
3131 return (PSA_ERROR_NOT_SUPPORTED);
3135 psa_status_t psa_sign_hash(mbedtls_svc_key_id_t key,
3136 psa_algorithm_t alg,
3137 const uint8_t *hash,
3138 size_t hash_length,
3139 uint8_t *signature,
3140 size_t signature_size,
3141 size_t *signature_length) {
3142 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3143 psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
3144 psa_key_slot_t *slot;
3146 *signature_length = signature_size;
3147 /* Immediately reject a zero-length signature buffer. This guarantees
3148 * that signature must be a valid pointer. (On the other hand, the hash
3149 * buffer can in principle be empty since it doesn't actually have
3150 * to be a hash.) */
3151 if (signature_size == 0)
3152 return (PSA_ERROR_BUFFER_TOO_SMALL);
3154 status = psa_get_and_lock_key_slot_with_policy(key, &slot,
3155 PSA_KEY_USAGE_SIGN_HASH,
3156 alg);
3157 if (status != PSA_SUCCESS)
3158 goto exit;
3159 if (! PSA_KEY_TYPE_IS_KEY_PAIR(slot->attr.type)) {
3160 status = PSA_ERROR_INVALID_ARGUMENT;
3161 goto exit;
3164 psa_key_attributes_t attributes = {
3165 .core = slot->attr
3168 status = psa_driver_wrapper_sign_hash(
3169 &attributes, slot->key.data, slot->key.bytes,
3170 alg, hash, hash_length,
3171 signature, signature_size, signature_length);
3173 exit:
3174 /* Fill the unused part of the output buffer (the whole buffer on error,
3175 * the trailing part on success) with something that isn't a valid mac
3176 * (barring an attack on the mac and deliberately-crafted input),
3177 * in case the caller doesn't check the return status properly. */
3178 if (status == PSA_SUCCESS)
3179 memset(signature + *signature_length, '!',
3180 signature_size - *signature_length);
3181 else
3182 memset(signature, '!', signature_size);
3183 /* If signature_size is 0 then we have nothing to do. We must not call
3184 * memset because signature may be NULL in this case. */
3186 unlock_status = psa_unlock_key_slot(slot);
3188 return ((status == PSA_SUCCESS) ? unlock_status : status);
3191 psa_status_t psa_verify_hash_internal(
3192 const psa_key_attributes_t *attributes,
3193 const uint8_t *key_buffer, size_t key_buffer_size,
3194 psa_algorithm_t alg, const uint8_t *hash, size_t hash_length,
3195 const uint8_t *signature, size_t signature_length) {
3196 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) || \
3197 defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS)
3198 if (PSA_KEY_TYPE_IS_RSA(attributes->core.type)) {
3199 return (mbedtls_psa_rsa_verify_hash(
3200 attributes,
3201 key_buffer, key_buffer_size,
3202 alg, hash, hash_length,
3203 signature, signature_length));
3204 } else
3205 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) ||
3206 * defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS) */
3207 if (PSA_KEY_TYPE_IS_ECC(attributes->core.type)) {
3208 #if defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
3209 defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)
3210 if (PSA_ALG_IS_ECDSA(alg)) {
3211 return (mbedtls_psa_ecdsa_verify_hash(
3212 attributes,
3213 key_buffer, key_buffer_size,
3214 alg, hash, hash_length,
3215 signature, signature_length));
3216 } else
3217 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
3218 * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) */
3220 return (PSA_ERROR_INVALID_ARGUMENT);
3222 } else {
3223 (void)key_buffer;
3224 (void)key_buffer_size;
3225 (void)alg;
3226 (void)hash;
3227 (void)hash_length;
3228 (void)signature;
3229 (void)signature_length;
3231 return (PSA_ERROR_NOT_SUPPORTED);
3235 psa_status_t psa_verify_hash(mbedtls_svc_key_id_t key,
3236 psa_algorithm_t alg,
3237 const uint8_t *hash,
3238 size_t hash_length,
3239 const uint8_t *signature,
3240 size_t signature_length) {
3241 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3242 psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
3243 psa_key_slot_t *slot;
3245 status = psa_get_and_lock_key_slot_with_policy(key, &slot,
3246 PSA_KEY_USAGE_VERIFY_HASH,
3247 alg);
3248 if (status != PSA_SUCCESS)
3249 return (status);
3251 psa_key_attributes_t attributes = {
3252 .core = slot->attr
3255 status = psa_driver_wrapper_verify_hash(
3256 &attributes, slot->key.data, slot->key.bytes,
3257 alg, hash, hash_length,
3258 signature, signature_length);
3260 unlock_status = psa_unlock_key_slot(slot);
3262 return ((status == PSA_SUCCESS) ? unlock_status : status);
3265 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
3266 static void psa_rsa_oaep_set_padding_mode(psa_algorithm_t alg,
3267 mbedtls_rsa_context *rsa) {
3268 psa_algorithm_t hash_alg = PSA_ALG_RSA_OAEP_GET_HASH(alg);
3269 const mbedtls_md_info_t *md_info = mbedtls_md_info_from_psa(hash_alg);
3270 mbedtls_md_type_t md_alg = mbedtls_md_get_type(md_info);
3271 mbedtls_rsa_set_padding(rsa, MBEDTLS_RSA_PKCS_V21, md_alg);
3273 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP) */
3275 psa_status_t psa_asymmetric_encrypt(mbedtls_svc_key_id_t key,
3276 psa_algorithm_t alg,
3277 const uint8_t *input,
3278 size_t input_length,
3279 const uint8_t *salt,
3280 size_t salt_length,
3281 uint8_t *output,
3282 size_t output_size,
3283 size_t *output_length) {
3284 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3285 psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
3286 psa_key_slot_t *slot;
3288 (void) input;
3289 (void) input_length;
3290 (void) salt;
3291 (void) output;
3292 (void) output_size;
3294 *output_length = 0;
3296 if (! PSA_ALG_IS_RSA_OAEP(alg) && salt_length != 0)
3297 return (PSA_ERROR_INVALID_ARGUMENT);
3299 status = psa_get_and_lock_transparent_key_slot_with_policy(
3300 key, &slot, PSA_KEY_USAGE_ENCRYPT, alg);
3301 if (status != PSA_SUCCESS)
3302 return (status);
3303 if (!(PSA_KEY_TYPE_IS_PUBLIC_KEY(slot->attr.type) ||
3304 PSA_KEY_TYPE_IS_KEY_PAIR(slot->attr.type))) {
3305 status = PSA_ERROR_INVALID_ARGUMENT;
3306 goto exit;
3309 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT) || \
3310 defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
3311 if (PSA_KEY_TYPE_IS_RSA(slot->attr.type)) {
3312 mbedtls_rsa_context *rsa = NULL;
3313 status = mbedtls_psa_rsa_load_representation(slot->attr.type,
3314 slot->key.data,
3315 slot->key.bytes,
3316 &rsa);
3317 if (status != PSA_SUCCESS)
3318 goto rsa_exit;
3320 if (output_size < mbedtls_rsa_get_len(rsa)) {
3321 status = PSA_ERROR_BUFFER_TOO_SMALL;
3322 goto rsa_exit;
3324 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT)
3325 if (alg == PSA_ALG_RSA_PKCS1V15_CRYPT) {
3326 status = mbedtls_to_psa_error(
3327 mbedtls_rsa_pkcs1_encrypt(rsa,
3328 mbedtls_psa_get_random,
3329 MBEDTLS_PSA_RANDOM_STATE,
3330 MBEDTLS_RSA_PUBLIC,
3331 input_length,
3332 input,
3333 output));
3334 } else
3335 #endif /* MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT */
3336 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
3337 if (PSA_ALG_IS_RSA_OAEP(alg)) {
3338 psa_rsa_oaep_set_padding_mode(alg, rsa);
3339 status = mbedtls_to_psa_error(
3340 mbedtls_rsa_rsaes_oaep_encrypt(rsa,
3341 mbedtls_psa_get_random,
3342 MBEDTLS_PSA_RANDOM_STATE,
3343 MBEDTLS_RSA_PUBLIC,
3344 salt, salt_length,
3345 input_length,
3346 input,
3347 output));
3348 } else
3349 #endif /* MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP */
3351 status = PSA_ERROR_INVALID_ARGUMENT;
3352 goto rsa_exit;
3354 rsa_exit:
3355 if (status == PSA_SUCCESS)
3356 *output_length = mbedtls_rsa_get_len(rsa);
3358 mbedtls_rsa_free(rsa);
3359 mbedtls_free(rsa);
3360 } else
3361 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT) ||
3362 * defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP) */
3364 status = PSA_ERROR_NOT_SUPPORTED;
3367 exit:
3368 unlock_status = psa_unlock_key_slot(slot);
3370 return ((status == PSA_SUCCESS) ? unlock_status : status);
3373 psa_status_t psa_asymmetric_decrypt(mbedtls_svc_key_id_t key,
3374 psa_algorithm_t alg,
3375 const uint8_t *input,
3376 size_t input_length,
3377 const uint8_t *salt,
3378 size_t salt_length,
3379 uint8_t *output,
3380 size_t output_size,
3381 size_t *output_length) {
3382 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3383 psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
3384 psa_key_slot_t *slot;
3386 (void) input;
3387 (void) input_length;
3388 (void) salt;
3389 (void) output;
3390 (void) output_size;
3392 *output_length = 0;
3394 if (! PSA_ALG_IS_RSA_OAEP(alg) && salt_length != 0)
3395 return (PSA_ERROR_INVALID_ARGUMENT);
3397 status = psa_get_and_lock_transparent_key_slot_with_policy(
3398 key, &slot, PSA_KEY_USAGE_DECRYPT, alg);
3399 if (status != PSA_SUCCESS)
3400 return (status);
3401 if (! PSA_KEY_TYPE_IS_KEY_PAIR(slot->attr.type)) {
3402 status = PSA_ERROR_INVALID_ARGUMENT;
3403 goto exit;
3406 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT) || \
3407 defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
3408 if (slot->attr.type == PSA_KEY_TYPE_RSA_KEY_PAIR) {
3409 mbedtls_rsa_context *rsa = NULL;
3410 status = mbedtls_psa_rsa_load_representation(slot->attr.type,
3411 slot->key.data,
3412 slot->key.bytes,
3413 &rsa);
3414 if (status != PSA_SUCCESS)
3415 goto exit;
3417 if (input_length != mbedtls_rsa_get_len(rsa)) {
3418 status = PSA_ERROR_INVALID_ARGUMENT;
3419 goto rsa_exit;
3422 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT)
3423 if (alg == PSA_ALG_RSA_PKCS1V15_CRYPT) {
3424 status = mbedtls_to_psa_error(
3425 mbedtls_rsa_pkcs1_decrypt(rsa,
3426 mbedtls_psa_get_random,
3427 MBEDTLS_PSA_RANDOM_STATE,
3428 MBEDTLS_RSA_PRIVATE,
3429 output_length,
3430 input,
3431 output,
3432 output_size));
3433 } else
3434 #endif /* MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT */
3435 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
3436 if (PSA_ALG_IS_RSA_OAEP(alg)) {
3437 psa_rsa_oaep_set_padding_mode(alg, rsa);
3438 status = mbedtls_to_psa_error(
3439 mbedtls_rsa_rsaes_oaep_decrypt(rsa,
3440 mbedtls_psa_get_random,
3441 MBEDTLS_PSA_RANDOM_STATE,
3442 MBEDTLS_RSA_PRIVATE,
3443 salt, salt_length,
3444 output_length,
3445 input,
3446 output,
3447 output_size));
3448 } else
3449 #endif /* MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP */
3451 status = PSA_ERROR_INVALID_ARGUMENT;
3454 rsa_exit:
3455 mbedtls_rsa_free(rsa);
3456 mbedtls_free(rsa);
3457 } else
3458 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT) ||
3459 * defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP) */
3461 status = PSA_ERROR_NOT_SUPPORTED;
3464 exit:
3465 unlock_status = psa_unlock_key_slot(slot);
3467 return ((status == PSA_SUCCESS) ? unlock_status : status);
3472 /****************************************************************/
3473 /* Symmetric cryptography */
3474 /****************************************************************/
3476 static psa_status_t psa_cipher_setup(psa_cipher_operation_t *operation,
3477 mbedtls_svc_key_id_t key,
3478 psa_algorithm_t alg,
3479 mbedtls_operation_t cipher_operation) {
3480 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3481 psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
3482 int ret = 0;
3483 psa_key_slot_t *slot;
3484 size_t key_bits;
3485 const mbedtls_cipher_info_t *cipher_info = NULL;
3486 psa_key_usage_t usage = (cipher_operation == MBEDTLS_ENCRYPT ?
3487 PSA_KEY_USAGE_ENCRYPT :
3488 PSA_KEY_USAGE_DECRYPT);
3490 /* A context must be freshly initialized before it can be set up. */
3491 if (operation->alg != 0)
3492 return (PSA_ERROR_BAD_STATE);
3494 /* The requested algorithm must be one that can be processed by cipher. */
3495 if (! PSA_ALG_IS_CIPHER(alg))
3496 return (PSA_ERROR_INVALID_ARGUMENT);
3498 /* Fetch key material from key storage. */
3499 status = psa_get_and_lock_key_slot_with_policy(key, &slot, usage, alg);
3500 if (status != PSA_SUCCESS)
3501 goto exit;
3503 /* Initialize the operation struct members, except for alg. The alg member
3504 * is used to indicate to psa_cipher_abort that there are resources to free,
3505 * so we only set it after resources have been allocated/initialized. */
3506 operation->key_set = 0;
3507 operation->iv_set = 0;
3508 operation->mbedtls_in_use = 0;
3509 operation->iv_size = 0;
3510 operation->block_size = 0;
3511 if (alg == PSA_ALG_ECB_NO_PADDING)
3512 operation->iv_required = 0;
3513 else
3514 operation->iv_required = 1;
3516 /* Try doing the operation through a driver before using software fallback. */
3517 if (cipher_operation == MBEDTLS_ENCRYPT)
3518 status = psa_driver_wrapper_cipher_encrypt_setup(&operation->ctx.driver,
3519 slot,
3520 alg);
3521 else
3522 status = psa_driver_wrapper_cipher_decrypt_setup(&operation->ctx.driver,
3523 slot,
3524 alg);
3526 if (status == PSA_SUCCESS) {
3527 /* Once the driver context is initialised, it needs to be freed using
3528 * psa_cipher_abort. Indicate this through setting alg. */
3529 operation->alg = alg;
3532 if (status != PSA_ERROR_NOT_SUPPORTED ||
3533 psa_key_lifetime_is_external(slot->attr.lifetime))
3534 goto exit;
3536 /* Proceed with initializing an mbed TLS cipher context if no driver is
3537 * available for the given algorithm & key. */
3538 mbedtls_cipher_init(&operation->ctx.cipher);
3540 /* Once the cipher context is initialised, it needs to be freed using
3541 * psa_cipher_abort. Indicate there is something to be freed through setting
3542 * alg, and indicate the operation is being done using mbedtls crypto through
3543 * setting mbedtls_in_use. */
3544 operation->alg = alg;
3545 operation->mbedtls_in_use = 1;
3547 key_bits = psa_get_key_slot_bits(slot);
3548 cipher_info = mbedtls_cipher_info_from_psa(alg, slot->attr.type, key_bits, NULL);
3549 if (cipher_info == NULL) {
3550 status = PSA_ERROR_NOT_SUPPORTED;
3551 goto exit;
3554 ret = mbedtls_cipher_setup(&operation->ctx.cipher, cipher_info);
3555 if (ret != 0)
3556 goto exit;
3558 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES)
3559 if (slot->attr.type == PSA_KEY_TYPE_DES && key_bits == 128) {
3560 /* Two-key Triple-DES is 3-key Triple-DES with K1=K3 */
3561 uint8_t keys[24];
3562 memcpy(keys, slot->key.data, 16);
3563 memcpy(keys + 16, slot->key.data, 8);
3564 ret = mbedtls_cipher_setkey(&operation->ctx.cipher,
3565 keys,
3566 192, cipher_operation);
3567 } else
3568 #endif
3570 ret = mbedtls_cipher_setkey(&operation->ctx.cipher,
3571 slot->key.data,
3572 (int) key_bits, cipher_operation);
3574 if (ret != 0)
3575 goto exit;
3577 #if defined(MBEDTLS_PSA_BUILTIN_ALG_CBC_NO_PADDING) || \
3578 defined(MBEDTLS_PSA_BUILTIN_ALG_CBC_PKCS7)
3579 switch (alg) {
3580 case PSA_ALG_CBC_NO_PADDING:
3581 ret = mbedtls_cipher_set_padding_mode(&operation->ctx.cipher,
3582 MBEDTLS_PADDING_NONE);
3583 break;
3584 case PSA_ALG_CBC_PKCS7:
3585 ret = mbedtls_cipher_set_padding_mode(&operation->ctx.cipher,
3586 MBEDTLS_PADDING_PKCS7);
3587 break;
3588 default:
3589 /* The algorithm doesn't involve padding. */
3590 ret = 0;
3591 break;
3593 if (ret != 0)
3594 goto exit;
3595 #endif /* MBEDTLS_PSA_BUILTIN_ALG_CBC_NO_PADDING || MBEDTLS_PSA_BUILTIN_ALG_CBC_PKCS7 */
3597 operation->block_size = (PSA_ALG_IS_STREAM_CIPHER(alg) ? 1 :
3598 PSA_BLOCK_CIPHER_BLOCK_LENGTH(slot->attr.type));
3599 if ((alg & PSA_ALG_CIPHER_FROM_BLOCK_FLAG) != 0 &&
3600 alg != PSA_ALG_ECB_NO_PADDING) {
3601 operation->iv_size = PSA_BLOCK_CIPHER_BLOCK_LENGTH(slot->attr.type);
3603 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_CHACHA20)
3604 else if (alg == PSA_ALG_STREAM_CIPHER && slot->attr.type == PSA_KEY_TYPE_CHACHA20)
3605 operation->iv_size = 12;
3606 #endif
3608 status = PSA_SUCCESS;
3610 exit:
3611 if (ret != 0)
3612 status = mbedtls_to_psa_error(ret);
3613 if (status == PSA_SUCCESS) {
3614 /* Update operation flags for both driver and software implementations */
3615 operation->key_set = 1;
3616 } else
3617 psa_cipher_abort(operation);
3619 unlock_status = psa_unlock_key_slot(slot);
3621 return ((status == PSA_SUCCESS) ? unlock_status : status);
3624 psa_status_t psa_cipher_encrypt_setup(psa_cipher_operation_t *operation,
3625 mbedtls_svc_key_id_t key,
3626 psa_algorithm_t alg) {
3627 return (psa_cipher_setup(operation, key, alg, MBEDTLS_ENCRYPT));
3630 psa_status_t psa_cipher_decrypt_setup(psa_cipher_operation_t *operation,
3631 mbedtls_svc_key_id_t key,
3632 psa_algorithm_t alg) {
3633 return (psa_cipher_setup(operation, key, alg, MBEDTLS_DECRYPT));
3636 psa_status_t psa_cipher_generate_iv(psa_cipher_operation_t *operation,
3637 uint8_t *iv,
3638 size_t iv_size,
3639 size_t *iv_length) {
3640 psa_status_t status;
3641 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3642 if (operation->iv_set || ! operation->iv_required) {
3643 return (PSA_ERROR_BAD_STATE);
3646 if (operation->mbedtls_in_use == 0) {
3647 status = psa_driver_wrapper_cipher_generate_iv(&operation->ctx.driver,
3649 iv_size,
3650 iv_length);
3651 goto exit;
3654 if (iv_size < operation->iv_size) {
3655 status = PSA_ERROR_BUFFER_TOO_SMALL;
3656 goto exit;
3658 ret = mbedtls_psa_get_random(MBEDTLS_PSA_RANDOM_STATE,
3659 iv, operation->iv_size);
3660 if (ret != 0) {
3661 status = mbedtls_to_psa_error(ret);
3662 goto exit;
3665 *iv_length = operation->iv_size;
3666 status = psa_cipher_set_iv(operation, iv, *iv_length);
3668 exit:
3669 if (status == PSA_SUCCESS)
3670 operation->iv_set = 1;
3671 else
3672 psa_cipher_abort(operation);
3673 return (status);
3676 psa_status_t psa_cipher_set_iv(psa_cipher_operation_t *operation,
3677 const uint8_t *iv,
3678 size_t iv_length) {
3679 psa_status_t status;
3680 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3681 if (operation->iv_set || ! operation->iv_required) {
3682 return (PSA_ERROR_BAD_STATE);
3685 if (operation->mbedtls_in_use == 0) {
3686 status = psa_driver_wrapper_cipher_set_iv(&operation->ctx.driver,
3688 iv_length);
3689 goto exit;
3692 if (iv_length != operation->iv_size) {
3693 status = PSA_ERROR_INVALID_ARGUMENT;
3694 goto exit;
3696 ret = mbedtls_cipher_set_iv(&operation->ctx.cipher, iv, iv_length);
3697 status = mbedtls_to_psa_error(ret);
3698 exit:
3699 if (status == PSA_SUCCESS)
3700 operation->iv_set = 1;
3701 else
3702 psa_cipher_abort(operation);
3703 return (status);
3706 /* Process input for which the algorithm is set to ECB mode. This requires
3707 * manual processing, since the PSA API is defined as being able to process
3708 * arbitrary-length calls to psa_cipher_update() with ECB mode, but the
3709 * underlying mbedtls_cipher_update only takes full blocks. */
3710 static psa_status_t psa_cipher_update_ecb_internal(
3711 mbedtls_cipher_context_t *ctx,
3712 const uint8_t *input,
3713 size_t input_length,
3714 uint8_t *output,
3715 size_t output_size,
3716 size_t *output_length) {
3717 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3718 size_t block_size = ctx->cipher_info->block_size;
3719 size_t internal_output_length = 0;
3720 *output_length = 0;
3722 if (input_length == 0) {
3723 status = PSA_SUCCESS;
3724 goto exit;
3727 if (ctx->unprocessed_len > 0) {
3728 /* Fill up to block size, and run the block if there's a full one. */
3729 size_t bytes_to_copy = block_size - ctx->unprocessed_len;
3731 if (input_length < bytes_to_copy)
3732 bytes_to_copy = input_length;
3734 memcpy(&(ctx->unprocessed_data[ctx->unprocessed_len]),
3735 input, bytes_to_copy);
3736 input_length -= bytes_to_copy;
3737 input += bytes_to_copy;
3738 ctx->unprocessed_len += bytes_to_copy;
3740 if (ctx->unprocessed_len == block_size) {
3741 status = mbedtls_to_psa_error(
3742 mbedtls_cipher_update(ctx,
3743 ctx->unprocessed_data,
3744 block_size,
3745 output, &internal_output_length));
3747 if (status != PSA_SUCCESS)
3748 goto exit;
3750 output += internal_output_length;
3751 output_size -= internal_output_length;
3752 *output_length += internal_output_length;
3753 ctx->unprocessed_len = 0;
3757 while (input_length >= block_size) {
3758 /* Run all full blocks we have, one by one */
3759 status = mbedtls_to_psa_error(
3760 mbedtls_cipher_update(ctx, input,
3761 block_size,
3762 output, &internal_output_length));
3764 if (status != PSA_SUCCESS)
3765 goto exit;
3767 input_length -= block_size;
3768 input += block_size;
3770 output += internal_output_length;
3771 output_size -= internal_output_length;
3772 *output_length += internal_output_length;
3775 if (input_length > 0) {
3776 /* Save unprocessed bytes for later processing */
3777 memcpy(&(ctx->unprocessed_data[ctx->unprocessed_len]),
3778 input, input_length);
3779 ctx->unprocessed_len += input_length;
3782 status = PSA_SUCCESS;
3784 exit:
3785 return (status);
3788 psa_status_t psa_cipher_update(psa_cipher_operation_t *operation,
3789 const uint8_t *input,
3790 size_t input_length,
3791 uint8_t *output,
3792 size_t output_size,
3793 size_t *output_length) {
3794 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3795 size_t expected_output_size;
3796 if (operation->alg == 0) {
3797 return (PSA_ERROR_BAD_STATE);
3799 if (operation->iv_required && ! operation->iv_set) {
3800 return (PSA_ERROR_BAD_STATE);
3803 if (operation->mbedtls_in_use == 0) {
3804 status = psa_driver_wrapper_cipher_update(&operation->ctx.driver,
3805 input,
3806 input_length,
3807 output,
3808 output_size,
3809 output_length);
3810 goto exit;
3813 if (! PSA_ALG_IS_STREAM_CIPHER(operation->alg)) {
3814 /* Take the unprocessed partial block left over from previous
3815 * update calls, if any, plus the input to this call. Remove
3816 * the last partial block, if any. You get the data that will be
3817 * output in this call. */
3818 expected_output_size =
3819 (operation->ctx.cipher.unprocessed_len + input_length)
3820 / operation->block_size * operation->block_size;
3821 } else {
3822 expected_output_size = input_length;
3825 if (output_size < expected_output_size) {
3826 status = PSA_ERROR_BUFFER_TOO_SMALL;
3827 goto exit;
3830 if (operation->alg == PSA_ALG_ECB_NO_PADDING) {
3831 /* mbedtls_cipher_update has an API inconsistency: it will only
3832 * process a single block at a time in ECB mode. Abstract away that
3833 * inconsistency here to match the PSA API behaviour. */
3834 status = psa_cipher_update_ecb_internal(&operation->ctx.cipher,
3835 input,
3836 input_length,
3837 output,
3838 output_size,
3839 output_length);
3840 } else {
3841 status = mbedtls_to_psa_error(
3842 mbedtls_cipher_update(&operation->ctx.cipher, input,
3843 input_length, output, output_length));
3845 exit:
3846 if (status != PSA_SUCCESS)
3847 psa_cipher_abort(operation);
3848 return (status);
3851 psa_status_t psa_cipher_finish(psa_cipher_operation_t *operation,
3852 uint8_t *output,
3853 size_t output_size,
3854 size_t *output_length) {
3855 psa_status_t status = PSA_ERROR_GENERIC_ERROR;
3856 uint8_t temp_output_buffer[MBEDTLS_MAX_BLOCK_LENGTH];
3857 if (operation->alg == 0) {
3858 return (PSA_ERROR_BAD_STATE);
3860 if (operation->iv_required && ! operation->iv_set) {
3861 return (PSA_ERROR_BAD_STATE);
3864 if (operation->mbedtls_in_use == 0) {
3865 status = psa_driver_wrapper_cipher_finish(&operation->ctx.driver,
3866 output,
3867 output_size,
3868 output_length);
3869 goto exit;
3872 if (operation->ctx.cipher.unprocessed_len != 0) {
3873 if (operation->alg == PSA_ALG_ECB_NO_PADDING ||
3874 operation->alg == PSA_ALG_CBC_NO_PADDING) {
3875 status = PSA_ERROR_INVALID_ARGUMENT;
3876 goto exit;
3880 status = mbedtls_to_psa_error(
3881 mbedtls_cipher_finish(&operation->ctx.cipher,
3882 temp_output_buffer,
3883 output_length));
3884 if (status != PSA_SUCCESS)
3885 goto exit;
3887 if (*output_length == 0)
3888 ; /* Nothing to copy. Note that output may be NULL in this case. */
3889 else if (output_size >= *output_length)
3890 memcpy(output, temp_output_buffer, *output_length);
3891 else
3892 status = PSA_ERROR_BUFFER_TOO_SMALL;
3894 exit:
3895 if (operation->mbedtls_in_use == 1)
3896 mbedtls_platform_zeroize(temp_output_buffer, sizeof(temp_output_buffer));
3898 if (status == PSA_SUCCESS)
3899 return (psa_cipher_abort(operation));
3900 else {
3901 *output_length = 0;
3902 (void) psa_cipher_abort(operation);
3904 return (status);
3908 psa_status_t psa_cipher_abort(psa_cipher_operation_t *operation) {
3909 if (operation->alg == 0) {
3910 /* The object has (apparently) been initialized but it is not (yet)
3911 * in use. It's ok to call abort on such an object, and there's
3912 * nothing to do. */
3913 return (PSA_SUCCESS);
3916 /* Sanity check (shouldn't happen: operation->alg should
3917 * always have been initialized to a valid value). */
3918 if (! PSA_ALG_IS_CIPHER(operation->alg))
3919 return (PSA_ERROR_BAD_STATE);
3921 if (operation->mbedtls_in_use == 0)
3922 psa_driver_wrapper_cipher_abort(&operation->ctx.driver);
3923 else
3924 mbedtls_cipher_free(&operation->ctx.cipher);
3926 operation->alg = 0;
3927 operation->key_set = 0;
3928 operation->iv_set = 0;
3929 operation->mbedtls_in_use = 0;
3930 operation->iv_size = 0;
3931 operation->block_size = 0;
3932 operation->iv_required = 0;
3934 return (PSA_SUCCESS);
3940 /****************************************************************/
3941 /* AEAD */
3942 /****************************************************************/
3944 typedef struct {
3945 psa_key_slot_t *slot;
3946 const mbedtls_cipher_info_t *cipher_info;
3947 union {
3948 unsigned dummy; /* Make the union non-empty even with no supported algorithms. */
3949 #if defined(MBEDTLS_CCM_C)
3950 mbedtls_ccm_context ccm;
3951 #endif /* MBEDTLS_CCM_C */
3952 #if defined(MBEDTLS_GCM_C)
3953 mbedtls_gcm_context gcm;
3954 #endif /* MBEDTLS_GCM_C */
3955 #if defined(MBEDTLS_CHACHAPOLY_C)
3956 mbedtls_chachapoly_context chachapoly;
3957 #endif /* MBEDTLS_CHACHAPOLY_C */
3958 } ctx;
3959 psa_algorithm_t core_alg;
3960 uint8_t full_tag_length;
3961 uint8_t tag_length;
3962 } aead_operation_t;
3964 #define AEAD_OPERATION_INIT {0, 0, {0}, 0, 0, 0}
3966 static void psa_aead_abort_internal(aead_operation_t *operation) {
3967 switch (operation->core_alg) {
3968 #if defined(MBEDTLS_CCM_C)
3969 case PSA_ALG_CCM:
3970 mbedtls_ccm_free(&operation->ctx.ccm);
3971 break;
3972 #endif /* MBEDTLS_CCM_C */
3973 #if defined(MBEDTLS_GCM_C)
3974 case PSA_ALG_GCM:
3975 mbedtls_gcm_free(&operation->ctx.gcm);
3976 break;
3977 #endif /* MBEDTLS_GCM_C */
3980 psa_unlock_key_slot(operation->slot);
3983 static psa_status_t psa_aead_setup(aead_operation_t *operation,
3984 mbedtls_svc_key_id_t key,
3985 psa_key_usage_t usage,
3986 psa_algorithm_t alg) {
3987 psa_status_t status;
3988 size_t key_bits;
3989 mbedtls_cipher_id_t cipher_id;
3991 status = psa_get_and_lock_transparent_key_slot_with_policy(
3992 key, &operation->slot, usage, alg);
3993 if (status != PSA_SUCCESS)
3994 return (status);
3996 key_bits = psa_get_key_slot_bits(operation->slot);
3998 operation->cipher_info =
3999 mbedtls_cipher_info_from_psa(alg, operation->slot->attr.type, key_bits,
4000 &cipher_id);
4001 if (operation->cipher_info == NULL) {
4002 status = PSA_ERROR_NOT_SUPPORTED;
4003 goto cleanup;
4006 switch (PSA_ALG_AEAD_WITH_SHORTENED_TAG(alg, 0)) {
4007 #if defined(MBEDTLS_CCM_C)
4008 case PSA_ALG_AEAD_WITH_SHORTENED_TAG(PSA_ALG_CCM, 0):
4009 operation->core_alg = PSA_ALG_CCM;
4010 operation->full_tag_length = 16;
4011 /* CCM allows the following tag lengths: 4, 6, 8, 10, 12, 14, 16.
4012 * The call to mbedtls_ccm_encrypt_and_tag or
4013 * mbedtls_ccm_auth_decrypt will validate the tag length. */
4014 if (PSA_BLOCK_CIPHER_BLOCK_LENGTH(operation->slot->attr.type) != 16) {
4015 status = PSA_ERROR_INVALID_ARGUMENT;
4016 goto cleanup;
4018 mbedtls_ccm_init(&operation->ctx.ccm);
4019 status = mbedtls_to_psa_error(
4020 mbedtls_ccm_setkey(&operation->ctx.ccm, cipher_id,
4021 operation->slot->key.data,
4022 (unsigned int) key_bits));
4023 if (status != 0)
4024 goto cleanup;
4025 break;
4026 #endif /* MBEDTLS_CCM_C */
4028 #if defined(MBEDTLS_GCM_C)
4029 case PSA_ALG_AEAD_WITH_SHORTENED_TAG(PSA_ALG_GCM, 0):
4030 operation->core_alg = PSA_ALG_GCM;
4031 operation->full_tag_length = 16;
4032 /* GCM allows the following tag lengths: 4, 8, 12, 13, 14, 15, 16.
4033 * The call to mbedtls_gcm_crypt_and_tag or
4034 * mbedtls_gcm_auth_decrypt will validate the tag length. */
4035 if (PSA_BLOCK_CIPHER_BLOCK_LENGTH(operation->slot->attr.type) != 16) {
4036 status = PSA_ERROR_INVALID_ARGUMENT;
4037 goto cleanup;
4039 mbedtls_gcm_init(&operation->ctx.gcm);
4040 status = mbedtls_to_psa_error(
4041 mbedtls_gcm_setkey(&operation->ctx.gcm, cipher_id,
4042 operation->slot->key.data,
4043 (unsigned int) key_bits));
4044 if (status != 0)
4045 goto cleanup;
4046 break;
4047 #endif /* MBEDTLS_GCM_C */
4049 #if defined(MBEDTLS_CHACHAPOLY_C)
4050 case PSA_ALG_AEAD_WITH_SHORTENED_TAG(PSA_ALG_CHACHA20_POLY1305, 0):
4051 operation->core_alg = PSA_ALG_CHACHA20_POLY1305;
4052 operation->full_tag_length = 16;
4053 /* We only support the default tag length. */
4054 if (alg != PSA_ALG_CHACHA20_POLY1305) {
4055 status = PSA_ERROR_NOT_SUPPORTED;
4056 goto cleanup;
4058 mbedtls_chachapoly_init(&operation->ctx.chachapoly);
4059 status = mbedtls_to_psa_error(
4060 mbedtls_chachapoly_setkey(&operation->ctx.chachapoly,
4061 operation->slot->key.data));
4062 if (status != 0)
4063 goto cleanup;
4064 break;
4065 #endif /* MBEDTLS_CHACHAPOLY_C */
4067 default:
4068 status = PSA_ERROR_NOT_SUPPORTED;
4069 goto cleanup;
4072 if (PSA_AEAD_TAG_LENGTH(alg) > operation->full_tag_length) {
4073 status = PSA_ERROR_INVALID_ARGUMENT;
4074 goto cleanup;
4076 operation->tag_length = PSA_AEAD_TAG_LENGTH(alg);
4078 return (PSA_SUCCESS);
4080 cleanup:
4081 psa_aead_abort_internal(operation);
4082 return (status);
4085 psa_status_t psa_aead_encrypt(mbedtls_svc_key_id_t key,
4086 psa_algorithm_t alg,
4087 const uint8_t *nonce,
4088 size_t nonce_length,
4089 const uint8_t *additional_data,
4090 size_t additional_data_length,
4091 const uint8_t *plaintext,
4092 size_t plaintext_length,
4093 uint8_t *ciphertext,
4094 size_t ciphertext_size,
4095 size_t *ciphertext_length) {
4096 psa_status_t status;
4097 aead_operation_t operation = AEAD_OPERATION_INIT;
4098 uint8_t *tag;
4100 *ciphertext_length = 0;
4102 status = psa_aead_setup(&operation, key, PSA_KEY_USAGE_ENCRYPT, alg);
4103 if (status != PSA_SUCCESS)
4104 return (status);
4106 /* For all currently supported modes, the tag is at the end of the
4107 * ciphertext. */
4108 if (ciphertext_size < (plaintext_length + operation.tag_length)) {
4109 status = PSA_ERROR_BUFFER_TOO_SMALL;
4110 goto exit;
4112 tag = ciphertext + plaintext_length;
4114 #if defined(MBEDTLS_GCM_C)
4115 if (operation.core_alg == PSA_ALG_GCM) {
4116 status = mbedtls_to_psa_error(
4117 mbedtls_gcm_crypt_and_tag(&operation.ctx.gcm,
4118 MBEDTLS_GCM_ENCRYPT,
4119 plaintext_length,
4120 nonce, nonce_length,
4121 additional_data, additional_data_length,
4122 plaintext, ciphertext,
4123 operation.tag_length, tag));
4124 } else
4125 #endif /* MBEDTLS_GCM_C */
4126 #if defined(MBEDTLS_CCM_C)
4127 if (operation.core_alg == PSA_ALG_CCM) {
4128 status = mbedtls_to_psa_error(
4129 mbedtls_ccm_encrypt_and_tag(&operation.ctx.ccm,
4130 plaintext_length,
4131 nonce, nonce_length,
4132 additional_data,
4133 additional_data_length,
4134 plaintext, ciphertext,
4135 tag, operation.tag_length));
4136 } else
4137 #endif /* MBEDTLS_CCM_C */
4138 #if defined(MBEDTLS_CHACHAPOLY_C)
4139 if (operation.core_alg == PSA_ALG_CHACHA20_POLY1305) {
4140 if (nonce_length != 12 || operation.tag_length != 16) {
4141 status = PSA_ERROR_NOT_SUPPORTED;
4142 goto exit;
4144 status = mbedtls_to_psa_error(
4145 mbedtls_chachapoly_encrypt_and_tag(&operation.ctx.chachapoly,
4146 plaintext_length,
4147 nonce,
4148 additional_data,
4149 additional_data_length,
4150 plaintext,
4151 ciphertext,
4152 tag));
4153 } else
4154 #endif /* MBEDTLS_CHACHAPOLY_C */
4156 (void) tag;
4157 return (PSA_ERROR_NOT_SUPPORTED);
4160 if (status != PSA_SUCCESS && ciphertext_size != 0)
4161 memset(ciphertext, 0, ciphertext_size);
4163 exit:
4164 psa_aead_abort_internal(&operation);
4165 if (status == PSA_SUCCESS)
4166 *ciphertext_length = plaintext_length + operation.tag_length;
4167 return (status);
4170 /* Locate the tag in a ciphertext buffer containing the encrypted data
4171 * followed by the tag. Return the length of the part preceding the tag in
4172 * *plaintext_length. This is the size of the plaintext in modes where
4173 * the encrypted data has the same size as the plaintext, such as
4174 * CCM and GCM. */
4175 static psa_status_t psa_aead_unpadded_locate_tag(size_t tag_length,
4176 const uint8_t *ciphertext,
4177 size_t ciphertext_length,
4178 size_t plaintext_size,
4179 const uint8_t **p_tag) {
4180 size_t payload_length;
4181 if (tag_length > ciphertext_length)
4182 return (PSA_ERROR_INVALID_ARGUMENT);
4183 payload_length = ciphertext_length - tag_length;
4184 if (payload_length > plaintext_size)
4185 return (PSA_ERROR_BUFFER_TOO_SMALL);
4186 *p_tag = ciphertext + payload_length;
4187 return (PSA_SUCCESS);
4190 psa_status_t psa_aead_decrypt(mbedtls_svc_key_id_t key,
4191 psa_algorithm_t alg,
4192 const uint8_t *nonce,
4193 size_t nonce_length,
4194 const uint8_t *additional_data,
4195 size_t additional_data_length,
4196 const uint8_t *ciphertext,
4197 size_t ciphertext_length,
4198 uint8_t *plaintext,
4199 size_t plaintext_size,
4200 size_t *plaintext_length) {
4201 psa_status_t status;
4202 aead_operation_t operation = AEAD_OPERATION_INIT;
4203 const uint8_t *tag = NULL;
4205 *plaintext_length = 0;
4207 status = psa_aead_setup(&operation, key, PSA_KEY_USAGE_DECRYPT, alg);
4208 if (status != PSA_SUCCESS)
4209 return (status);
4211 status = psa_aead_unpadded_locate_tag(operation.tag_length,
4212 ciphertext, ciphertext_length,
4213 plaintext_size, &tag);
4214 if (status != PSA_SUCCESS)
4215 goto exit;
4217 #if defined(MBEDTLS_GCM_C)
4218 if (operation.core_alg == PSA_ALG_GCM) {
4219 status = mbedtls_to_psa_error(
4220 mbedtls_gcm_auth_decrypt(&operation.ctx.gcm,
4221 ciphertext_length - operation.tag_length,
4222 nonce, nonce_length,
4223 additional_data,
4224 additional_data_length,
4225 tag, operation.tag_length,
4226 ciphertext, plaintext));
4227 } else
4228 #endif /* MBEDTLS_GCM_C */
4229 #if defined(MBEDTLS_CCM_C)
4230 if (operation.core_alg == PSA_ALG_CCM) {
4231 status = mbedtls_to_psa_error(
4232 mbedtls_ccm_auth_decrypt(&operation.ctx.ccm,
4233 ciphertext_length - operation.tag_length,
4234 nonce, nonce_length,
4235 additional_data,
4236 additional_data_length,
4237 ciphertext, plaintext,
4238 tag, operation.tag_length));
4239 } else
4240 #endif /* MBEDTLS_CCM_C */
4241 #if defined(MBEDTLS_CHACHAPOLY_C)
4242 if (operation.core_alg == PSA_ALG_CHACHA20_POLY1305) {
4243 if (nonce_length != 12 || operation.tag_length != 16) {
4244 status = PSA_ERROR_NOT_SUPPORTED;
4245 goto exit;
4247 status = mbedtls_to_psa_error(
4248 mbedtls_chachapoly_auth_decrypt(&operation.ctx.chachapoly,
4249 ciphertext_length - operation.tag_length,
4250 nonce,
4251 additional_data,
4252 additional_data_length,
4253 tag,
4254 ciphertext,
4255 plaintext));
4256 } else
4257 #endif /* MBEDTLS_CHACHAPOLY_C */
4259 return (PSA_ERROR_NOT_SUPPORTED);
4262 if (status != PSA_SUCCESS && plaintext_size != 0)
4263 memset(plaintext, 0, plaintext_size);
4265 exit:
4266 psa_aead_abort_internal(&operation);
4267 if (status == PSA_SUCCESS)
4268 *plaintext_length = ciphertext_length - operation.tag_length;
4269 return (status);
4274 /****************************************************************/
4275 /* Generators */
4276 /****************************************************************/
4278 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF) || \
4279 defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
4280 defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
4281 #define AT_LEAST_ONE_BUILTIN_KDF
4282 #endif
4284 #define HKDF_STATE_INIT 0 /* no input yet */
4285 #define HKDF_STATE_STARTED 1 /* got salt */
4286 #define HKDF_STATE_KEYED 2 /* got key */
4287 #define HKDF_STATE_OUTPUT 3 /* output started */
4289 static psa_algorithm_t psa_key_derivation_get_kdf_alg(
4290 const psa_key_derivation_operation_t *operation) {
4291 if (PSA_ALG_IS_KEY_AGREEMENT(operation->alg))
4292 return (PSA_ALG_KEY_AGREEMENT_GET_KDF(operation->alg));
4293 else
4294 return (operation->alg);
4297 psa_status_t psa_key_derivation_abort(psa_key_derivation_operation_t *operation) {
4298 psa_status_t status = PSA_SUCCESS;
4299 psa_algorithm_t kdf_alg = psa_key_derivation_get_kdf_alg(operation);
4300 if (kdf_alg == 0) {
4301 /* The object has (apparently) been initialized but it is not
4302 * in use. It's ok to call abort on such an object, and there's
4303 * nothing to do. */
4304 } else
4305 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF)
4306 if (PSA_ALG_IS_HKDF(kdf_alg)) {
4307 mbedtls_free(operation->ctx.hkdf.info);
4308 status = psa_hmac_abort_internal(&operation->ctx.hkdf.hmac);
4309 } else
4310 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF */
4311 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
4312 defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
4313 if (PSA_ALG_IS_TLS12_PRF(kdf_alg) ||
4314 /* TLS-1.2 PSK-to-MS KDF uses the same core as TLS-1.2 PRF */
4315 PSA_ALG_IS_TLS12_PSK_TO_MS(kdf_alg)) {
4316 if (operation->ctx.tls12_prf.seed != NULL) {
4317 mbedtls_platform_zeroize(operation->ctx.tls12_prf.seed,
4318 operation->ctx.tls12_prf.seed_length);
4319 mbedtls_free(operation->ctx.tls12_prf.seed);
4322 if (operation->ctx.tls12_prf.label != NULL) {
4323 mbedtls_platform_zeroize(operation->ctx.tls12_prf.label,
4324 operation->ctx.tls12_prf.label_length);
4325 mbedtls_free(operation->ctx.tls12_prf.label);
4328 status = psa_hmac_abort_internal(&operation->ctx.tls12_prf.hmac);
4330 /* We leave the fields Ai and output_block to be erased safely by the
4331 * mbedtls_platform_zeroize() in the end of this function. */
4332 } else
4333 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) ||
4334 * defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS) */
4336 status = PSA_ERROR_BAD_STATE;
4338 mbedtls_platform_zeroize(operation, sizeof(*operation));
4339 return (status);
4342 psa_status_t psa_key_derivation_get_capacity(const psa_key_derivation_operation_t *operation,
4343 size_t *capacity) {
4344 if (operation->alg == 0) {
4345 /* This is a blank key derivation operation. */
4346 return (PSA_ERROR_BAD_STATE);
4349 *capacity = operation->capacity;
4350 return (PSA_SUCCESS);
4353 psa_status_t psa_key_derivation_set_capacity(psa_key_derivation_operation_t *operation,
4354 size_t capacity) {
4355 if (operation->alg == 0)
4356 return (PSA_ERROR_BAD_STATE);
4357 if (capacity > operation->capacity)
4358 return (PSA_ERROR_INVALID_ARGUMENT);
4359 operation->capacity = capacity;
4360 return (PSA_SUCCESS);
4363 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF)
4364 /* Read some bytes from an HKDF-based operation. This performs a chunk
4365 * of the expand phase of the HKDF algorithm. */
4366 static psa_status_t psa_key_derivation_hkdf_read(psa_hkdf_key_derivation_t *hkdf,
4367 psa_algorithm_t hash_alg,
4368 uint8_t *output,
4369 size_t output_length) {
4370 uint8_t hash_length = PSA_HASH_LENGTH(hash_alg);
4371 psa_status_t status;
4373 if (hkdf->state < HKDF_STATE_KEYED || ! hkdf->info_set)
4374 return (PSA_ERROR_BAD_STATE);
4375 hkdf->state = HKDF_STATE_OUTPUT;
4377 while (output_length != 0) {
4378 /* Copy what remains of the current block */
4379 uint8_t n = hash_length - hkdf->offset_in_block;
4380 if (n > output_length)
4381 n = (uint8_t) output_length;
4382 memcpy(output, hkdf->output_block + hkdf->offset_in_block, n);
4383 output += n;
4384 output_length -= n;
4385 hkdf->offset_in_block += n;
4386 if (output_length == 0)
4387 break;
4388 /* We can't be wanting more output after block 0xff, otherwise
4389 * the capacity check in psa_key_derivation_output_bytes() would have
4390 * prevented this call. It could happen only if the operation
4391 * object was corrupted or if this function is called directly
4392 * inside the library. */
4393 if (hkdf->block_number == 0xff)
4394 return (PSA_ERROR_BAD_STATE);
4396 /* We need a new block */
4397 ++hkdf->block_number;
4398 hkdf->offset_in_block = 0;
4399 status = psa_hmac_setup_internal(&hkdf->hmac,
4400 hkdf->prk, hash_length,
4401 hash_alg);
4402 if (status != PSA_SUCCESS)
4403 return (status);
4404 if (hkdf->block_number != 1) {
4405 status = psa_hash_update(&hkdf->hmac.hash_ctx,
4406 hkdf->output_block,
4407 hash_length);
4408 if (status != PSA_SUCCESS)
4409 return (status);
4411 status = psa_hash_update(&hkdf->hmac.hash_ctx,
4412 hkdf->info,
4413 hkdf->info_length);
4414 if (status != PSA_SUCCESS)
4415 return (status);
4416 status = psa_hash_update(&hkdf->hmac.hash_ctx,
4417 &hkdf->block_number, 1);
4418 if (status != PSA_SUCCESS)
4419 return (status);
4420 status = psa_hmac_finish_internal(&hkdf->hmac,
4421 hkdf->output_block,
4422 sizeof(hkdf->output_block));
4423 if (status != PSA_SUCCESS)
4424 return (status);
4427 return (PSA_SUCCESS);
4429 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF */
4431 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
4432 defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
4433 static psa_status_t psa_key_derivation_tls12_prf_generate_next_block(
4434 psa_tls12_prf_key_derivation_t *tls12_prf,
4435 psa_algorithm_t alg) {
4436 psa_algorithm_t hash_alg = PSA_ALG_HKDF_GET_HASH(alg);
4437 uint8_t hash_length = PSA_HASH_LENGTH(hash_alg);
4438 psa_hash_operation_t backup = PSA_HASH_OPERATION_INIT;
4439 psa_status_t status, cleanup_status;
4441 /* We can't be wanting more output after block 0xff, otherwise
4442 * the capacity check in psa_key_derivation_output_bytes() would have
4443 * prevented this call. It could happen only if the operation
4444 * object was corrupted or if this function is called directly
4445 * inside the library. */
4446 if (tls12_prf->block_number == 0xff)
4447 return (PSA_ERROR_CORRUPTION_DETECTED);
4449 /* We need a new block */
4450 ++tls12_prf->block_number;
4451 tls12_prf->left_in_block = hash_length;
4453 /* Recall the definition of the TLS-1.2-PRF from RFC 5246:
4455 * PRF(secret, label, seed) = P_<hash>(secret, label + seed)
4457 * P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
4458 * HMAC_hash(secret, A(2) + seed) +
4459 * HMAC_hash(secret, A(3) + seed) + ...
4461 * A(0) = seed
4462 * A(i) = HMAC_hash(secret, A(i-1))
4464 * The `psa_tls12_prf_key_derivation` structure saves the block
4465 * `HMAC_hash(secret, A(i) + seed)` from which the output
4466 * is currently extracted as `output_block` and where i is
4467 * `block_number`.
4470 /* Save the hash context before using it, to preserve the hash state with
4471 * only the inner padding in it. We need this, because inner padding depends
4472 * on the key (secret in the RFC's terminology). */
4473 status = psa_hash_clone(&tls12_prf->hmac.hash_ctx, &backup);
4474 if (status != PSA_SUCCESS)
4475 goto cleanup;
4477 /* Calculate A(i) where i = tls12_prf->block_number. */
4478 if (tls12_prf->block_number == 1) {
4479 /* A(1) = HMAC_hash(secret, A(0)), where A(0) = seed. (The RFC overloads
4480 * the variable seed and in this instance means it in the context of the
4481 * P_hash function, where seed = label + seed.) */
4482 status = psa_hash_update(&tls12_prf->hmac.hash_ctx,
4483 tls12_prf->label, tls12_prf->label_length);
4484 if (status != PSA_SUCCESS)
4485 goto cleanup;
4486 status = psa_hash_update(&tls12_prf->hmac.hash_ctx,
4487 tls12_prf->seed, tls12_prf->seed_length);
4488 if (status != PSA_SUCCESS)
4489 goto cleanup;
4490 } else {
4491 /* A(i) = HMAC_hash(secret, A(i-1)) */
4492 status = psa_hash_update(&tls12_prf->hmac.hash_ctx,
4493 tls12_prf->Ai, hash_length);
4494 if (status != PSA_SUCCESS)
4495 goto cleanup;
4498 status = psa_hmac_finish_internal(&tls12_prf->hmac,
4499 tls12_prf->Ai, hash_length);
4500 if (status != PSA_SUCCESS)
4501 goto cleanup;
4502 status = psa_hash_clone(&backup, &tls12_prf->hmac.hash_ctx);
4503 if (status != PSA_SUCCESS)
4504 goto cleanup;
4506 /* Calculate HMAC_hash(secret, A(i) + label + seed). */
4507 status = psa_hash_update(&tls12_prf->hmac.hash_ctx,
4508 tls12_prf->Ai, hash_length);
4509 if (status != PSA_SUCCESS)
4510 goto cleanup;
4511 status = psa_hash_update(&tls12_prf->hmac.hash_ctx,
4512 tls12_prf->label, tls12_prf->label_length);
4513 if (status != PSA_SUCCESS)
4514 goto cleanup;
4515 status = psa_hash_update(&tls12_prf->hmac.hash_ctx,
4516 tls12_prf->seed, tls12_prf->seed_length);
4517 if (status != PSA_SUCCESS)
4518 goto cleanup;
4519 status = psa_hmac_finish_internal(&tls12_prf->hmac,
4520 tls12_prf->output_block, hash_length);
4521 if (status != PSA_SUCCESS)
4522 goto cleanup;
4523 status = psa_hash_clone(&backup, &tls12_prf->hmac.hash_ctx);
4524 if (status != PSA_SUCCESS)
4525 goto cleanup;
4528 cleanup:
4530 cleanup_status = psa_hash_abort(&backup);
4531 if (status == PSA_SUCCESS && cleanup_status != PSA_SUCCESS)
4532 status = cleanup_status;
4534 return (status);
4537 static psa_status_t psa_key_derivation_tls12_prf_read(
4538 psa_tls12_prf_key_derivation_t *tls12_prf,
4539 psa_algorithm_t alg,
4540 uint8_t *output,
4541 size_t output_length) {
4542 psa_algorithm_t hash_alg = PSA_ALG_TLS12_PRF_GET_HASH(alg);
4543 uint8_t hash_length = PSA_HASH_LENGTH(hash_alg);
4544 psa_status_t status;
4545 uint8_t offset, length;
4547 while (output_length != 0) {
4548 /* Check if we have fully processed the current block. */
4549 if (tls12_prf->left_in_block == 0) {
4550 status = psa_key_derivation_tls12_prf_generate_next_block(tls12_prf,
4551 alg);
4552 if (status != PSA_SUCCESS)
4553 return (status);
4555 continue;
4558 if (tls12_prf->left_in_block > output_length)
4559 length = (uint8_t) output_length;
4560 else
4561 length = tls12_prf->left_in_block;
4563 offset = hash_length - tls12_prf->left_in_block;
4564 memcpy(output, tls12_prf->output_block + offset, length);
4565 output += length;
4566 output_length -= length;
4567 tls12_prf->left_in_block -= length;
4570 return (PSA_SUCCESS);
4572 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF ||
4573 * MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
4575 psa_status_t psa_key_derivation_output_bytes(
4576 psa_key_derivation_operation_t *operation,
4577 uint8_t *output,
4578 size_t output_length) {
4579 psa_status_t status;
4580 psa_algorithm_t kdf_alg = psa_key_derivation_get_kdf_alg(operation);
4582 if (operation->alg == 0) {
4583 /* This is a blank operation. */
4584 return (PSA_ERROR_BAD_STATE);
4587 if (output_length > operation->capacity) {
4588 operation->capacity = 0;
4589 /* Go through the error path to wipe all confidential data now
4590 * that the operation object is useless. */
4591 status = PSA_ERROR_INSUFFICIENT_DATA;
4592 goto exit;
4594 if (output_length == 0 && operation->capacity == 0) {
4595 /* Edge case: this is a finished operation, and 0 bytes
4596 * were requested. The right error in this case could
4597 * be either INSUFFICIENT_CAPACITY or BAD_STATE. Return
4598 * INSUFFICIENT_CAPACITY, which is right for a finished
4599 * operation, for consistency with the case when
4600 * output_length > 0. */
4601 return (PSA_ERROR_INSUFFICIENT_DATA);
4603 operation->capacity -= output_length;
4605 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF)
4606 if (PSA_ALG_IS_HKDF(kdf_alg)) {
4607 psa_algorithm_t hash_alg = PSA_ALG_HKDF_GET_HASH(kdf_alg);
4608 status = psa_key_derivation_hkdf_read(&operation->ctx.hkdf, hash_alg,
4609 output, output_length);
4610 } else
4611 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF */
4612 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
4613 defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
4614 if (PSA_ALG_IS_TLS12_PRF(kdf_alg) ||
4615 PSA_ALG_IS_TLS12_PSK_TO_MS(kdf_alg)) {
4616 status = psa_key_derivation_tls12_prf_read(&operation->ctx.tls12_prf,
4617 kdf_alg, output,
4618 output_length);
4619 } else
4620 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF ||
4621 * MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
4623 (void) kdf_alg;
4624 return (PSA_ERROR_BAD_STATE);
4627 exit:
4628 if (status != PSA_SUCCESS) {
4629 /* Preserve the algorithm upon errors, but clear all sensitive state.
4630 * This allows us to differentiate between exhausted operations and
4631 * blank operations, so we can return PSA_ERROR_BAD_STATE on blank
4632 * operations. */
4633 psa_algorithm_t alg = operation->alg;
4634 psa_key_derivation_abort(operation);
4635 operation->alg = alg;
4636 memset(output, '!', output_length);
4638 return (status);
4641 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES)
4642 static void psa_des_set_key_parity(uint8_t *data, size_t data_size) {
4643 if (data_size >= 8)
4644 mbedtls_des_key_set_parity(data);
4645 if (data_size >= 16)
4646 mbedtls_des_key_set_parity(data + 8);
4647 if (data_size >= 24)
4648 mbedtls_des_key_set_parity(data + 16);
4650 #endif /* MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES */
4652 static psa_status_t psa_generate_derived_key_internal(
4653 psa_key_slot_t *slot,
4654 size_t bits,
4655 psa_key_derivation_operation_t *operation) {
4656 uint8_t *data = NULL;
4657 size_t bytes = PSA_BITS_TO_BYTES(bits);
4658 psa_status_t status;
4660 if (! key_type_is_raw_bytes(slot->attr.type))
4661 return (PSA_ERROR_INVALID_ARGUMENT);
4662 if (bits % 8 != 0)
4663 return (PSA_ERROR_INVALID_ARGUMENT);
4664 data = mbedtls_calloc(1, bytes);
4665 if (data == NULL)
4666 return (PSA_ERROR_INSUFFICIENT_MEMORY);
4668 status = psa_key_derivation_output_bytes(operation, data, bytes);
4669 if (status != PSA_SUCCESS)
4670 goto exit;
4671 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES)
4672 if (slot->attr.type == PSA_KEY_TYPE_DES)
4673 psa_des_set_key_parity(data, bytes);
4674 #endif /* MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES */
4676 status = psa_allocate_buffer_to_slot(slot, bytes);
4677 if (status != PSA_SUCCESS)
4678 goto exit;
4680 slot->attr.bits = (psa_key_bits_t) bits;
4681 psa_key_attributes_t attributes = {
4682 .core = slot->attr
4685 status = psa_driver_wrapper_import_key(&attributes,
4686 data, bytes,
4687 slot->key.data,
4688 slot->key.bytes,
4689 &slot->key.bytes, &bits);
4690 if (bits != slot->attr.bits)
4691 status = PSA_ERROR_INVALID_ARGUMENT;
4693 exit:
4694 mbedtls_free(data);
4695 return (status);
4698 psa_status_t psa_key_derivation_output_key(const psa_key_attributes_t *attributes,
4699 psa_key_derivation_operation_t *operation,
4700 mbedtls_svc_key_id_t *key) {
4701 psa_status_t status;
4702 psa_key_slot_t *slot = NULL;
4703 psa_se_drv_table_entry_t *driver = NULL;
4705 *key = MBEDTLS_SVC_KEY_ID_INIT;
4707 /* Reject any attempt to create a zero-length key so that we don't
4708 * risk tripping up later, e.g. on a malloc(0) that returns NULL. */
4709 if (psa_get_key_bits(attributes) == 0)
4710 return (PSA_ERROR_INVALID_ARGUMENT);
4712 if (! operation->can_output_key)
4713 return (PSA_ERROR_NOT_PERMITTED);
4715 status = psa_start_key_creation(PSA_KEY_CREATION_DERIVE, attributes,
4716 &slot, &driver);
4717 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
4718 if (driver != NULL) {
4719 /* Deriving a key in a secure element is not implemented yet. */
4720 status = PSA_ERROR_NOT_SUPPORTED;
4722 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
4723 if (status == PSA_SUCCESS) {
4724 status = psa_generate_derived_key_internal(slot,
4725 attributes->core.bits,
4726 operation);
4728 if (status == PSA_SUCCESS)
4729 status = psa_finish_key_creation(slot, driver, key);
4730 if (status != PSA_SUCCESS)
4731 psa_fail_key_creation(slot, driver);
4733 return (status);
4738 /****************************************************************/
4739 /* Key derivation */
4740 /****************************************************************/
4742 #if defined(AT_LEAST_ONE_BUILTIN_KDF)
4743 static psa_status_t psa_key_derivation_setup_kdf(
4744 psa_key_derivation_operation_t *operation,
4745 psa_algorithm_t kdf_alg) {
4746 int is_kdf_alg_supported;
4748 /* Make sure that operation->ctx is properly zero-initialised. (Macro
4749 * initialisers for this union leave some bytes unspecified.) */
4750 memset(&operation->ctx, 0, sizeof(operation->ctx));
4752 /* Make sure that kdf_alg is a supported key derivation algorithm. */
4753 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF)
4754 if (PSA_ALG_IS_HKDF(kdf_alg))
4755 is_kdf_alg_supported = 1;
4756 else
4757 #endif
4758 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF)
4759 if (PSA_ALG_IS_TLS12_PRF(kdf_alg))
4760 is_kdf_alg_supported = 1;
4761 else
4762 #endif
4763 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
4764 if (PSA_ALG_IS_TLS12_PSK_TO_MS(kdf_alg))
4765 is_kdf_alg_supported = 1;
4766 else
4767 #endif
4768 is_kdf_alg_supported = 0;
4770 if (is_kdf_alg_supported) {
4771 psa_algorithm_t hash_alg = PSA_ALG_HKDF_GET_HASH(kdf_alg);
4772 size_t hash_size = PSA_HASH_LENGTH(hash_alg);
4773 if (hash_size == 0)
4774 return (PSA_ERROR_NOT_SUPPORTED);
4775 if ((PSA_ALG_IS_TLS12_PRF(kdf_alg) ||
4776 PSA_ALG_IS_TLS12_PSK_TO_MS(kdf_alg)) &&
4777 !(hash_alg == PSA_ALG_SHA_256 || hash_alg == PSA_ALG_SHA_384)) {
4778 return (PSA_ERROR_NOT_SUPPORTED);
4780 operation->capacity = 255 * hash_size;
4781 return (PSA_SUCCESS);
4784 return (PSA_ERROR_NOT_SUPPORTED);
4786 #endif /* AT_LEAST_ONE_BUILTIN_KDF */
4788 psa_status_t psa_key_derivation_setup(psa_key_derivation_operation_t *operation,
4789 psa_algorithm_t alg) {
4790 psa_status_t status;
4792 if (operation->alg != 0)
4793 return (PSA_ERROR_BAD_STATE);
4795 if (PSA_ALG_IS_RAW_KEY_AGREEMENT(alg))
4796 return (PSA_ERROR_INVALID_ARGUMENT);
4797 else if (PSA_ALG_IS_KEY_AGREEMENT(alg)) {
4798 #if defined(AT_LEAST_ONE_BUILTIN_KDF)
4799 psa_algorithm_t kdf_alg = PSA_ALG_KEY_AGREEMENT_GET_KDF(alg);
4800 status = psa_key_derivation_setup_kdf(operation, kdf_alg);
4801 #else
4802 return (PSA_ERROR_NOT_SUPPORTED);
4803 #endif /* AT_LEAST_ONE_BUILTIN_KDF */
4804 } else if (PSA_ALG_IS_KEY_DERIVATION(alg)) {
4805 #if defined(AT_LEAST_ONE_BUILTIN_KDF)
4806 status = psa_key_derivation_setup_kdf(operation, alg);
4807 #else
4808 return (PSA_ERROR_NOT_SUPPORTED);
4809 #endif /* AT_LEAST_ONE_BUILTIN_KDF */
4810 } else
4811 return (PSA_ERROR_INVALID_ARGUMENT);
4813 if (status == PSA_SUCCESS)
4814 operation->alg = alg;
4815 return (status);
4818 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF)
4819 static psa_status_t psa_hkdf_input(psa_hkdf_key_derivation_t *hkdf,
4820 psa_algorithm_t hash_alg,
4821 psa_key_derivation_step_t step,
4822 const uint8_t *data,
4823 size_t data_length) {
4824 psa_status_t status;
4825 switch (step) {
4826 case PSA_KEY_DERIVATION_INPUT_SALT:
4827 if (hkdf->state != HKDF_STATE_INIT)
4828 return (PSA_ERROR_BAD_STATE);
4829 status = psa_hmac_setup_internal(&hkdf->hmac,
4830 data, data_length,
4831 hash_alg);
4832 if (status != PSA_SUCCESS)
4833 return (status);
4834 hkdf->state = HKDF_STATE_STARTED;
4835 return (PSA_SUCCESS);
4836 case PSA_KEY_DERIVATION_INPUT_SECRET:
4837 /* If no salt was provided, use an empty salt. */
4838 if (hkdf->state == HKDF_STATE_INIT) {
4839 status = psa_hmac_setup_internal(&hkdf->hmac,
4840 NULL, 0,
4841 hash_alg);
4842 if (status != PSA_SUCCESS)
4843 return (status);
4844 hkdf->state = HKDF_STATE_STARTED;
4846 if (hkdf->state != HKDF_STATE_STARTED)
4847 return (PSA_ERROR_BAD_STATE);
4848 status = psa_hash_update(&hkdf->hmac.hash_ctx,
4849 data, data_length);
4850 if (status != PSA_SUCCESS)
4851 return (status);
4852 status = psa_hmac_finish_internal(&hkdf->hmac,
4853 hkdf->prk,
4854 sizeof(hkdf->prk));
4855 if (status != PSA_SUCCESS)
4856 return (status);
4857 hkdf->offset_in_block = PSA_HASH_LENGTH(hash_alg);
4858 hkdf->block_number = 0;
4859 hkdf->state = HKDF_STATE_KEYED;
4860 return (PSA_SUCCESS);
4861 case PSA_KEY_DERIVATION_INPUT_INFO:
4862 if (hkdf->state == HKDF_STATE_OUTPUT)
4863 return (PSA_ERROR_BAD_STATE);
4864 if (hkdf->info_set)
4865 return (PSA_ERROR_BAD_STATE);
4866 hkdf->info_length = data_length;
4867 if (data_length != 0) {
4868 hkdf->info = mbedtls_calloc(1, data_length);
4869 if (hkdf->info == NULL)
4870 return (PSA_ERROR_INSUFFICIENT_MEMORY);
4871 memcpy(hkdf->info, data, data_length);
4873 hkdf->info_set = 1;
4874 return (PSA_SUCCESS);
4875 default:
4876 return (PSA_ERROR_INVALID_ARGUMENT);
4879 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF */
4881 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
4882 defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
4883 static psa_status_t psa_tls12_prf_set_seed(psa_tls12_prf_key_derivation_t *prf,
4884 const uint8_t *data,
4885 size_t data_length) {
4886 if (prf->state != PSA_TLS12_PRF_STATE_INIT)
4887 return (PSA_ERROR_BAD_STATE);
4889 if (data_length != 0) {
4890 prf->seed = mbedtls_calloc(1, data_length);
4891 if (prf->seed == NULL)
4892 return (PSA_ERROR_INSUFFICIENT_MEMORY);
4894 memcpy(prf->seed, data, data_length);
4895 prf->seed_length = data_length;
4898 prf->state = PSA_TLS12_PRF_STATE_SEED_SET;
4900 return (PSA_SUCCESS);
4903 static psa_status_t psa_tls12_prf_set_key(psa_tls12_prf_key_derivation_t *prf,
4904 psa_algorithm_t hash_alg,
4905 const uint8_t *data,
4906 size_t data_length) {
4907 psa_status_t status;
4908 if (prf->state != PSA_TLS12_PRF_STATE_SEED_SET)
4909 return (PSA_ERROR_BAD_STATE);
4911 status = psa_hmac_setup_internal(&prf->hmac, data, data_length, hash_alg);
4912 if (status != PSA_SUCCESS)
4913 return (status);
4915 prf->state = PSA_TLS12_PRF_STATE_KEY_SET;
4917 return (PSA_SUCCESS);
4920 static psa_status_t psa_tls12_prf_set_label(psa_tls12_prf_key_derivation_t *prf,
4921 const uint8_t *data,
4922 size_t data_length) {
4923 if (prf->state != PSA_TLS12_PRF_STATE_KEY_SET)
4924 return (PSA_ERROR_BAD_STATE);
4926 if (data_length != 0) {
4927 prf->label = mbedtls_calloc(1, data_length);
4928 if (prf->label == NULL)
4929 return (PSA_ERROR_INSUFFICIENT_MEMORY);
4931 memcpy(prf->label, data, data_length);
4932 prf->label_length = data_length;
4935 prf->state = PSA_TLS12_PRF_STATE_LABEL_SET;
4937 return (PSA_SUCCESS);
4940 static psa_status_t psa_tls12_prf_input(psa_tls12_prf_key_derivation_t *prf,
4941 psa_algorithm_t hash_alg,
4942 psa_key_derivation_step_t step,
4943 const uint8_t *data,
4944 size_t data_length) {
4945 switch (step) {
4946 case PSA_KEY_DERIVATION_INPUT_SEED:
4947 return (psa_tls12_prf_set_seed(prf, data, data_length));
4948 case PSA_KEY_DERIVATION_INPUT_SECRET:
4949 return (psa_tls12_prf_set_key(prf, hash_alg, data, data_length));
4950 case PSA_KEY_DERIVATION_INPUT_LABEL:
4951 return (psa_tls12_prf_set_label(prf, data, data_length));
4952 default:
4953 return (PSA_ERROR_INVALID_ARGUMENT);
4956 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) ||
4957 * MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
4959 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
4960 static psa_status_t psa_tls12_prf_psk_to_ms_set_key(
4961 psa_tls12_prf_key_derivation_t *prf,
4962 psa_algorithm_t hash_alg,
4963 const uint8_t *data,
4964 size_t data_length) {
4965 psa_status_t status;
4966 uint8_t pms[ 4 + 2 * PSA_TLS12_PSK_TO_MS_PSK_MAX_SIZE ];
4967 uint8_t *cur = pms;
4969 if (data_length > PSA_TLS12_PSK_TO_MS_PSK_MAX_SIZE)
4970 return (PSA_ERROR_INVALID_ARGUMENT);
4972 /* Quoting RFC 4279, Section 2:
4974 * The premaster secret is formed as follows: if the PSK is N octets
4975 * long, concatenate a uint16 with the value N, N zero octets, a second
4976 * uint16 with the value N, and the PSK itself.
4979 *cur++ = (data_length >> 8) & 0xff;
4980 *cur++ = (data_length >> 0) & 0xff;
4981 memset(cur, 0, data_length);
4982 cur += data_length;
4983 *cur++ = pms[0];
4984 *cur++ = pms[1];
4985 memcpy(cur, data, data_length);
4986 cur += data_length;
4988 status = psa_tls12_prf_set_key(prf, hash_alg, pms, cur - pms);
4990 mbedtls_platform_zeroize(pms, sizeof(pms));
4991 return (status);
4994 static psa_status_t psa_tls12_prf_psk_to_ms_input(
4995 psa_tls12_prf_key_derivation_t *prf,
4996 psa_algorithm_t hash_alg,
4997 psa_key_derivation_step_t step,
4998 const uint8_t *data,
4999 size_t data_length) {
5000 if (step == PSA_KEY_DERIVATION_INPUT_SECRET) {
5001 return (psa_tls12_prf_psk_to_ms_set_key(prf, hash_alg,
5002 data, data_length));
5005 return (psa_tls12_prf_input(prf, hash_alg, step, data, data_length));
5007 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
5009 /** Check whether the given key type is acceptable for the given
5010 * input step of a key derivation.
5012 * Secret inputs must have the type #PSA_KEY_TYPE_DERIVE.
5013 * Non-secret inputs must have the type #PSA_KEY_TYPE_RAW_DATA.
5014 * Both secret and non-secret inputs can alternatively have the type
5015 * #PSA_KEY_TYPE_NONE, which is never the type of a key object, meaning
5016 * that the input was passed as a buffer rather than via a key object.
5018 static int psa_key_derivation_check_input_type(
5019 psa_key_derivation_step_t step,
5020 psa_key_type_t key_type) {
5021 switch (step) {
5022 case PSA_KEY_DERIVATION_INPUT_SECRET:
5023 if (key_type == PSA_KEY_TYPE_DERIVE)
5024 return (PSA_SUCCESS);
5025 if (key_type == PSA_KEY_TYPE_NONE)
5026 return (PSA_SUCCESS);
5027 break;
5028 case PSA_KEY_DERIVATION_INPUT_LABEL:
5029 case PSA_KEY_DERIVATION_INPUT_SALT:
5030 case PSA_KEY_DERIVATION_INPUT_INFO:
5031 case PSA_KEY_DERIVATION_INPUT_SEED:
5032 if (key_type == PSA_KEY_TYPE_RAW_DATA)
5033 return (PSA_SUCCESS);
5034 if (key_type == PSA_KEY_TYPE_NONE)
5035 return (PSA_SUCCESS);
5036 break;
5038 return (PSA_ERROR_INVALID_ARGUMENT);
5041 static psa_status_t psa_key_derivation_input_internal(
5042 psa_key_derivation_operation_t *operation,
5043 psa_key_derivation_step_t step,
5044 psa_key_type_t key_type,
5045 const uint8_t *data,
5046 size_t data_length) {
5047 psa_status_t status;
5048 psa_algorithm_t kdf_alg = psa_key_derivation_get_kdf_alg(operation);
5050 status = psa_key_derivation_check_input_type(step, key_type);
5051 if (status != PSA_SUCCESS)
5052 goto exit;
5054 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF)
5055 if (PSA_ALG_IS_HKDF(kdf_alg)) {
5056 status = psa_hkdf_input(&operation->ctx.hkdf,
5057 PSA_ALG_HKDF_GET_HASH(kdf_alg),
5058 step, data, data_length);
5059 } else
5060 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF */
5061 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF)
5062 if (PSA_ALG_IS_TLS12_PRF(kdf_alg)) {
5063 status = psa_tls12_prf_input(&operation->ctx.tls12_prf,
5064 PSA_ALG_HKDF_GET_HASH(kdf_alg),
5065 step, data, data_length);
5066 } else
5067 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF */
5068 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
5069 if (PSA_ALG_IS_TLS12_PSK_TO_MS(kdf_alg)) {
5070 status = psa_tls12_prf_psk_to_ms_input(&operation->ctx.tls12_prf,
5071 PSA_ALG_HKDF_GET_HASH(kdf_alg),
5072 step, data, data_length);
5073 } else
5074 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
5076 /* This can't happen unless the operation object was not initialized */
5077 (void) data;
5078 (void) data_length;
5079 (void) kdf_alg;
5080 return (PSA_ERROR_BAD_STATE);
5083 exit:
5084 if (status != PSA_SUCCESS)
5085 psa_key_derivation_abort(operation);
5086 return (status);
5089 psa_status_t psa_key_derivation_input_bytes(
5090 psa_key_derivation_operation_t *operation,
5091 psa_key_derivation_step_t step,
5092 const uint8_t *data,
5093 size_t data_length) {
5094 return (psa_key_derivation_input_internal(operation, step,
5095 PSA_KEY_TYPE_NONE,
5096 data, data_length));
5099 psa_status_t psa_key_derivation_input_key(
5100 psa_key_derivation_operation_t *operation,
5101 psa_key_derivation_step_t step,
5102 mbedtls_svc_key_id_t key) {
5103 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
5104 psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
5105 psa_key_slot_t *slot;
5107 status = psa_get_and_lock_transparent_key_slot_with_policy(
5108 key, &slot, PSA_KEY_USAGE_DERIVE, operation->alg);
5109 if (status != PSA_SUCCESS) {
5110 psa_key_derivation_abort(operation);
5111 return (status);
5114 /* Passing a key object as a SECRET input unlocks the permission
5115 * to output to a key object. */
5116 if (step == PSA_KEY_DERIVATION_INPUT_SECRET)
5117 operation->can_output_key = 1;
5119 status = psa_key_derivation_input_internal(operation,
5120 step, slot->attr.type,
5121 slot->key.data,
5122 slot->key.bytes);
5124 unlock_status = psa_unlock_key_slot(slot);
5126 return ((status == PSA_SUCCESS) ? unlock_status : status);
5131 /****************************************************************/
5132 /* Key agreement */
5133 /****************************************************************/
5135 #if defined(MBEDTLS_PSA_BUILTIN_ALG_ECDH)
5136 static psa_status_t psa_key_agreement_ecdh(const uint8_t *peer_key,
5137 size_t peer_key_length,
5138 const mbedtls_ecp_keypair *our_key,
5139 uint8_t *shared_secret,
5140 size_t shared_secret_size,
5141 size_t *shared_secret_length) {
5142 mbedtls_ecp_keypair *their_key = NULL;
5143 mbedtls_ecdh_context ecdh;
5144 psa_status_t status;
5145 size_t bits = 0;
5146 psa_ecc_family_t curve = mbedtls_ecc_group_to_psa(our_key->grp.id, &bits);
5147 mbedtls_ecdh_init(&ecdh);
5149 status = mbedtls_psa_ecp_load_representation(
5150 PSA_KEY_TYPE_ECC_PUBLIC_KEY(curve),
5151 bits,
5152 peer_key,
5153 peer_key_length,
5154 &their_key);
5155 if (status != PSA_SUCCESS)
5156 goto exit;
5158 status = mbedtls_to_psa_error(
5159 mbedtls_ecdh_get_params(&ecdh, their_key, MBEDTLS_ECDH_THEIRS));
5160 if (status != PSA_SUCCESS)
5161 goto exit;
5162 status = mbedtls_to_psa_error(
5163 mbedtls_ecdh_get_params(&ecdh, our_key, MBEDTLS_ECDH_OURS));
5164 if (status != PSA_SUCCESS)
5165 goto exit;
5167 status = mbedtls_to_psa_error(
5168 mbedtls_ecdh_calc_secret(&ecdh,
5169 shared_secret_length,
5170 shared_secret, shared_secret_size,
5171 mbedtls_psa_get_random,
5172 MBEDTLS_PSA_RANDOM_STATE));
5173 if (status != PSA_SUCCESS)
5174 goto exit;
5175 if (PSA_BITS_TO_BYTES(bits) != *shared_secret_length)
5176 status = PSA_ERROR_CORRUPTION_DETECTED;
5178 exit:
5179 if (status != PSA_SUCCESS)
5180 mbedtls_platform_zeroize(shared_secret, shared_secret_size);
5181 mbedtls_ecdh_free(&ecdh);
5182 mbedtls_ecp_keypair_free(their_key);
5183 mbedtls_free(their_key);
5185 return (status);
5187 #endif /* MBEDTLS_PSA_BUILTIN_ALG_ECDH */
5189 #define PSA_KEY_AGREEMENT_MAX_SHARED_SECRET_SIZE MBEDTLS_ECP_MAX_BYTES
5191 static psa_status_t psa_key_agreement_raw_internal(psa_algorithm_t alg,
5192 psa_key_slot_t *private_key,
5193 const uint8_t *peer_key,
5194 size_t peer_key_length,
5195 uint8_t *shared_secret,
5196 size_t shared_secret_size,
5197 size_t *shared_secret_length) {
5198 switch (alg) {
5199 #if defined(MBEDTLS_PSA_BUILTIN_ALG_ECDH)
5200 case PSA_ALG_ECDH:
5201 if (! PSA_KEY_TYPE_IS_ECC_KEY_PAIR(private_key->attr.type))
5202 return (PSA_ERROR_INVALID_ARGUMENT);
5203 mbedtls_ecp_keypair *ecp = NULL;
5204 psa_status_t status = mbedtls_psa_ecp_load_representation(
5205 private_key->attr.type,
5206 private_key->attr.bits,
5207 private_key->key.data,
5208 private_key->key.bytes,
5209 &ecp);
5210 if (status != PSA_SUCCESS)
5211 return (status);
5212 status = psa_key_agreement_ecdh(peer_key, peer_key_length,
5213 ecp,
5214 shared_secret, shared_secret_size,
5215 shared_secret_length);
5216 mbedtls_ecp_keypair_free(ecp);
5217 mbedtls_free(ecp);
5218 return (status);
5219 #endif /* MBEDTLS_PSA_BUILTIN_ALG_ECDH */
5220 default:
5221 (void) private_key;
5222 (void) peer_key;
5223 (void) peer_key_length;
5224 (void) shared_secret;
5225 (void) shared_secret_size;
5226 (void) shared_secret_length;
5227 return (PSA_ERROR_NOT_SUPPORTED);
5231 /* Note that if this function fails, you must call psa_key_derivation_abort()
5232 * to potentially free embedded data structures and wipe confidential data.
5234 static psa_status_t psa_key_agreement_internal(psa_key_derivation_operation_t *operation,
5235 psa_key_derivation_step_t step,
5236 psa_key_slot_t *private_key,
5237 const uint8_t *peer_key,
5238 size_t peer_key_length) {
5239 psa_status_t status;
5240 uint8_t shared_secret[PSA_KEY_AGREEMENT_MAX_SHARED_SECRET_SIZE];
5241 size_t shared_secret_length = 0;
5242 psa_algorithm_t ka_alg = PSA_ALG_KEY_AGREEMENT_GET_BASE(operation->alg);
5244 /* Step 1: run the secret agreement algorithm to generate the shared
5245 * secret. */
5246 status = psa_key_agreement_raw_internal(ka_alg,
5247 private_key,
5248 peer_key, peer_key_length,
5249 shared_secret,
5250 sizeof(shared_secret),
5251 &shared_secret_length);
5252 if (status != PSA_SUCCESS)
5253 goto exit;
5255 /* Step 2: set up the key derivation to generate key material from
5256 * the shared secret. A shared secret is permitted wherever a key
5257 * of type DERIVE is permitted. */
5258 status = psa_key_derivation_input_internal(operation, step,
5259 PSA_KEY_TYPE_DERIVE,
5260 shared_secret,
5261 shared_secret_length);
5262 exit:
5263 mbedtls_platform_zeroize(shared_secret, shared_secret_length);
5264 return (status);
5267 psa_status_t psa_key_derivation_key_agreement(psa_key_derivation_operation_t *operation,
5268 psa_key_derivation_step_t step,
5269 mbedtls_svc_key_id_t private_key,
5270 const uint8_t *peer_key,
5271 size_t peer_key_length) {
5272 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
5273 psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
5274 psa_key_slot_t *slot;
5276 if (! PSA_ALG_IS_KEY_AGREEMENT(operation->alg))
5277 return (PSA_ERROR_INVALID_ARGUMENT);
5278 status = psa_get_and_lock_transparent_key_slot_with_policy(
5279 private_key, &slot, PSA_KEY_USAGE_DERIVE, operation->alg);
5280 if (status != PSA_SUCCESS)
5281 return (status);
5282 status = psa_key_agreement_internal(operation, step,
5283 slot,
5284 peer_key, peer_key_length);
5285 if (status != PSA_SUCCESS)
5286 psa_key_derivation_abort(operation);
5287 else {
5288 /* If a private key has been added as SECRET, we allow the derived
5289 * key material to be used as a key in PSA Crypto. */
5290 if (step == PSA_KEY_DERIVATION_INPUT_SECRET)
5291 operation->can_output_key = 1;
5294 unlock_status = psa_unlock_key_slot(slot);
5296 return ((status == PSA_SUCCESS) ? unlock_status : status);
5299 psa_status_t psa_raw_key_agreement(psa_algorithm_t alg,
5300 mbedtls_svc_key_id_t private_key,
5301 const uint8_t *peer_key,
5302 size_t peer_key_length,
5303 uint8_t *output,
5304 size_t output_size,
5305 size_t *output_length) {
5306 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
5307 psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
5308 psa_key_slot_t *slot = NULL;
5310 if (! PSA_ALG_IS_KEY_AGREEMENT(alg)) {
5311 status = PSA_ERROR_INVALID_ARGUMENT;
5312 goto exit;
5314 status = psa_get_and_lock_transparent_key_slot_with_policy(
5315 private_key, &slot, PSA_KEY_USAGE_DERIVE, alg);
5316 if (status != PSA_SUCCESS)
5317 goto exit;
5319 status = psa_key_agreement_raw_internal(alg, slot,
5320 peer_key, peer_key_length,
5321 output, output_size,
5322 output_length);
5324 exit:
5325 if (status != PSA_SUCCESS) {
5326 /* If an error happens and is not handled properly, the output
5327 * may be used as a key to protect sensitive data. Arrange for such
5328 * a key to be random, which is likely to result in decryption or
5329 * verification errors. This is better than filling the buffer with
5330 * some constant data such as zeros, which would result in the data
5331 * being protected with a reproducible, easily knowable key.
5333 psa_generate_random(output, output_size);
5334 *output_length = output_size;
5337 unlock_status = psa_unlock_key_slot(slot);
5339 return ((status == PSA_SUCCESS) ? unlock_status : status);
5344 /****************************************************************/
5345 /* Random generation */
5346 /****************************************************************/
5348 /** Initialize the PSA random generator.
5350 static void mbedtls_psa_random_init(mbedtls_psa_random_context_t *rng) {
5351 #if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
5352 memset(rng, 0, sizeof(*rng));
5353 #else /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
5355 /* Set default configuration if
5356 * mbedtls_psa_crypto_configure_entropy_sources() hasn't been called. */
5357 if (rng->entropy_init == NULL)
5358 rng->entropy_init = mbedtls_entropy_init;
5359 if (rng->entropy_free == NULL)
5360 rng->entropy_free = mbedtls_entropy_free;
5362 rng->entropy_init(&rng->entropy);
5363 #if defined(MBEDTLS_PSA_INJECT_ENTROPY) && \
5364 defined(MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES)
5365 /* The PSA entropy injection feature depends on using NV seed as an entropy
5366 * source. Add NV seed as an entropy source for PSA entropy injection. */
5367 mbedtls_entropy_add_source(&rng->entropy,
5368 mbedtls_nv_seed_poll, NULL,
5369 MBEDTLS_ENTROPY_BLOCK_SIZE,
5370 MBEDTLS_ENTROPY_SOURCE_STRONG);
5371 #endif
5373 mbedtls_psa_drbg_init(MBEDTLS_PSA_RANDOM_STATE);
5374 #endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
5377 /** Deinitialize the PSA random generator.
5379 static void mbedtls_psa_random_free(mbedtls_psa_random_context_t *rng) {
5380 #if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
5381 memset(rng, 0, sizeof(*rng));
5382 #else /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
5383 mbedtls_psa_drbg_free(MBEDTLS_PSA_RANDOM_STATE);
5384 rng->entropy_free(&rng->entropy);
5385 #endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
5388 /** Seed the PSA random generator.
5390 static psa_status_t mbedtls_psa_random_seed(mbedtls_psa_random_context_t *rng) {
5391 #if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
5392 /* Do nothing: the external RNG seeds itself. */
5393 (void) rng;
5394 return (PSA_SUCCESS);
5395 #else /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
5396 const unsigned char drbg_seed[] = "PSA";
5397 int ret = mbedtls_psa_drbg_seed(&rng->entropy,
5398 drbg_seed, sizeof(drbg_seed) - 1);
5399 return mbedtls_to_psa_error(ret);
5400 #endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
5403 psa_status_t psa_generate_random(uint8_t *output,
5404 size_t output_size) {
5405 GUARD_MODULE_INITIALIZED;
5407 #if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
5409 size_t output_length = 0;
5410 psa_status_t status = mbedtls_psa_external_get_random(&global_data.rng,
5411 output, output_size,
5412 &output_length);
5413 if (status != PSA_SUCCESS)
5414 return (status);
5415 /* Breaking up a request into smaller chunks is currently not supported
5416 * for the extrernal RNG interface. */
5417 if (output_length != output_size)
5418 return (PSA_ERROR_INSUFFICIENT_ENTROPY);
5419 return (PSA_SUCCESS);
5421 #else /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
5423 while (output_size > 0) {
5424 size_t request_size =
5425 (output_size > MBEDTLS_PSA_RANDOM_MAX_REQUEST ?
5426 MBEDTLS_PSA_RANDOM_MAX_REQUEST :
5427 output_size);
5428 int ret = mbedtls_psa_get_random(MBEDTLS_PSA_RANDOM_STATE,
5429 output, request_size);
5430 if (ret != 0)
5431 return (mbedtls_to_psa_error(ret));
5432 output_size -= request_size;
5433 output += request_size;
5435 return (PSA_SUCCESS);
5436 #endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
5439 /* Wrapper function allowing the classic API to use the PSA RNG.
5441 * `mbedtls_psa_get_random(MBEDTLS_PSA_RANDOM_STATE, ...)` calls
5442 * `psa_generate_random(...)`. The state parameter is ignored since the
5443 * PSA API doesn't support passing an explicit state.
5445 * In the non-external case, psa_generate_random() calls an
5446 * `mbedtls_xxx_drbg_random` function which has exactly the same signature
5447 * and semantics as mbedtls_psa_get_random(). As an optimization,
5448 * instead of doing this back-and-forth between the PSA API and the
5449 * classic API, psa_crypto_random_impl.h defines `mbedtls_psa_get_random`
5450 * as a constant function pointer to `mbedtls_xxx_drbg_random`.
5452 #if defined (MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
5453 int mbedtls_psa_get_random(void *p_rng,
5454 unsigned char *output,
5455 size_t output_size) {
5456 /* This function takes a pointer to the RNG state because that's what
5457 * classic mbedtls functions using an RNG expect. The PSA RNG manages
5458 * its own state internally and doesn't let the caller access that state.
5459 * So we just ignore the state parameter, and in practice we'll pass
5460 * NULL. */
5461 (void) p_rng;
5462 psa_status_t status = psa_generate_random(output, output_size);
5463 if (status == PSA_SUCCESS)
5464 return (0);
5465 else
5466 return (MBEDTLS_ERR_ENTROPY_SOURCE_FAILED);
5468 #endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
5470 #if defined(MBEDTLS_PSA_INJECT_ENTROPY)
5471 #include "mbedtls/entropy_poll.h"
5473 psa_status_t mbedtls_psa_inject_entropy(const uint8_t *seed,
5474 size_t seed_size) {
5475 if (global_data.initialized)
5476 return (PSA_ERROR_NOT_PERMITTED);
5478 if (((seed_size < MBEDTLS_ENTROPY_MIN_PLATFORM) ||
5479 (seed_size < MBEDTLS_ENTROPY_BLOCK_SIZE)) ||
5480 (seed_size > MBEDTLS_ENTROPY_MAX_SEED_SIZE))
5481 return (PSA_ERROR_INVALID_ARGUMENT);
5483 return (mbedtls_psa_storage_inject_entropy(seed, seed_size));
5485 #endif /* MBEDTLS_PSA_INJECT_ENTROPY */
5487 /** Validate the key type and size for key generation
5489 * \param type The key type
5490 * \param bits The number of bits of the key
5492 * \retval #PSA_SUCCESS
5493 * The key type and size are valid.
5494 * \retval #PSA_ERROR_INVALID_ARGUMENT
5495 * The size in bits of the key is not valid.
5496 * \retval #PSA_ERROR_NOT_SUPPORTED
5497 * The type and/or the size in bits of the key or the combination of
5498 * the two is not supported.
5500 static psa_status_t psa_validate_key_type_and_size_for_key_generation(
5501 psa_key_type_t type, size_t bits) {
5502 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
5504 if (key_type_is_raw_bytes(type)) {
5505 status = validate_unstructured_key_bit_size(type, bits);
5506 if (status != PSA_SUCCESS)
5507 return (status);
5508 } else
5509 #if defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR)
5510 if (PSA_KEY_TYPE_IS_RSA(type) && PSA_KEY_TYPE_IS_KEY_PAIR(type)) {
5511 if (bits > PSA_VENDOR_RSA_MAX_KEY_BITS)
5512 return (PSA_ERROR_NOT_SUPPORTED);
5514 /* Accept only byte-aligned keys, for the same reasons as
5515 * in psa_import_rsa_key(). */
5516 if (bits % 8 != 0)
5517 return (PSA_ERROR_NOT_SUPPORTED);
5518 } else
5519 #endif /* defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR) */
5521 #if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR)
5522 if (PSA_KEY_TYPE_IS_ECC(type) && PSA_KEY_TYPE_IS_KEY_PAIR(type)) {
5523 /* To avoid empty block, return successfully here. */
5524 return (PSA_SUCCESS);
5525 } else
5526 #endif /* defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR) */
5528 return (PSA_ERROR_NOT_SUPPORTED);
5531 return (PSA_SUCCESS);
5534 psa_status_t psa_generate_key_internal(
5535 const psa_key_attributes_t *attributes,
5536 uint8_t *key_buffer, size_t key_buffer_size, size_t *key_buffer_length) {
5537 psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
5538 psa_key_type_t type = attributes->core.type;
5540 if ((attributes->domain_parameters == NULL) &&
5541 (attributes->domain_parameters_size != 0))
5542 return (PSA_ERROR_INVALID_ARGUMENT);
5544 if (key_type_is_raw_bytes(type)) {
5545 status = psa_generate_random(key_buffer, key_buffer_size);
5546 if (status != PSA_SUCCESS)
5547 return (status);
5549 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES)
5550 if (type == PSA_KEY_TYPE_DES)
5551 psa_des_set_key_parity(key_buffer, key_buffer_size);
5552 #endif /* MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES */
5553 } else
5555 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR)
5556 if (type == PSA_KEY_TYPE_RSA_KEY_PAIR) {
5557 return (mbedtls_psa_rsa_generate_key(attributes,
5558 key_buffer,
5559 key_buffer_size,
5560 key_buffer_length));
5561 } else
5562 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) */
5564 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR)
5565 if (PSA_KEY_TYPE_IS_ECC(type) && PSA_KEY_TYPE_IS_KEY_PAIR(type)) {
5566 return (mbedtls_psa_ecp_generate_key(attributes,
5567 key_buffer,
5568 key_buffer_size,
5569 key_buffer_length));
5570 } else
5571 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) */
5573 (void)key_buffer_length;
5574 return (PSA_ERROR_NOT_SUPPORTED);
5577 return (PSA_SUCCESS);
5580 psa_status_t psa_generate_key(const psa_key_attributes_t *attributes,
5581 mbedtls_svc_key_id_t *key) {
5582 psa_status_t status;
5583 psa_key_slot_t *slot = NULL;
5584 psa_se_drv_table_entry_t *driver = NULL;
5585 size_t key_buffer_size;
5587 *key = MBEDTLS_SVC_KEY_ID_INIT;
5589 /* Reject any attempt to create a zero-length key so that we don't
5590 * risk tripping up later, e.g. on a malloc(0) that returns NULL. */
5591 if (psa_get_key_bits(attributes) == 0)
5592 return (PSA_ERROR_INVALID_ARGUMENT);
5594 status = psa_start_key_creation(PSA_KEY_CREATION_GENERATE, attributes,
5595 &slot, &driver);
5596 if (status != PSA_SUCCESS)
5597 goto exit;
5599 /* In the case of a transparent key or an opaque key stored in local
5600 * storage (thus not in the case of generating a key in a secure element
5601 * or cryptoprocessor with storage), we have to allocate a buffer to
5602 * hold the generated key material. */
5603 if (slot->key.data == NULL) {
5604 if (PSA_KEY_LIFETIME_GET_LOCATION(attributes->core.lifetime) ==
5605 PSA_KEY_LOCATION_LOCAL_STORAGE) {
5606 status = psa_validate_key_type_and_size_for_key_generation(
5607 attributes->core.type, attributes->core.bits);
5608 if (status != PSA_SUCCESS)
5609 goto exit;
5611 key_buffer_size = PSA_EXPORT_KEY_OUTPUT_SIZE(
5612 attributes->core.type,
5613 attributes->core.bits);
5614 } else {
5615 status = psa_driver_wrapper_get_key_buffer_size(
5616 attributes, &key_buffer_size);
5617 if (status != PSA_SUCCESS)
5618 goto exit;
5621 status = psa_allocate_buffer_to_slot(slot, key_buffer_size);
5622 if (status != PSA_SUCCESS)
5623 goto exit;
5626 status = psa_driver_wrapper_generate_key(attributes,
5627 slot->key.data, slot->key.bytes, &slot->key.bytes);
5629 if (status != PSA_SUCCESS)
5630 psa_remove_key_data_from_memory(slot);
5632 exit:
5633 if (status == PSA_SUCCESS)
5634 status = psa_finish_key_creation(slot, driver, key);
5635 if (status != PSA_SUCCESS)
5636 psa_fail_key_creation(slot, driver);
5638 return (status);
5641 /****************************************************************/
5642 /* Module setup */
5643 /****************************************************************/
5645 #if !defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
5646 psa_status_t mbedtls_psa_crypto_configure_entropy_sources(
5647 void (* entropy_init)(mbedtls_entropy_context *ctx),
5648 void (* entropy_free)(mbedtls_entropy_context *ctx)) {
5649 if (global_data.rng_state != RNG_NOT_INITIALIZED)
5650 return (PSA_ERROR_BAD_STATE);
5651 global_data.rng.entropy_init = entropy_init;
5652 global_data.rng.entropy_free = entropy_free;
5653 return (PSA_SUCCESS);
5655 #endif /* !defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG) */
5657 void mbedtls_psa_crypto_free(void) {
5658 psa_wipe_all_key_slots();
5659 if (global_data.rng_state != RNG_NOT_INITIALIZED) {
5660 mbedtls_psa_random_free(&global_data.rng);
5662 /* Wipe all remaining data, including configuration.
5663 * In particular, this sets all state indicator to the value
5664 * indicating "uninitialized". */
5665 mbedtls_platform_zeroize(&global_data, sizeof(global_data));
5666 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
5667 /* Unregister all secure element drivers, so that we restart from
5668 * a pristine state. */
5669 psa_unregister_all_se_drivers();
5670 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
5673 #if defined(PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS)
5674 /** Recover a transaction that was interrupted by a power failure.
5676 * This function is called during initialization, before psa_crypto_init()
5677 * returns. If this function returns a failure status, the initialization
5678 * fails.
5680 static psa_status_t psa_crypto_recover_transaction(
5681 const psa_crypto_transaction_t *transaction) {
5682 switch (transaction->unknown.type) {
5683 case PSA_CRYPTO_TRANSACTION_CREATE_KEY:
5684 case PSA_CRYPTO_TRANSACTION_DESTROY_KEY:
5685 /* TODO - fall through to the failure case until this
5686 * is implemented.
5687 * https://github.com/ARMmbed/mbed-crypto/issues/218
5689 default:
5690 /* We found an unsupported transaction in the storage.
5691 * We don't know what state the storage is in. Give up. */
5692 return (PSA_ERROR_DATA_INVALID);
5695 #endif /* PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS */
5697 psa_status_t psa_crypto_init(void) {
5698 psa_status_t status;
5700 /* Double initialization is explicitly allowed. */
5701 if (global_data.initialized != 0)
5702 return (PSA_SUCCESS);
5704 /* Initialize and seed the random generator. */
5705 mbedtls_psa_random_init(&global_data.rng);
5706 global_data.rng_state = RNG_INITIALIZED;
5707 status = mbedtls_psa_random_seed(&global_data.rng);
5708 if (status != PSA_SUCCESS)
5709 goto exit;
5710 global_data.rng_state = RNG_SEEDED;
5712 status = psa_initialize_key_slots();
5713 if (status != PSA_SUCCESS)
5714 goto exit;
5716 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
5717 status = psa_init_all_se_drivers();
5718 if (status != PSA_SUCCESS)
5719 goto exit;
5720 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
5722 #if defined(PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS)
5723 status = psa_crypto_load_transaction();
5724 if (status == PSA_SUCCESS) {
5725 status = psa_crypto_recover_transaction(&psa_crypto_transaction);
5726 if (status != PSA_SUCCESS)
5727 goto exit;
5728 status = psa_crypto_stop_transaction();
5729 } else if (status == PSA_ERROR_DOES_NOT_EXIST) {
5730 /* There's no transaction to complete. It's all good. */
5731 status = PSA_SUCCESS;
5733 #endif /* PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS */
5735 /* All done. */
5736 global_data.initialized = 1;
5738 exit:
5739 if (status != PSA_SUCCESS)
5740 mbedtls_psa_crypto_free();
5741 return (status);
5744 #endif /* MBEDTLS_PSA_CRYPTO_C */