• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  PSA crypto layer on top of Mbed TLS crypto
3  */
4 /*
5  *  Copyright The Mbed TLS Contributors
6  *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
7  */
8 
9 #include "common.h"
10 
11 #if defined(MBEDTLS_PSA_CRYPTO_C)
12 
13 #if defined(MBEDTLS_PSA_CRYPTO_CONFIG)
14 #include "check_crypto_config.h"
15 #endif
16 
17 #include "psa/crypto.h"
18 
19 #include "psa_crypto_cipher.h"
20 #include "psa_crypto_core.h"
21 #include "psa_crypto_invasive.h"
22 #include "psa_crypto_driver_wrappers.h"
23 #include "psa_crypto_ecp.h"
24 #include "psa_crypto_hash.h"
25 #include "psa_crypto_mac.h"
26 #include "psa_crypto_rsa.h"
27 #include "psa_crypto_ecp.h"
28 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
29 #include "psa_crypto_se.h"
30 #endif
31 #include "psa_crypto_slot_management.h"
32 /* Include internal declarations that are useful for implementing persistently
33  * stored keys. */
34 #include "psa_crypto_storage.h"
35 
36 #include "psa_crypto_random_impl.h"
37 
38 #include <stdlib.h>
39 #include <string.h>
40 #include "mbedtls/platform.h"
41 
42 #include "mbedtls/aes.h"
43 #include "mbedtls/arc4.h"
44 #include "mbedtls/asn1.h"
45 #include "mbedtls/asn1write.h"
46 #include "mbedtls/bignum.h"
47 #include "mbedtls/blowfish.h"
48 #include "mbedtls/camellia.h"
49 #include "mbedtls/chacha20.h"
50 #include "mbedtls/chachapoly.h"
51 #include "mbedtls/cipher.h"
52 #include "mbedtls/ccm.h"
53 #include "mbedtls/cmac.h"
54 #include "mbedtls/des.h"
55 #include "mbedtls/ecdh.h"
56 #include "mbedtls/ecp.h"
57 #include "mbedtls/entropy.h"
58 #include "mbedtls/error.h"
59 #include "mbedtls/gcm.h"
60 #include "mbedtls/md2.h"
61 #include "mbedtls/md4.h"
62 #include "mbedtls/md5.h"
63 #include "mbedtls/md.h"
64 #include "mbedtls/md_internal.h"
65 #include "mbedtls/pk.h"
66 #include "mbedtls/pk_internal.h"
67 #include "mbedtls/platform_util.h"
68 #include "mbedtls/error.h"
69 #include "mbedtls/ripemd160.h"
70 #include "mbedtls/rsa.h"
71 #include "mbedtls/sha1.h"
72 #include "mbedtls/sha256.h"
73 #include "mbedtls/sha512.h"
74 #include "mbedtls/xtea.h"
75 
76 #define ARRAY_LENGTH(array) (sizeof(array) / sizeof(*(array)))
77 
78 /****************************************************************/
79 /* Global data, support functions and library management */
80 /****************************************************************/
81 
key_type_is_raw_bytes(psa_key_type_t type)82 static int key_type_is_raw_bytes(psa_key_type_t type)
83 {
84     return PSA_KEY_TYPE_IS_UNSTRUCTURED(type);
85 }
86 
87 /* Values for psa_global_data_t::rng_state */
88 #define RNG_NOT_INITIALIZED 0
89 #define RNG_INITIALIZED 1
90 #define RNG_SEEDED 2
91 
92 typedef struct {
93     unsigned initialized : 1;
94     unsigned rng_state : 2;
95     mbedtls_psa_random_context_t rng;
96 } psa_global_data_t;
97 
98 static psa_global_data_t global_data;
99 
100 #if !defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
101 mbedtls_psa_drbg_context_t *const mbedtls_psa_random_state =
102     &global_data.rng.drbg;
103 #endif
104 
105 #define GUARD_MODULE_INITIALIZED        \
106     if (global_data.initialized == 0)  \
107     return PSA_ERROR_BAD_STATE;
108 
mbedtls_to_psa_error(int ret)109 psa_status_t mbedtls_to_psa_error(int ret)
110 {
111     /* Mbed TLS error codes can combine a high-level error code and a
112      * low-level error code. The low-level error usually reflects the
113      * root cause better, so dispatch on that preferably. */
114     int low_level_ret = -(-ret & 0x007f);
115     switch (low_level_ret != 0 ? low_level_ret : ret) {
116         case 0:
117             return PSA_SUCCESS;
118 
119         case MBEDTLS_ERR_AES_INVALID_KEY_LENGTH:
120         case MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH:
121         case MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE:
122             return PSA_ERROR_NOT_SUPPORTED;
123         case MBEDTLS_ERR_AES_HW_ACCEL_FAILED:
124             return PSA_ERROR_HARDWARE_FAILURE;
125 
126         case MBEDTLS_ERR_ARC4_HW_ACCEL_FAILED:
127             return PSA_ERROR_HARDWARE_FAILURE;
128 
129         case MBEDTLS_ERR_ASN1_OUT_OF_DATA:
130         case MBEDTLS_ERR_ASN1_UNEXPECTED_TAG:
131         case MBEDTLS_ERR_ASN1_INVALID_LENGTH:
132         case MBEDTLS_ERR_ASN1_LENGTH_MISMATCH:
133         case MBEDTLS_ERR_ASN1_INVALID_DATA:
134             return PSA_ERROR_INVALID_ARGUMENT;
135         case MBEDTLS_ERR_ASN1_ALLOC_FAILED:
136             return PSA_ERROR_INSUFFICIENT_MEMORY;
137         case MBEDTLS_ERR_ASN1_BUF_TOO_SMALL:
138             return PSA_ERROR_BUFFER_TOO_SMALL;
139 
140 #if defined(MBEDTLS_ERR_BLOWFISH_BAD_INPUT_DATA)
141         case MBEDTLS_ERR_BLOWFISH_BAD_INPUT_DATA:
142 #elif defined(MBEDTLS_ERR_BLOWFISH_INVALID_KEY_LENGTH)
143         case MBEDTLS_ERR_BLOWFISH_INVALID_KEY_LENGTH:
144 #endif
145         case MBEDTLS_ERR_BLOWFISH_INVALID_INPUT_LENGTH:
146             return PSA_ERROR_NOT_SUPPORTED;
147         case MBEDTLS_ERR_BLOWFISH_HW_ACCEL_FAILED:
148             return PSA_ERROR_HARDWARE_FAILURE;
149 
150 #if defined(MBEDTLS_ERR_CAMELLIA_BAD_INPUT_DATA)
151         case MBEDTLS_ERR_CAMELLIA_BAD_INPUT_DATA:
152 #elif defined(MBEDTLS_ERR_CAMELLIA_INVALID_KEY_LENGTH)
153         case MBEDTLS_ERR_CAMELLIA_INVALID_KEY_LENGTH:
154 #endif
155         case MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH:
156             return PSA_ERROR_NOT_SUPPORTED;
157         case MBEDTLS_ERR_CAMELLIA_HW_ACCEL_FAILED:
158             return PSA_ERROR_HARDWARE_FAILURE;
159 
160         case MBEDTLS_ERR_CCM_BAD_INPUT:
161             return PSA_ERROR_INVALID_ARGUMENT;
162         case MBEDTLS_ERR_CCM_AUTH_FAILED:
163             return PSA_ERROR_INVALID_SIGNATURE;
164         case MBEDTLS_ERR_CCM_HW_ACCEL_FAILED:
165             return PSA_ERROR_HARDWARE_FAILURE;
166 
167         case MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA:
168             return PSA_ERROR_INVALID_ARGUMENT;
169 
170         case MBEDTLS_ERR_CHACHAPOLY_BAD_STATE:
171             return PSA_ERROR_BAD_STATE;
172         case MBEDTLS_ERR_CHACHAPOLY_AUTH_FAILED:
173             return PSA_ERROR_INVALID_SIGNATURE;
174 
175         case MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE:
176             return PSA_ERROR_NOT_SUPPORTED;
177         case MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA:
178             return PSA_ERROR_INVALID_ARGUMENT;
179         case MBEDTLS_ERR_CIPHER_ALLOC_FAILED:
180             return PSA_ERROR_INSUFFICIENT_MEMORY;
181         case MBEDTLS_ERR_CIPHER_INVALID_PADDING:
182             return PSA_ERROR_INVALID_PADDING;
183         case MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED:
184             return PSA_ERROR_INVALID_ARGUMENT;
185         case MBEDTLS_ERR_CIPHER_AUTH_FAILED:
186             return PSA_ERROR_INVALID_SIGNATURE;
187         case MBEDTLS_ERR_CIPHER_INVALID_CONTEXT:
188             return PSA_ERROR_CORRUPTION_DETECTED;
189         case MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED:
190             return PSA_ERROR_HARDWARE_FAILURE;
191 
192         case MBEDTLS_ERR_CMAC_HW_ACCEL_FAILED:
193             return PSA_ERROR_HARDWARE_FAILURE;
194 
195 #if !(defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG) ||      \
196             defined(MBEDTLS_PSA_HMAC_DRBG_MD_TYPE))
197         /* Only check CTR_DRBG error codes if underlying mbedtls_xxx
198          * functions are passed a CTR_DRBG instance. */
199         case MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED:
200             return PSA_ERROR_INSUFFICIENT_ENTROPY;
201         case MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG:
202         case MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG:
203             return PSA_ERROR_NOT_SUPPORTED;
204         case MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR:
205             return PSA_ERROR_INSUFFICIENT_ENTROPY;
206 #endif
207 
208         case MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH:
209             return PSA_ERROR_NOT_SUPPORTED;
210         case MBEDTLS_ERR_DES_HW_ACCEL_FAILED:
211             return PSA_ERROR_HARDWARE_FAILURE;
212 
213         case MBEDTLS_ERR_ENTROPY_NO_SOURCES_DEFINED:
214         case MBEDTLS_ERR_ENTROPY_NO_STRONG_SOURCE:
215         case MBEDTLS_ERR_ENTROPY_SOURCE_FAILED:
216             return PSA_ERROR_INSUFFICIENT_ENTROPY;
217 
218         case MBEDTLS_ERR_GCM_AUTH_FAILED:
219             return PSA_ERROR_INVALID_SIGNATURE;
220         case MBEDTLS_ERR_GCM_BAD_INPUT:
221             return PSA_ERROR_INVALID_ARGUMENT;
222         case MBEDTLS_ERR_GCM_HW_ACCEL_FAILED:
223             return PSA_ERROR_HARDWARE_FAILURE;
224 
225 #if !defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG) &&        \
226             defined(MBEDTLS_PSA_HMAC_DRBG_MD_TYPE)
227         /* Only check HMAC_DRBG error codes if underlying mbedtls_xxx
228          * functions are passed a HMAC_DRBG instance. */
229         case MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED:
230             return PSA_ERROR_INSUFFICIENT_ENTROPY;
231         case MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG:
232         case MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG:
233             return PSA_ERROR_NOT_SUPPORTED;
234         case MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR:
235             return PSA_ERROR_INSUFFICIENT_ENTROPY;
236 #endif
237 
238         case MBEDTLS_ERR_MD2_HW_ACCEL_FAILED:
239         case MBEDTLS_ERR_MD4_HW_ACCEL_FAILED:
240         case MBEDTLS_ERR_MD5_HW_ACCEL_FAILED:
241             return PSA_ERROR_HARDWARE_FAILURE;
242 
243         case MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE:
244             return PSA_ERROR_NOT_SUPPORTED;
245         case MBEDTLS_ERR_MD_BAD_INPUT_DATA:
246             return PSA_ERROR_INVALID_ARGUMENT;
247         case MBEDTLS_ERR_MD_ALLOC_FAILED:
248             return PSA_ERROR_INSUFFICIENT_MEMORY;
249         case MBEDTLS_ERR_MD_FILE_IO_ERROR:
250             return PSA_ERROR_STORAGE_FAILURE;
251         case MBEDTLS_ERR_MD_HW_ACCEL_FAILED:
252             return PSA_ERROR_HARDWARE_FAILURE;
253 
254         case MBEDTLS_ERR_MPI_FILE_IO_ERROR:
255             return PSA_ERROR_STORAGE_FAILURE;
256         case MBEDTLS_ERR_MPI_BAD_INPUT_DATA:
257             return PSA_ERROR_INVALID_ARGUMENT;
258         case MBEDTLS_ERR_MPI_INVALID_CHARACTER:
259             return PSA_ERROR_INVALID_ARGUMENT;
260         case MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL:
261             return PSA_ERROR_BUFFER_TOO_SMALL;
262         case MBEDTLS_ERR_MPI_NEGATIVE_VALUE:
263             return PSA_ERROR_INVALID_ARGUMENT;
264         case MBEDTLS_ERR_MPI_DIVISION_BY_ZERO:
265             return PSA_ERROR_INVALID_ARGUMENT;
266         case MBEDTLS_ERR_MPI_NOT_ACCEPTABLE:
267             return PSA_ERROR_INVALID_ARGUMENT;
268         case MBEDTLS_ERR_MPI_ALLOC_FAILED:
269             return PSA_ERROR_INSUFFICIENT_MEMORY;
270 
271         case MBEDTLS_ERR_PK_ALLOC_FAILED:
272             return PSA_ERROR_INSUFFICIENT_MEMORY;
273         case MBEDTLS_ERR_PK_TYPE_MISMATCH:
274         case MBEDTLS_ERR_PK_BAD_INPUT_DATA:
275             return PSA_ERROR_INVALID_ARGUMENT;
276         case MBEDTLS_ERR_PK_FILE_IO_ERROR:
277             return PSA_ERROR_STORAGE_FAILURE;
278         case MBEDTLS_ERR_PK_KEY_INVALID_VERSION:
279         case MBEDTLS_ERR_PK_KEY_INVALID_FORMAT:
280             return PSA_ERROR_INVALID_ARGUMENT;
281         case MBEDTLS_ERR_PK_UNKNOWN_PK_ALG:
282             return PSA_ERROR_NOT_SUPPORTED;
283         case MBEDTLS_ERR_PK_PASSWORD_REQUIRED:
284         case MBEDTLS_ERR_PK_PASSWORD_MISMATCH:
285             return PSA_ERROR_NOT_PERMITTED;
286         case MBEDTLS_ERR_PK_INVALID_PUBKEY:
287             return PSA_ERROR_INVALID_ARGUMENT;
288         case MBEDTLS_ERR_PK_INVALID_ALG:
289         case MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE:
290         case MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE:
291             return PSA_ERROR_NOT_SUPPORTED;
292         case MBEDTLS_ERR_PK_SIG_LEN_MISMATCH:
293             return PSA_ERROR_INVALID_SIGNATURE;
294         case MBEDTLS_ERR_PK_HW_ACCEL_FAILED:
295             return PSA_ERROR_HARDWARE_FAILURE;
296 
297         case MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED:
298             return PSA_ERROR_HARDWARE_FAILURE;
299         case MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED:
300             return PSA_ERROR_NOT_SUPPORTED;
301 
302         case MBEDTLS_ERR_RIPEMD160_HW_ACCEL_FAILED:
303             return PSA_ERROR_HARDWARE_FAILURE;
304 
305         case MBEDTLS_ERR_RSA_BAD_INPUT_DATA:
306             return PSA_ERROR_INVALID_ARGUMENT;
307         case MBEDTLS_ERR_RSA_INVALID_PADDING:
308             return PSA_ERROR_INVALID_PADDING;
309         case MBEDTLS_ERR_RSA_KEY_GEN_FAILED:
310             return PSA_ERROR_HARDWARE_FAILURE;
311         case MBEDTLS_ERR_RSA_KEY_CHECK_FAILED:
312             return PSA_ERROR_INVALID_ARGUMENT;
313         case MBEDTLS_ERR_RSA_PUBLIC_FAILED:
314         case MBEDTLS_ERR_RSA_PRIVATE_FAILED:
315             return PSA_ERROR_CORRUPTION_DETECTED;
316         case MBEDTLS_ERR_RSA_VERIFY_FAILED:
317             return PSA_ERROR_INVALID_SIGNATURE;
318         case MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE:
319             return PSA_ERROR_BUFFER_TOO_SMALL;
320         case MBEDTLS_ERR_RSA_RNG_FAILED:
321             return PSA_ERROR_INSUFFICIENT_ENTROPY;
322         case MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION:
323             return PSA_ERROR_NOT_SUPPORTED;
324         case MBEDTLS_ERR_RSA_HW_ACCEL_FAILED:
325             return PSA_ERROR_HARDWARE_FAILURE;
326 
327         case MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED:
328         case MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED:
329         case MBEDTLS_ERR_SHA512_HW_ACCEL_FAILED:
330             return PSA_ERROR_HARDWARE_FAILURE;
331 
332         case MBEDTLS_ERR_XTEA_INVALID_INPUT_LENGTH:
333             return PSA_ERROR_INVALID_ARGUMENT;
334         case MBEDTLS_ERR_XTEA_HW_ACCEL_FAILED:
335             return PSA_ERROR_HARDWARE_FAILURE;
336 
337         case MBEDTLS_ERR_ECP_BAD_INPUT_DATA:
338         case MBEDTLS_ERR_ECP_INVALID_KEY:
339             return PSA_ERROR_INVALID_ARGUMENT;
340         case MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL:
341             return PSA_ERROR_BUFFER_TOO_SMALL;
342         case MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE:
343             return PSA_ERROR_NOT_SUPPORTED;
344         case MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH:
345         case MBEDTLS_ERR_ECP_VERIFY_FAILED:
346             return PSA_ERROR_INVALID_SIGNATURE;
347         case MBEDTLS_ERR_ECP_ALLOC_FAILED:
348             return PSA_ERROR_INSUFFICIENT_MEMORY;
349         case MBEDTLS_ERR_ECP_RANDOM_FAILED:
350             return PSA_ERROR_INSUFFICIENT_ENTROPY;
351         case MBEDTLS_ERR_ECP_HW_ACCEL_FAILED:
352             return PSA_ERROR_HARDWARE_FAILURE;
353 
354         case MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED:
355             return PSA_ERROR_CORRUPTION_DETECTED;
356 
357         default:
358             return PSA_ERROR_GENERIC_ERROR;
359     }
360 }
361 
362 
363 
364 
365 /****************************************************************/
366 /* Key management */
367 /****************************************************************/
368 
369 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) || \
370     defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY) || \
371     defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
372     defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) || \
373     defined(MBEDTLS_PSA_BUILTIN_ALG_ECDH)
mbedtls_ecc_group_of_psa(psa_ecc_family_t curve,size_t bits,int bits_is_sloppy)374 mbedtls_ecp_group_id mbedtls_ecc_group_of_psa(psa_ecc_family_t curve,
375                                               size_t bits,
376                                               int bits_is_sloppy)
377 {
378     switch (curve) {
379         case PSA_ECC_FAMILY_SECP_R1:
380             switch (bits) {
381 #if defined(PSA_WANT_ECC_SECP_R1_192)
382                 case 192:
383                     return MBEDTLS_ECP_DP_SECP192R1;
384 #endif
385 #if defined(PSA_WANT_ECC_SECP_R1_224)
386                 case 224:
387                     return MBEDTLS_ECP_DP_SECP224R1;
388 #endif
389 #if defined(PSA_WANT_ECC_SECP_R1_256)
390                 case 256:
391                     return MBEDTLS_ECP_DP_SECP256R1;
392 #endif
393 #if defined(PSA_WANT_ECC_SECP_R1_384)
394                 case 384:
395                     return MBEDTLS_ECP_DP_SECP384R1;
396 #endif
397 #if defined(PSA_WANT_ECC_SECP_R1_521)
398                 case 521:
399                     return MBEDTLS_ECP_DP_SECP521R1;
400                 case 528:
401                     if (bits_is_sloppy) {
402                         return MBEDTLS_ECP_DP_SECP521R1;
403                     }
404                     break;
405 #endif
406             }
407             break;
408 
409         case PSA_ECC_FAMILY_BRAINPOOL_P_R1:
410             switch (bits) {
411 #if defined(PSA_WANT_ECC_BRAINPOOL_P_R1_256)
412                 case 256:
413                     return MBEDTLS_ECP_DP_BP256R1;
414 #endif
415 #if defined(PSA_WANT_ECC_BRAINPOOL_P_R1_384)
416                 case 384:
417                     return MBEDTLS_ECP_DP_BP384R1;
418 #endif
419 #if defined(PSA_WANT_ECC_BRAINPOOL_P_R1_512)
420                 case 512:
421                     return MBEDTLS_ECP_DP_BP512R1;
422 #endif
423             }
424             break;
425 
426         case PSA_ECC_FAMILY_MONTGOMERY:
427             switch (bits) {
428 #if defined(PSA_WANT_ECC_MONTGOMERY_255)
429                 case 255:
430                     return MBEDTLS_ECP_DP_CURVE25519;
431                 case 256:
432                     if (bits_is_sloppy) {
433                         return MBEDTLS_ECP_DP_CURVE25519;
434                     }
435                     break;
436 #endif
437 #if defined(PSA_WANT_ECC_MONTGOMERY_448)
438                 case 448:
439                     return MBEDTLS_ECP_DP_CURVE448;
440 #endif
441             }
442             break;
443 
444         case PSA_ECC_FAMILY_SECP_K1:
445             switch (bits) {
446 #if defined(PSA_WANT_ECC_SECP_K1_192)
447                 case 192:
448                     return MBEDTLS_ECP_DP_SECP192K1;
449 #endif
450 #if defined(PSA_WANT_ECC_SECP_K1_224)
451                 case 224:
452                     return MBEDTLS_ECP_DP_SECP224K1;
453 #endif
454 #if defined(PSA_WANT_ECC_SECP_K1_256)
455                 case 256:
456                     return MBEDTLS_ECP_DP_SECP256K1;
457 #endif
458             }
459             break;
460     }
461 
462     (void) bits_is_sloppy;
463     return MBEDTLS_ECP_DP_NONE;
464 }
465 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) ||
466           defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY) ||
467           defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
468           defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) ||
469           defined(MBEDTLS_PSA_BUILTIN_ALG_ECDH) */
470 
validate_unstructured_key_bit_size(psa_key_type_t type,size_t bits)471 static psa_status_t validate_unstructured_key_bit_size(psa_key_type_t type,
472                                                        size_t bits)
473 {
474     /* Check that the bit size is acceptable for the key type */
475     switch (type) {
476         case PSA_KEY_TYPE_RAW_DATA:
477         case PSA_KEY_TYPE_HMAC:
478         case PSA_KEY_TYPE_DERIVE:
479             break;
480 #if defined(PSA_WANT_KEY_TYPE_AES)
481         case PSA_KEY_TYPE_AES:
482             if (bits != 128 && bits != 192 && bits != 256) {
483                 return PSA_ERROR_INVALID_ARGUMENT;
484             }
485             break;
486 #endif
487 #if defined(PSA_WANT_KEY_TYPE_ARIA)
488         case PSA_KEY_TYPE_ARIA:
489             if (bits != 128 && bits != 192 && bits != 256) {
490                 return PSA_ERROR_INVALID_ARGUMENT;
491             }
492             break;
493 #endif
494 #if defined(PSA_WANT_KEY_TYPE_CAMELLIA)
495         case PSA_KEY_TYPE_CAMELLIA:
496             if (bits != 128 && bits != 192 && bits != 256) {
497                 return PSA_ERROR_INVALID_ARGUMENT;
498             }
499             break;
500 #endif
501 #if defined(PSA_WANT_KEY_TYPE_DES)
502         case PSA_KEY_TYPE_DES:
503             if (bits != 64 && bits != 128 && bits != 192) {
504                 return PSA_ERROR_INVALID_ARGUMENT;
505             }
506             break;
507 #endif
508 #if defined(PSA_WANT_KEY_TYPE_ARC4)
509         case PSA_KEY_TYPE_ARC4:
510             if (bits < 8 || bits > 2048) {
511                 return PSA_ERROR_INVALID_ARGUMENT;
512             }
513             break;
514 #endif
515 #if defined(PSA_WANT_KEY_TYPE_CHACHA20)
516         case PSA_KEY_TYPE_CHACHA20:
517             if (bits != 256) {
518                 return PSA_ERROR_INVALID_ARGUMENT;
519             }
520             break;
521 #endif
522         default:
523             return PSA_ERROR_NOT_SUPPORTED;
524     }
525     if (bits % 8 != 0) {
526         return PSA_ERROR_INVALID_ARGUMENT;
527     }
528 
529     return PSA_SUCCESS;
530 }
531 
532 /** Check whether a given key type is valid for use with a given MAC algorithm
533  *
534  * Upon successful return of this function, the behavior of #PSA_MAC_LENGTH
535  * when called with the validated \p algorithm and \p key_type is well-defined.
536  *
537  * \param[in] algorithm     The specific MAC algorithm (can be wildcard).
538  * \param[in] key_type      The key type of the key to be used with the
539  *                          \p algorithm.
540  *
541  * \retval #PSA_SUCCESS
542  *         The \p key_type is valid for use with the \p algorithm
543  * \retval #PSA_ERROR_INVALID_ARGUMENT
544  *         The \p key_type is not valid for use with the \p algorithm
545  */
psa_mac_key_can_do(psa_algorithm_t algorithm,psa_key_type_t key_type)546 MBEDTLS_STATIC_TESTABLE psa_status_t psa_mac_key_can_do(
547     psa_algorithm_t algorithm,
548     psa_key_type_t key_type)
549 {
550     if (PSA_ALG_IS_HMAC(algorithm)) {
551         if (key_type == PSA_KEY_TYPE_HMAC) {
552             return PSA_SUCCESS;
553         }
554     }
555 
556     if (PSA_ALG_IS_BLOCK_CIPHER_MAC(algorithm)) {
557         /* Check that we're calling PSA_BLOCK_CIPHER_BLOCK_LENGTH with a cipher
558          * key. */
559         if ((key_type & PSA_KEY_TYPE_CATEGORY_MASK) ==
560             PSA_KEY_TYPE_CATEGORY_SYMMETRIC) {
561             /* PSA_BLOCK_CIPHER_BLOCK_LENGTH returns 1 for stream ciphers and
562              * the block length (larger than 1) for block ciphers. */
563             if (PSA_BLOCK_CIPHER_BLOCK_LENGTH(key_type) > 1) {
564                 return PSA_SUCCESS;
565             }
566         }
567     }
568 
569     return PSA_ERROR_INVALID_ARGUMENT;
570 }
571 
psa_allocate_buffer_to_slot(psa_key_slot_t * slot,size_t buffer_length)572 psa_status_t psa_allocate_buffer_to_slot(psa_key_slot_t *slot,
573                                          size_t buffer_length)
574 {
575     if (slot->key.data != NULL) {
576         return PSA_ERROR_ALREADY_EXISTS;
577     }
578 
579     slot->key.data = mbedtls_calloc(1, buffer_length);
580     if (slot->key.data == NULL) {
581         return PSA_ERROR_INSUFFICIENT_MEMORY;
582     }
583 
584     slot->key.bytes = buffer_length;
585     return PSA_SUCCESS;
586 }
587 
psa_copy_key_material_into_slot(psa_key_slot_t * slot,const uint8_t * data,size_t data_length)588 psa_status_t psa_copy_key_material_into_slot(psa_key_slot_t *slot,
589                                              const uint8_t *data,
590                                              size_t data_length)
591 {
592     psa_status_t status = psa_allocate_buffer_to_slot(slot,
593                                                       data_length);
594     if (status != PSA_SUCCESS) {
595         return status;
596     }
597 
598     memcpy(slot->key.data, data, data_length);
599     return PSA_SUCCESS;
600 }
601 
psa_import_key_into_slot(const psa_key_attributes_t * attributes,const uint8_t * data,size_t data_length,uint8_t * key_buffer,size_t key_buffer_size,size_t * key_buffer_length,size_t * bits)602 psa_status_t psa_import_key_into_slot(
603     const psa_key_attributes_t *attributes,
604     const uint8_t *data, size_t data_length,
605     uint8_t *key_buffer, size_t key_buffer_size,
606     size_t *key_buffer_length, size_t *bits)
607 {
608     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
609     psa_key_type_t type = attributes->core.type;
610 
611     /* zero-length keys are never supported. */
612     if (data_length == 0) {
613         return PSA_ERROR_NOT_SUPPORTED;
614     }
615 
616     if (key_type_is_raw_bytes(type)) {
617         *bits = PSA_BYTES_TO_BITS(data_length);
618 
619         /* Ensure that the bytes-to-bits conversion hasn't overflown. */
620         if (data_length > SIZE_MAX / 8) {
621             return PSA_ERROR_NOT_SUPPORTED;
622         }
623 
624         /* Enforce a size limit, and in particular ensure that the bit
625          * size fits in its representation type. */
626         if ((*bits) > PSA_MAX_KEY_BITS) {
627             return PSA_ERROR_NOT_SUPPORTED;
628         }
629 
630         status = validate_unstructured_key_bit_size(type, *bits);
631         if (status != PSA_SUCCESS) {
632             return status;
633         }
634 
635         /* Copy the key material. */
636         memcpy(key_buffer, data, data_length);
637         *key_buffer_length = data_length;
638         (void) key_buffer_size;
639 
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);
650         }
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);
661         }
662 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) ||
663         * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY) */
664     }
665 
666     return PSA_ERROR_NOT_SUPPORTED;
667 }
668 
669 /** Calculate the intersection of two algorithm usage policies.
670  *
671  * Return 0 (which allows no operation) on incompatibility.
672  */
psa_key_policy_algorithm_intersection(psa_key_type_t key_type,psa_algorithm_t alg1,psa_algorithm_t alg2)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 {
678     /* Common case: both sides actually specify the same policy. */
679     if (alg1 == alg2) {
680         return alg1;
681     }
682     /* If the policies are from the same hash-and-sign family, check
683      * if one is a wildcard. If so the other has the specific algorithm. */
684     if (PSA_ALG_IS_SIGN_HASH(alg1) &&
685         PSA_ALG_IS_SIGN_HASH(alg2) &&
686         (alg1 & ~PSA_ALG_HASH_MASK) == (alg2 & ~PSA_ALG_HASH_MASK)) {
687         if (PSA_ALG_SIGN_GET_HASH(alg1) == PSA_ALG_ANY_HASH) {
688             return alg2;
689         }
690         if (PSA_ALG_SIGN_GET_HASH(alg2) == PSA_ALG_ANY_HASH) {
691             return alg1;
692         }
693     }
694     /* If the policies are from the same AEAD family, check whether
695      * one of them is a minimum-tag-length wildcard. Calculate the most
696      * restrictive tag length. */
697     if (PSA_ALG_IS_AEAD(alg1) && PSA_ALG_IS_AEAD(alg2) &&
698         (PSA_ALG_AEAD_WITH_SHORTENED_TAG(alg1, 0) ==
699          PSA_ALG_AEAD_WITH_SHORTENED_TAG(alg2, 0))) {
700         size_t alg1_len = PSA_ALG_AEAD_GET_TAG_LENGTH(alg1);
701         size_t alg2_len = PSA_ALG_AEAD_GET_TAG_LENGTH(alg2);
702         size_t restricted_len = alg1_len > alg2_len ? alg1_len : alg2_len;
703 
704         /* If both are wildcards, return most restrictive wildcard */
705         if (((alg1 & PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG) != 0) &&
706             ((alg2 & PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG) != 0)) {
707             return PSA_ALG_AEAD_WITH_AT_LEAST_THIS_LENGTH_TAG(
708                 alg1, restricted_len);
709         }
710         /* If only one is a wildcard, return specific algorithm if compatible. */
711         if (((alg1 & PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG) != 0) &&
712             (alg1_len <= alg2_len)) {
713             return alg2;
714         }
715         if (((alg2 & PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG) != 0) &&
716             (alg2_len <= alg1_len)) {
717             return alg1;
718         }
719     }
720     /* If the policies are from the same MAC family, check whether one
721      * of them is a minimum-MAC-length policy. Calculate the most
722      * restrictive tag length. */
723     if (PSA_ALG_IS_MAC(alg1) && PSA_ALG_IS_MAC(alg2) &&
724         (PSA_ALG_FULL_LENGTH_MAC(alg1) ==
725          PSA_ALG_FULL_LENGTH_MAC(alg2))) {
726         /* Validate the combination of key type and algorithm. Since the base
727          * algorithm of alg1 and alg2 are the same, we only need this once. */
728         if (PSA_SUCCESS != psa_mac_key_can_do(alg1, key_type)) {
729             return 0;
730         }
731 
732         /* Get the (exact or at-least) output lengths for both sides of the
733          * requested intersection. None of the currently supported algorithms
734          * have an output length dependent on the actual key size, so setting it
735          * to a bogus value of 0 is currently OK.
736          *
737          * Note that for at-least-this-length wildcard algorithms, the output
738          * length is set to the shortest allowed length, which allows us to
739          * calculate the most restrictive tag length for the intersection. */
740         size_t alg1_len = PSA_MAC_LENGTH(key_type, 0, alg1);
741         size_t alg2_len = PSA_MAC_LENGTH(key_type, 0, alg2);
742         size_t restricted_len = alg1_len > alg2_len ? alg1_len : alg2_len;
743 
744         /* If both are wildcards, return most restrictive wildcard */
745         if (((alg1 & PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG) != 0) &&
746             ((alg2 & PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG) != 0)) {
747             return PSA_ALG_AT_LEAST_THIS_LENGTH_MAC(alg1, restricted_len);
748         }
749 
750         /* If only one is an at-least-this-length policy, the intersection would
751          * be the other (fixed-length) policy as long as said fixed length is
752          * equal to or larger than the shortest allowed length. */
753         if ((alg1 & PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG) != 0) {
754             return (alg1_len <= alg2_len) ? alg2 : 0;
755         }
756         if ((alg2 & PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG) != 0) {
757             return (alg2_len <= alg1_len) ? alg1 : 0;
758         }
759 
760         /* If none of them are wildcards, check whether they define the same tag
761          * length. This is still possible here when one is default-length and
762          * the other specific-length. Ensure to always return the
763          * specific-length version for the intersection. */
764         if (alg1_len == alg2_len) {
765             return PSA_ALG_TRUNCATED_MAC(alg1, alg1_len);
766         }
767     }
768     /* If the policies are incompatible, allow nothing. */
769     return 0;
770 }
771 
psa_key_algorithm_permits(psa_key_type_t key_type,psa_algorithm_t policy_alg,psa_algorithm_t requested_alg)772 static int psa_key_algorithm_permits(psa_key_type_t key_type,
773                                      psa_algorithm_t policy_alg,
774                                      psa_algorithm_t requested_alg)
775 {
776     /* Common case: the policy only allows requested_alg. */
777     if (requested_alg == policy_alg) {
778         return 1;
779     }
780     /* If policy_alg is a hash-and-sign with a wildcard for the hash,
781      * and requested_alg is the same hash-and-sign family with any hash,
782      * then requested_alg is compliant with policy_alg. */
783     if (PSA_ALG_IS_SIGN_HASH(requested_alg) &&
784         PSA_ALG_SIGN_GET_HASH(policy_alg) == PSA_ALG_ANY_HASH) {
785         return (policy_alg & ~PSA_ALG_HASH_MASK) ==
786                (requested_alg & ~PSA_ALG_HASH_MASK);
787     }
788     /* If policy_alg is a wildcard AEAD algorithm of the same base as
789      * the requested algorithm, check the requested tag length to be
790      * equal-length or longer than the wildcard-specified length. */
791     if (PSA_ALG_IS_AEAD(policy_alg) &&
792         PSA_ALG_IS_AEAD(requested_alg) &&
793         (PSA_ALG_AEAD_WITH_SHORTENED_TAG(policy_alg, 0) ==
794          PSA_ALG_AEAD_WITH_SHORTENED_TAG(requested_alg, 0)) &&
795         ((policy_alg & PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG) != 0)) {
796         return PSA_ALG_AEAD_GET_TAG_LENGTH(policy_alg) <=
797                PSA_ALG_AEAD_GET_TAG_LENGTH(requested_alg);
798     }
799     /* If policy_alg is a MAC algorithm of the same base as the requested
800      * algorithm, check whether their MAC lengths are compatible. */
801     if (PSA_ALG_IS_MAC(policy_alg) &&
802         PSA_ALG_IS_MAC(requested_alg) &&
803         (PSA_ALG_FULL_LENGTH_MAC(policy_alg) ==
804          PSA_ALG_FULL_LENGTH_MAC(requested_alg))) {
805         /* Validate the combination of key type and algorithm. Since the policy
806          * and requested algorithms are the same, we only need this once. */
807         if (PSA_SUCCESS != psa_mac_key_can_do(policy_alg, key_type)) {
808             return 0;
809         }
810 
811         /* Get both the requested output length for the algorithm which is to be
812          * verified, and the default output length for the base algorithm.
813          * Note that none of the currently supported algorithms have an output
814          * length dependent on actual key size, so setting it to a bogus value
815          * of 0 is currently OK. */
816         size_t requested_output_length = PSA_MAC_LENGTH(
817             key_type, 0, requested_alg);
818         size_t default_output_length = PSA_MAC_LENGTH(
819             key_type, 0,
820             PSA_ALG_FULL_LENGTH_MAC(requested_alg));
821 
822         /* If the policy is default-length, only allow an algorithm with
823          * a declared exact-length matching the default. */
824         if (PSA_MAC_TRUNCATED_LENGTH(policy_alg) == 0) {
825             return requested_output_length == default_output_length;
826         }
827 
828         /* If the requested algorithm is default-length, allow it if the policy
829          * length exactly matches the default length. */
830         if (PSA_MAC_TRUNCATED_LENGTH(requested_alg) == 0 &&
831             PSA_MAC_TRUNCATED_LENGTH(policy_alg) == default_output_length) {
832             return 1;
833         }
834 
835         /* If policy_alg is an at-least-this-length wildcard MAC algorithm,
836          * check for the requested MAC length to be equal to or longer than the
837          * minimum allowed length. */
838         if ((policy_alg & PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG) != 0) {
839             return PSA_MAC_TRUNCATED_LENGTH(policy_alg) <=
840                    requested_output_length;
841         }
842     }
843     /* If policy_alg is a generic key agreement operation, then using it for
844      * a key derivation with that key agreement should also be allowed. This
845      * behaviour is expected to be defined in a future specification version. */
846     if (PSA_ALG_IS_RAW_KEY_AGREEMENT(policy_alg) &&
847         PSA_ALG_IS_KEY_AGREEMENT(requested_alg)) {
848         return PSA_ALG_KEY_AGREEMENT_GET_BASE(requested_alg) ==
849                policy_alg;
850     }
851     /* If it isn't explicitly permitted, it's forbidden. */
852     return 0;
853 }
854 
855 /** Test whether a policy permits an algorithm.
856  *
857  * The caller must test usage flags separately.
858  *
859  * \note This function requires providing the key type for which the policy is
860  *       being validated, since some algorithm policy definitions (e.g. MAC)
861  *       have different properties depending on what kind of cipher it is
862  *       combined with.
863  *
864  * \retval PSA_SUCCESS                  When \p alg is a specific algorithm
865  *                                      allowed by the \p policy.
866  * \retval PSA_ERROR_INVALID_ARGUMENT   When \p alg is not a specific algorithm
867  * \retval PSA_ERROR_NOT_PERMITTED      When \p alg is a specific algorithm, but
868  *                                      the \p policy does not allow it.
869  */
psa_key_policy_permits(const psa_key_policy_t * policy,psa_key_type_t key_type,psa_algorithm_t alg)870 static psa_status_t psa_key_policy_permits(const psa_key_policy_t *policy,
871                                            psa_key_type_t key_type,
872                                            psa_algorithm_t alg)
873 {
874     /* '0' is not a valid algorithm */
875     if (alg == 0) {
876         return PSA_ERROR_INVALID_ARGUMENT;
877     }
878 
879     /* A requested algorithm cannot be a wildcard. */
880     if (PSA_ALG_IS_WILDCARD(alg)) {
881         return PSA_ERROR_INVALID_ARGUMENT;
882     }
883 
884     if (psa_key_algorithm_permits(key_type, policy->alg, alg) ||
885         psa_key_algorithm_permits(key_type, policy->alg2, alg)) {
886         return PSA_SUCCESS;
887     } else {
888         return PSA_ERROR_NOT_PERMITTED;
889     }
890 }
891 
892 /** Restrict a key policy based on a constraint.
893  *
894  * \note This function requires providing the key type for which the policy is
895  *       being restricted, since some algorithm policy definitions (e.g. MAC)
896  *       have different properties depending on what kind of cipher it is
897  *       combined with.
898  *
899  * \param[in] key_type      The key type for which to restrict the policy
900  * \param[in,out] policy    The policy to restrict.
901  * \param[in] constraint    The policy constraint to apply.
902  *
903  * \retval #PSA_SUCCESS
904  *         \c *policy contains the intersection of the original value of
905  *         \c *policy and \c *constraint.
906  * \retval #PSA_ERROR_INVALID_ARGUMENT
907  *         \c key_type, \c *policy and \c *constraint are incompatible.
908  *         \c *policy is unchanged.
909  */
psa_restrict_key_policy(psa_key_type_t key_type,psa_key_policy_t * policy,const psa_key_policy_t * constraint)910 static psa_status_t psa_restrict_key_policy(
911     psa_key_type_t key_type,
912     psa_key_policy_t *policy,
913     const psa_key_policy_t *constraint)
914 {
915     psa_algorithm_t intersection_alg =
916         psa_key_policy_algorithm_intersection(key_type, policy->alg,
917                                               constraint->alg);
918     psa_algorithm_t intersection_alg2 =
919         psa_key_policy_algorithm_intersection(key_type, policy->alg2,
920                                               constraint->alg2);
921     if (intersection_alg == 0 && policy->alg != 0 && constraint->alg != 0) {
922         return PSA_ERROR_INVALID_ARGUMENT;
923     }
924     if (intersection_alg2 == 0 && policy->alg2 != 0 && constraint->alg2 != 0) {
925         return PSA_ERROR_INVALID_ARGUMENT;
926     }
927     policy->usage &= constraint->usage;
928     policy->alg = intersection_alg;
929     policy->alg2 = intersection_alg2;
930     return PSA_SUCCESS;
931 }
932 
933 /** Get the description of a key given its identifier and policy constraints
934  *  and lock it.
935  *
936  * The key must have allow all the usage flags set in \p usage. If \p alg is
937  * nonzero, the key must allow operations with this algorithm. If \p alg is
938  * zero, the algorithm is not checked.
939  *
940  * In case of a persistent key, the function loads the description of the key
941  * into a key slot if not already done.
942  *
943  * On success, the returned key slot is locked. It is the responsibility of
944  * the caller to unlock the key slot when it does not access it anymore.
945  */
psa_get_and_lock_key_slot_with_policy(mbedtls_svc_key_id_t key,psa_key_slot_t ** p_slot,psa_key_usage_t usage,psa_algorithm_t alg)946 static psa_status_t psa_get_and_lock_key_slot_with_policy(
947     mbedtls_svc_key_id_t key,
948     psa_key_slot_t **p_slot,
949     psa_key_usage_t usage,
950     psa_algorithm_t alg)
951 {
952     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
953     psa_key_slot_t *slot;
954 
955     status = psa_get_and_lock_key_slot(key, p_slot);
956     if (status != PSA_SUCCESS) {
957         return status;
958     }
959     slot = *p_slot;
960 
961     /* Enforce that usage policy for the key slot contains all the flags
962      * required by the usage parameter. There is one exception: public
963      * keys can always be exported, so we treat public key objects as
964      * if they had the export flag. */
965     if (PSA_KEY_TYPE_IS_PUBLIC_KEY(slot->attr.type)) {
966         usage &= ~PSA_KEY_USAGE_EXPORT;
967     }
968 
969     if ((slot->attr.policy.usage & usage) != usage) {
970         status = PSA_ERROR_NOT_PERMITTED;
971         goto error;
972     }
973 
974     /* Enforce that the usage policy permits the requested algorithm. */
975     if (alg != 0) {
976         status = psa_key_policy_permits(&slot->attr.policy,
977                                         slot->attr.type,
978                                         alg);
979         if (status != PSA_SUCCESS) {
980             goto error;
981         }
982     }
983 
984     return PSA_SUCCESS;
985 
986 error:
987     *p_slot = NULL;
988     psa_unlock_key_slot(slot);
989 
990     return status;
991 }
992 
993 /** Get a key slot containing a transparent key and lock it.
994  *
995  * A transparent key is a key for which the key material is directly
996  * available, as opposed to a key in a secure element and/or to be used
997  * by a secure element.
998  *
999  * This is a temporary function that may be used instead of
1000  * psa_get_and_lock_key_slot_with_policy() when there is no opaque key support
1001  * for a cryptographic operation.
1002  *
1003  * On success, the returned key slot is locked. It is the responsibility of the
1004  * caller to unlock the key slot when it does not access it anymore.
1005  */
psa_get_and_lock_transparent_key_slot_with_policy(mbedtls_svc_key_id_t key,psa_key_slot_t ** p_slot,psa_key_usage_t usage,psa_algorithm_t alg)1006 static psa_status_t psa_get_and_lock_transparent_key_slot_with_policy(
1007     mbedtls_svc_key_id_t key,
1008     psa_key_slot_t **p_slot,
1009     psa_key_usage_t usage,
1010     psa_algorithm_t alg)
1011 {
1012     psa_status_t status = psa_get_and_lock_key_slot_with_policy(key, p_slot,
1013                                                                 usage, alg);
1014     if (status != PSA_SUCCESS) {
1015         return status;
1016     }
1017 
1018     if (psa_key_lifetime_is_external((*p_slot)->attr.lifetime)) {
1019         psa_unlock_key_slot(*p_slot);
1020         *p_slot = NULL;
1021         return PSA_ERROR_NOT_SUPPORTED;
1022     }
1023 
1024     return PSA_SUCCESS;
1025 }
1026 
psa_remove_key_data_from_memory(psa_key_slot_t * slot)1027 psa_status_t psa_remove_key_data_from_memory(psa_key_slot_t *slot)
1028 {
1029     /* Data pointer will always be either a valid pointer or NULL in an
1030      * initialized slot, so we can just free it. */
1031     if (slot->key.data != NULL) {
1032         mbedtls_platform_zeroize(slot->key.data, slot->key.bytes);
1033     }
1034 
1035     mbedtls_free(slot->key.data);
1036     slot->key.data = NULL;
1037     slot->key.bytes = 0;
1038 
1039     return PSA_SUCCESS;
1040 }
1041 
1042 /** Completely wipe a slot in memory, including its policy.
1043  * Persistent storage is not affected. */
psa_wipe_key_slot(psa_key_slot_t * slot)1044 psa_status_t psa_wipe_key_slot(psa_key_slot_t *slot)
1045 {
1046     psa_status_t status = psa_remove_key_data_from_memory(slot);
1047 
1048     /*
1049      * As the return error code may not be handled in case of multiple errors,
1050      * do our best to report an unexpected lock counter: if available
1051      * call MBEDTLS_PARAM_FAILED that may terminate execution (if called as
1052      * part of the execution of a test suite this will stop the test suite
1053      * execution).
1054      */
1055     if (slot->lock_count != 1) {
1056 #ifdef MBEDTLS_CHECK_PARAMS
1057         MBEDTLS_PARAM_FAILED(slot->lock_count == 1);
1058 #endif
1059         status = PSA_ERROR_CORRUPTION_DETECTED;
1060     }
1061 
1062     /* Multipart operations may still be using the key. This is safe
1063      * because all multipart operation objects are independent from
1064      * the key slot: if they need to access the key after the setup
1065      * phase, they have a copy of the key. Note that this means that
1066      * key material can linger until all operations are completed. */
1067     /* At this point, key material and other type-specific content has
1068      * been wiped. Clear remaining metadata. We can call memset and not
1069      * zeroize because the metadata is not particularly sensitive. */
1070     memset(slot, 0, sizeof(*slot));
1071     return status;
1072 }
1073 
psa_destroy_key(mbedtls_svc_key_id_t key)1074 psa_status_t psa_destroy_key(mbedtls_svc_key_id_t key)
1075 {
1076     psa_key_slot_t *slot;
1077     psa_status_t status; /* status of the last operation */
1078     psa_status_t overall_status = PSA_SUCCESS;
1079 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1080     psa_se_drv_table_entry_t *driver;
1081 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1082 
1083     if (mbedtls_svc_key_id_is_null(key)) {
1084         return PSA_SUCCESS;
1085     }
1086 
1087     /*
1088      * Get the description of the key in a key slot. In case of a persistent
1089      * key, this will load the key description from persistent memory if not
1090      * done yet. We cannot avoid this loading as without it we don't know if
1091      * the key is operated by an SE or not and this information is needed by
1092      * the current implementation.
1093      */
1094     status = psa_get_and_lock_key_slot(key, &slot);
1095     if (status != PSA_SUCCESS) {
1096         return status;
1097     }
1098 
1099     /*
1100      * If the key slot containing the key description is under access by the
1101      * library (apart from the present access), the key cannot be destroyed
1102      * yet. For the time being, just return in error. Eventually (to be
1103      * implemented), the key should be destroyed when all accesses have
1104      * stopped.
1105      */
1106     if (slot->lock_count > 1) {
1107         psa_unlock_key_slot(slot);
1108         return PSA_ERROR_GENERIC_ERROR;
1109     }
1110 
1111     if (PSA_KEY_LIFETIME_IS_READ_ONLY(slot->attr.lifetime)) {
1112         /* Refuse the destruction of a read-only key (which may or may not work
1113          * if we attempt it, depending on whether the key is merely read-only
1114          * by policy or actually physically read-only).
1115          * Just do the best we can, which is to wipe the copy in memory
1116          * (done in this function's cleanup code). */
1117         overall_status = PSA_ERROR_NOT_PERMITTED;
1118         goto exit;
1119     }
1120 
1121 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1122     driver = psa_get_se_driver_entry(slot->attr.lifetime);
1123     if (driver != NULL) {
1124         /* For a key in a secure element, we need to do three things:
1125          * remove the key file in internal storage, destroy the
1126          * key inside the secure element, and update the driver's
1127          * persistent data. Start a transaction that will encompass these
1128          * three actions. */
1129         psa_crypto_prepare_transaction(PSA_CRYPTO_TRANSACTION_DESTROY_KEY);
1130         psa_crypto_transaction.key.lifetime = slot->attr.lifetime;
1131         psa_crypto_transaction.key.slot = psa_key_slot_get_slot_number(slot);
1132         psa_crypto_transaction.key.id = slot->attr.id;
1133         status = psa_crypto_save_transaction();
1134         if (status != PSA_SUCCESS) {
1135             (void) psa_crypto_stop_transaction();
1136             /* We should still try to destroy the key in the secure
1137              * element and the key metadata in storage. This is especially
1138              * important if the error is that the storage is full.
1139              * But how to do it exactly without risking an inconsistent
1140              * state after a reset?
1141              * https://github.com/ARMmbed/mbed-crypto/issues/215
1142              */
1143             overall_status = status;
1144             goto exit;
1145         }
1146 
1147         status = psa_destroy_se_key(driver,
1148                                     psa_key_slot_get_slot_number(slot));
1149         if (overall_status == PSA_SUCCESS) {
1150             overall_status = status;
1151         }
1152     }
1153 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1154 
1155 #if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C)
1156     if (!PSA_KEY_LIFETIME_IS_VOLATILE(slot->attr.lifetime)) {
1157         status = psa_destroy_persistent_key(slot->attr.id);
1158         if (overall_status == PSA_SUCCESS) {
1159             overall_status = status;
1160         }
1161 
1162         /* TODO: other slots may have a copy of the same key. We should
1163          * invalidate them.
1164          * https://github.com/ARMmbed/mbed-crypto/issues/214
1165          */
1166     }
1167 #endif /* defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) */
1168 
1169 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1170     if (driver != NULL) {
1171         status = psa_save_se_persistent_data(driver);
1172         if (overall_status == PSA_SUCCESS) {
1173             overall_status = status;
1174         }
1175         status = psa_crypto_stop_transaction();
1176         if (overall_status == PSA_SUCCESS) {
1177             overall_status = status;
1178         }
1179     }
1180 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1181 
1182 exit:
1183     status = psa_wipe_key_slot(slot);
1184     /* Prioritize CORRUPTION_DETECTED from wiping over a storage error */
1185     if (status != PSA_SUCCESS) {
1186         overall_status = status;
1187     }
1188     return overall_status;
1189 }
1190 
1191 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) || \
1192     defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY)
psa_get_rsa_public_exponent(const mbedtls_rsa_context * rsa,psa_key_attributes_t * attributes)1193 static psa_status_t psa_get_rsa_public_exponent(
1194     const mbedtls_rsa_context *rsa,
1195     psa_key_attributes_t *attributes)
1196 {
1197     mbedtls_mpi mpi;
1198     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1199     uint8_t *buffer = NULL;
1200     size_t buflen;
1201     mbedtls_mpi_init(&mpi);
1202 
1203     ret = mbedtls_rsa_export(rsa, NULL, NULL, NULL, NULL, &mpi);
1204     if (ret != 0) {
1205         goto exit;
1206     }
1207     if (mbedtls_mpi_cmp_int(&mpi, 65537) == 0) {
1208         /* It's the default value, which is reported as an empty string,
1209          * so there's nothing to do. */
1210         goto exit;
1211     }
1212 
1213     buflen = mbedtls_mpi_size(&mpi);
1214     buffer = mbedtls_calloc(1, buflen);
1215     if (buffer == NULL) {
1216         ret = MBEDTLS_ERR_MPI_ALLOC_FAILED;
1217         goto exit;
1218     }
1219     ret = mbedtls_mpi_write_binary(&mpi, buffer, buflen);
1220     if (ret != 0) {
1221         goto exit;
1222     }
1223     attributes->domain_parameters = buffer;
1224     attributes->domain_parameters_size = buflen;
1225 
1226 exit:
1227     mbedtls_mpi_free(&mpi);
1228     if (ret != 0) {
1229         mbedtls_free(buffer);
1230     }
1231     return mbedtls_to_psa_error(ret);
1232 }
1233 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) ||
1234         * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY) */
1235 
1236 /** Retrieve all the publicly-accessible attributes of a key.
1237  */
psa_get_key_attributes(mbedtls_svc_key_id_t key,psa_key_attributes_t * attributes)1238 psa_status_t psa_get_key_attributes(mbedtls_svc_key_id_t key,
1239                                     psa_key_attributes_t *attributes)
1240 {
1241     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
1242     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
1243     psa_key_slot_t *slot;
1244 
1245     psa_reset_key_attributes(attributes);
1246 
1247     status = psa_get_and_lock_key_slot_with_policy(key, &slot, 0, 0);
1248     if (status != PSA_SUCCESS) {
1249         return status;
1250     }
1251 
1252     attributes->core = slot->attr;
1253     attributes->core.flags &= (MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY |
1254                                MBEDTLS_PSA_KA_MASK_DUAL_USE);
1255 
1256 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1257     if (psa_get_se_driver_entry(slot->attr.lifetime) != NULL) {
1258         psa_set_key_slot_number(attributes,
1259                                 psa_key_slot_get_slot_number(slot));
1260     }
1261 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1262 
1263     switch (slot->attr.type) {
1264 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) || \
1265     defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY)
1266         case PSA_KEY_TYPE_RSA_KEY_PAIR:
1267         case PSA_KEY_TYPE_RSA_PUBLIC_KEY:
1268             /* TODO: reporting the public exponent for opaque keys
1269              * is not yet implemented.
1270              * https://github.com/ARMmbed/mbed-crypto/issues/216
1271              */
1272             if (!psa_key_lifetime_is_external(slot->attr.lifetime)) {
1273                 mbedtls_rsa_context *rsa = NULL;
1274 
1275                 status = mbedtls_psa_rsa_load_representation(
1276                     slot->attr.type,
1277                     slot->key.data,
1278                     slot->key.bytes,
1279                     &rsa);
1280                 if (status != PSA_SUCCESS) {
1281                     break;
1282                 }
1283 
1284                 status = psa_get_rsa_public_exponent(rsa,
1285                                                      attributes);
1286                 mbedtls_rsa_free(rsa);
1287                 mbedtls_free(rsa);
1288             }
1289             break;
1290 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) ||
1291         * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY) */
1292         default:
1293             /* Nothing else to do. */
1294             break;
1295     }
1296 
1297     if (status != PSA_SUCCESS) {
1298         psa_reset_key_attributes(attributes);
1299     }
1300 
1301     unlock_status = psa_unlock_key_slot(slot);
1302 
1303     return (status == PSA_SUCCESS) ? unlock_status : status;
1304 }
1305 
1306 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
psa_get_key_slot_number(const psa_key_attributes_t * attributes,psa_key_slot_number_t * slot_number)1307 psa_status_t psa_get_key_slot_number(
1308     const psa_key_attributes_t *attributes,
1309     psa_key_slot_number_t *slot_number)
1310 {
1311     if (attributes->core.flags & MBEDTLS_PSA_KA_FLAG_HAS_SLOT_NUMBER) {
1312         *slot_number = attributes->slot_number;
1313         return PSA_SUCCESS;
1314     } else {
1315         return PSA_ERROR_INVALID_ARGUMENT;
1316     }
1317 }
1318 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1319 
psa_export_key_buffer_internal(const uint8_t * key_buffer,size_t key_buffer_size,uint8_t * data,size_t data_size,size_t * data_length)1320 static psa_status_t psa_export_key_buffer_internal(const uint8_t *key_buffer,
1321                                                    size_t key_buffer_size,
1322                                                    uint8_t *data,
1323                                                    size_t data_size,
1324                                                    size_t *data_length)
1325 {
1326     if (key_buffer_size > data_size) {
1327         return PSA_ERROR_BUFFER_TOO_SMALL;
1328     }
1329     memcpy(data, key_buffer, key_buffer_size);
1330     memset(data + key_buffer_size, 0,
1331            data_size - key_buffer_size);
1332     *data_length = key_buffer_size;
1333     return PSA_SUCCESS;
1334 }
1335 
psa_export_key_internal(const psa_key_attributes_t * attributes,const uint8_t * key_buffer,size_t key_buffer_size,uint8_t * data,size_t data_size,size_t * data_length)1336 psa_status_t psa_export_key_internal(
1337     const psa_key_attributes_t *attributes,
1338     const uint8_t *key_buffer, size_t key_buffer_size,
1339     uint8_t *data, size_t data_size, size_t *data_length)
1340 {
1341     psa_key_type_t type = attributes->core.type;
1342 
1343     if (key_type_is_raw_bytes(type) ||
1344         PSA_KEY_TYPE_IS_RSA(type)   ||
1345         PSA_KEY_TYPE_IS_ECC(type)) {
1346         return psa_export_key_buffer_internal(
1347             key_buffer, key_buffer_size,
1348             data, data_size, data_length);
1349     } else {
1350         /* This shouldn't happen in the reference implementation, but
1351            it is valid for a special-purpose implementation to omit
1352            support for exporting certain key types. */
1353         return PSA_ERROR_NOT_SUPPORTED;
1354     }
1355 }
1356 
psa_export_key(mbedtls_svc_key_id_t key,uint8_t * data,size_t data_size,size_t * data_length)1357 psa_status_t psa_export_key(mbedtls_svc_key_id_t key,
1358                             uint8_t *data,
1359                             size_t data_size,
1360                             size_t *data_length)
1361 {
1362     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
1363     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
1364     psa_key_slot_t *slot;
1365 
1366     /* Reject a zero-length output buffer now, since this can never be a
1367      * valid key representation. This way we know that data must be a valid
1368      * pointer and we can do things like memset(data, ..., data_size). */
1369     if (data_size == 0) {
1370         return PSA_ERROR_BUFFER_TOO_SMALL;
1371     }
1372 
1373     /* Set the key to empty now, so that even when there are errors, we always
1374      * set data_length to a value between 0 and data_size. On error, setting
1375      * the key to empty is a good choice because an empty key representation is
1376      * unlikely to be accepted anywhere. */
1377     *data_length = 0;
1378 
1379     /* Export requires the EXPORT flag. There is an exception for public keys,
1380      * which don't require any flag, but
1381      * psa_get_and_lock_key_slot_with_policy() takes care of this.
1382      */
1383     status = psa_get_and_lock_key_slot_with_policy(key, &slot,
1384                                                    PSA_KEY_USAGE_EXPORT, 0);
1385     if (status != PSA_SUCCESS) {
1386         return status;
1387     }
1388 
1389     psa_key_attributes_t attributes = {
1390         .core = slot->attr
1391     };
1392     status = psa_driver_wrapper_export_key(&attributes,
1393                                            slot->key.data, slot->key.bytes,
1394                                            data, data_size, data_length);
1395 
1396     unlock_status = psa_unlock_key_slot(slot);
1397 
1398     return (status == PSA_SUCCESS) ? unlock_status : status;
1399 }
1400 
psa_export_public_key_internal(const psa_key_attributes_t * attributes,const uint8_t * key_buffer,size_t key_buffer_size,uint8_t * data,size_t data_size,size_t * data_length)1401 psa_status_t psa_export_public_key_internal(
1402     const psa_key_attributes_t *attributes,
1403     const uint8_t *key_buffer,
1404     size_t key_buffer_size,
1405     uint8_t *data,
1406     size_t data_size,
1407     size_t *data_length)
1408 {
1409     psa_key_type_t type = attributes->core.type;
1410 
1411     if (PSA_KEY_TYPE_IS_RSA(type) || PSA_KEY_TYPE_IS_ECC(type)) {
1412         if (PSA_KEY_TYPE_IS_PUBLIC_KEY(type)) {
1413             /* Exporting public -> public */
1414             return psa_export_key_buffer_internal(
1415                 key_buffer, key_buffer_size,
1416                 data, data_size, data_length);
1417         }
1418 
1419         if (PSA_KEY_TYPE_IS_RSA(type)) {
1420 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) || \
1421             defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY)
1422             return mbedtls_psa_rsa_export_public_key(attributes,
1423                                                      key_buffer,
1424                                                      key_buffer_size,
1425                                                      data,
1426                                                      data_size,
1427                                                      data_length);
1428 #else
1429             /* We don't know how to convert a private RSA key to public. */
1430             return PSA_ERROR_NOT_SUPPORTED;
1431 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) ||
1432         * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY) */
1433         } else {
1434 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) || \
1435             defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY)
1436             return mbedtls_psa_ecp_export_public_key(attributes,
1437                                                      key_buffer,
1438                                                      key_buffer_size,
1439                                                      data,
1440                                                      data_size,
1441                                                      data_length);
1442 #else
1443             /* We don't know how to convert a private ECC key to public */
1444             return PSA_ERROR_NOT_SUPPORTED;
1445 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) ||
1446         * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY) */
1447         }
1448     } else {
1449         /* This shouldn't happen in the reference implementation, but
1450            it is valid for a special-purpose implementation to omit
1451            support for exporting certain key types. */
1452         return PSA_ERROR_NOT_SUPPORTED;
1453     }
1454 }
1455 
psa_export_public_key(mbedtls_svc_key_id_t key,uint8_t * data,size_t data_size,size_t * data_length)1456 psa_status_t psa_export_public_key(mbedtls_svc_key_id_t key,
1457                                    uint8_t *data,
1458                                    size_t data_size,
1459                                    size_t *data_length)
1460 {
1461     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
1462     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
1463     psa_key_attributes_t attributes;
1464     psa_key_slot_t *slot;
1465 
1466     /* Reject a zero-length output buffer now, since this can never be a
1467      * valid key representation. This way we know that data must be a valid
1468      * pointer and we can do things like memset(data, ..., data_size). */
1469     if (data_size == 0) {
1470         return PSA_ERROR_BUFFER_TOO_SMALL;
1471     }
1472 
1473     /* Set the key to empty now, so that even when there are errors, we always
1474      * set data_length to a value between 0 and data_size. On error, setting
1475      * the key to empty is a good choice because an empty key representation is
1476      * unlikely to be accepted anywhere. */
1477     *data_length = 0;
1478 
1479     /* Exporting a public key doesn't require a usage flag. */
1480     status = psa_get_and_lock_key_slot_with_policy(key, &slot, 0, 0);
1481     if (status != PSA_SUCCESS) {
1482         return status;
1483     }
1484 
1485     if (!PSA_KEY_TYPE_IS_ASYMMETRIC(slot->attr.type)) {
1486         status = PSA_ERROR_INVALID_ARGUMENT;
1487         goto exit;
1488     }
1489 
1490     attributes = (psa_key_attributes_t) {
1491         .core = slot->attr
1492     };
1493     status = psa_driver_wrapper_export_public_key(
1494         &attributes, slot->key.data, slot->key.bytes,
1495         data, data_size, data_length);
1496 
1497 exit:
1498     unlock_status = psa_unlock_key_slot(slot);
1499 
1500     return (status == PSA_SUCCESS) ? unlock_status : status;
1501 }
1502 
1503 MBEDTLS_STATIC_ASSERT((MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY & MBEDTLS_PSA_KA_MASK_DUAL_USE) == 0,
1504                       "One or more key attribute flag is listed as both external-only and dual-use")
1505 MBEDTLS_STATIC_ASSERT((PSA_KA_MASK_INTERNAL_ONLY & MBEDTLS_PSA_KA_MASK_DUAL_USE) == 0,
1506                       "One or more key attribute flag is listed as both internal-only and dual-use")
1507 MBEDTLS_STATIC_ASSERT((PSA_KA_MASK_INTERNAL_ONLY & MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY) == 0,
1508                       "One or more key attribute flag is listed as both internal-only and external-only")
1509 
1510 /** Validate that a key policy is internally well-formed.
1511  *
1512  * This function only rejects invalid policies. It does not validate the
1513  * consistency of the policy with respect to other attributes of the key
1514  * such as the key type.
1515  */
psa_validate_key_policy(const psa_key_policy_t * policy)1516 static psa_status_t psa_validate_key_policy(const psa_key_policy_t *policy)
1517 {
1518     if ((policy->usage & ~(PSA_KEY_USAGE_EXPORT |
1519                            PSA_KEY_USAGE_COPY |
1520                            PSA_KEY_USAGE_ENCRYPT |
1521                            PSA_KEY_USAGE_DECRYPT |
1522                            PSA_KEY_USAGE_SIGN_MESSAGE |
1523                            PSA_KEY_USAGE_VERIFY_MESSAGE |
1524                            PSA_KEY_USAGE_SIGN_HASH |
1525                            PSA_KEY_USAGE_VERIFY_HASH |
1526                            PSA_KEY_USAGE_DERIVE)) != 0) {
1527         return PSA_ERROR_INVALID_ARGUMENT;
1528     }
1529 
1530     return PSA_SUCCESS;
1531 }
1532 
1533 /** Validate the internal consistency of key attributes.
1534  *
1535  * This function only rejects invalid attribute values. If does not
1536  * validate the consistency of the attributes with any key data that may
1537  * be involved in the creation of the key.
1538  *
1539  * Call this function early in the key creation process.
1540  *
1541  * \param[in] attributes    Key attributes for the new key.
1542  * \param[out] p_drv        On any return, the driver for the key, if any.
1543  *                          NULL for a transparent key.
1544  *
1545  */
psa_validate_key_attributes(const psa_key_attributes_t * attributes,psa_se_drv_table_entry_t ** p_drv)1546 static psa_status_t psa_validate_key_attributes(
1547     const psa_key_attributes_t *attributes,
1548     psa_se_drv_table_entry_t **p_drv)
1549 {
1550     psa_status_t status = PSA_ERROR_INVALID_ARGUMENT;
1551     psa_key_lifetime_t lifetime = psa_get_key_lifetime(attributes);
1552     mbedtls_svc_key_id_t key = psa_get_key_id(attributes);
1553 
1554     status = psa_validate_key_location(lifetime, p_drv);
1555     if (status != PSA_SUCCESS) {
1556         return status;
1557     }
1558 
1559     status = psa_validate_key_persistence(lifetime);
1560     if (status != PSA_SUCCESS) {
1561         return status;
1562     }
1563 
1564     if (PSA_KEY_LIFETIME_IS_VOLATILE(lifetime)) {
1565         if (MBEDTLS_SVC_KEY_ID_GET_KEY_ID(key) != 0) {
1566             return PSA_ERROR_INVALID_ARGUMENT;
1567         }
1568     } else {
1569         if (!psa_is_valid_key_id(psa_get_key_id(attributes), 0)) {
1570             return PSA_ERROR_INVALID_ARGUMENT;
1571         }
1572     }
1573 
1574     status = psa_validate_key_policy(&attributes->core.policy);
1575     if (status != PSA_SUCCESS) {
1576         return status;
1577     }
1578 
1579     /* Refuse to create overly large keys.
1580      * Note that this doesn't trigger on import if the attributes don't
1581      * explicitly specify a size (so psa_get_key_bits returns 0), so
1582      * psa_import_key() needs its own checks. */
1583     if (psa_get_key_bits(attributes) > PSA_MAX_KEY_BITS) {
1584         return PSA_ERROR_NOT_SUPPORTED;
1585     }
1586 
1587     /* Reject invalid flags. These should not be reachable through the API. */
1588     if (attributes->core.flags & ~(MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY |
1589                                    MBEDTLS_PSA_KA_MASK_DUAL_USE)) {
1590         return PSA_ERROR_INVALID_ARGUMENT;
1591     }
1592 
1593     return PSA_SUCCESS;
1594 }
1595 
1596 /** Prepare a key slot to receive key material.
1597  *
1598  * This function allocates a key slot and sets its metadata.
1599  *
1600  * If this function fails, call psa_fail_key_creation().
1601  *
1602  * This function is intended to be used as follows:
1603  * -# Call psa_start_key_creation() to allocate a key slot, prepare
1604  *    it with the specified attributes, and in case of a volatile key assign it
1605  *    a volatile key identifier.
1606  * -# Populate the slot with the key material.
1607  * -# Call psa_finish_key_creation() to finalize the creation of the slot.
1608  * In case of failure at any step, stop the sequence and call
1609  * psa_fail_key_creation().
1610  *
1611  * On success, the key slot is locked. It is the responsibility of the caller
1612  * to unlock the key slot when it does not access it anymore.
1613  *
1614  * \param method            An identification of the calling function.
1615  * \param[in] attributes    Key attributes for the new key.
1616  * \param[out] p_slot       On success, a pointer to the prepared slot.
1617  * \param[out] p_drv        On any return, the driver for the key, if any.
1618  *                          NULL for a transparent key.
1619  *
1620  * \retval #PSA_SUCCESS
1621  *         The key slot is ready to receive key material.
1622  * \return If this function fails, the key slot is an invalid state.
1623  *         You must call psa_fail_key_creation() to wipe and free the slot.
1624  */
psa_start_key_creation(psa_key_creation_method_t method,const psa_key_attributes_t * attributes,psa_key_slot_t ** p_slot,psa_se_drv_table_entry_t ** p_drv)1625 static psa_status_t psa_start_key_creation(
1626     psa_key_creation_method_t method,
1627     const psa_key_attributes_t *attributes,
1628     psa_key_slot_t **p_slot,
1629     psa_se_drv_table_entry_t **p_drv)
1630 {
1631     psa_status_t status;
1632     psa_key_id_t volatile_key_id;
1633     psa_key_slot_t *slot;
1634 
1635     (void) method;
1636     *p_drv = NULL;
1637 
1638     status = psa_validate_key_attributes(attributes, p_drv);
1639     if (status != PSA_SUCCESS) {
1640         return status;
1641     }
1642 
1643     status = psa_get_empty_key_slot(&volatile_key_id, p_slot);
1644     if (status != PSA_SUCCESS) {
1645         return status;
1646     }
1647     slot = *p_slot;
1648 
1649     /* We're storing the declared bit-size of the key. It's up to each
1650      * creation mechanism to verify that this information is correct.
1651      * It's automatically correct for mechanisms that use the bit-size as
1652      * an input (generate, device) but not for those where the bit-size
1653      * is optional (import, copy). In case of a volatile key, assign it the
1654      * volatile key identifier associated to the slot returned to contain its
1655      * definition. */
1656 
1657     slot->attr = attributes->core;
1658     if (PSA_KEY_LIFETIME_IS_VOLATILE(slot->attr.lifetime)) {
1659 #if !defined(MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER)
1660         slot->attr.id = volatile_key_id;
1661 #else
1662         slot->attr.id.key_id = volatile_key_id;
1663 #endif
1664     }
1665 
1666     /* Erase external-only flags from the internal copy. To access
1667      * external-only flags, query `attributes`. Thanks to the check
1668      * in psa_validate_key_attributes(), this leaves the dual-use
1669      * flags and any internal flag that psa_get_empty_key_slot()
1670      * may have set. */
1671     slot->attr.flags &= ~MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY;
1672 
1673 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1674     /* For a key in a secure element, we need to do three things
1675      * when creating or registering a persistent key:
1676      * create the key file in internal storage, create the
1677      * key inside the secure element, and update the driver's
1678      * persistent data. This is done by starting a transaction that will
1679      * encompass these three actions.
1680      * For registering a volatile key, we just need to find an appropriate
1681      * slot number inside the SE. Since the key is designated volatile, creating
1682      * a transaction is not required. */
1683     /* The first thing to do is to find a slot number for the new key.
1684      * We save the slot number in persistent storage as part of the
1685      * transaction data. It will be needed to recover if the power
1686      * fails during the key creation process, to clean up on the secure
1687      * element side after restarting. Obtaining a slot number from the
1688      * secure element driver updates its persistent state, but we do not yet
1689      * save the driver's persistent state, so that if the power fails,
1690      * we can roll back to a state where the key doesn't exist. */
1691     if (*p_drv != NULL) {
1692         psa_key_slot_number_t slot_number;
1693         status = psa_find_se_slot_for_key(attributes, method, *p_drv,
1694                                           &slot_number);
1695         if (status != PSA_SUCCESS) {
1696             return status;
1697         }
1698 
1699         if (!PSA_KEY_LIFETIME_IS_VOLATILE(attributes->core.lifetime)) {
1700             psa_crypto_prepare_transaction(PSA_CRYPTO_TRANSACTION_CREATE_KEY);
1701             psa_crypto_transaction.key.lifetime = slot->attr.lifetime;
1702             psa_crypto_transaction.key.slot = slot_number;
1703             psa_crypto_transaction.key.id = slot->attr.id;
1704             status = psa_crypto_save_transaction();
1705             if (status != PSA_SUCCESS) {
1706                 (void) psa_crypto_stop_transaction();
1707                 return status;
1708             }
1709         }
1710 
1711         status = psa_copy_key_material_into_slot(
1712             slot, (uint8_t *) (&slot_number), sizeof(slot_number));
1713     }
1714 
1715     if (*p_drv == NULL && method == PSA_KEY_CREATION_REGISTER) {
1716         /* Key registration only makes sense with a secure element. */
1717         return PSA_ERROR_INVALID_ARGUMENT;
1718     }
1719 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1720 
1721     return PSA_SUCCESS;
1722 }
1723 
1724 /** Finalize the creation of a key once its key material has been set.
1725  *
1726  * This entails writing the key to persistent storage.
1727  *
1728  * If this function fails, call psa_fail_key_creation().
1729  * See the documentation of psa_start_key_creation() for the intended use
1730  * of this function.
1731  *
1732  * If the finalization succeeds, the function unlocks the key slot (it was
1733  * locked by psa_start_key_creation()) and the key slot cannot be accessed
1734  * anymore as part of the key creation process.
1735  *
1736  * \param[in,out] slot  Pointer to the slot with key material.
1737  * \param[in] driver    The secure element driver for the key,
1738  *                      or NULL for a transparent key.
1739  * \param[out] key      On success, identifier of the key. Note that the
1740  *                      key identifier is also stored in the key slot.
1741  *
1742  * \retval #PSA_SUCCESS
1743  *         The key was successfully created.
1744  * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
1745  * \retval #PSA_ERROR_INSUFFICIENT_STORAGE \emptydescription
1746  * \retval #PSA_ERROR_ALREADY_EXISTS \emptydescription
1747  * \retval #PSA_ERROR_DATA_INVALID \emptydescription
1748  * \retval #PSA_ERROR_DATA_CORRUPT \emptydescription
1749  * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
1750  *
1751  * \return If this function fails, the key slot is an invalid state.
1752  *         You must call psa_fail_key_creation() to wipe and free the slot.
1753  */
psa_finish_key_creation(psa_key_slot_t * slot,psa_se_drv_table_entry_t * driver,mbedtls_svc_key_id_t * key)1754 static psa_status_t psa_finish_key_creation(
1755     psa_key_slot_t *slot,
1756     psa_se_drv_table_entry_t *driver,
1757     mbedtls_svc_key_id_t *key)
1758 {
1759     psa_status_t status = PSA_SUCCESS;
1760     (void) slot;
1761     (void) driver;
1762 
1763 #if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C)
1764     if (!PSA_KEY_LIFETIME_IS_VOLATILE(slot->attr.lifetime)) {
1765 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1766         if (driver != NULL) {
1767             psa_se_key_data_storage_t data;
1768             psa_key_slot_number_t slot_number =
1769                 psa_key_slot_get_slot_number(slot);
1770 
1771             MBEDTLS_STATIC_ASSERT(sizeof(slot_number) ==
1772                                   sizeof(data.slot_number),
1773                                   "Slot number size does not match psa_se_key_data_storage_t");
1774 
1775             memcpy(&data.slot_number, &slot_number, sizeof(slot_number));
1776             status = psa_save_persistent_key(&slot->attr,
1777                                              (uint8_t *) &data,
1778                                              sizeof(data));
1779         } else
1780 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1781         {
1782             /* Key material is saved in export representation in the slot, so
1783              * just pass the slot buffer for storage. */
1784             status = psa_save_persistent_key(&slot->attr,
1785                                              slot->key.data,
1786                                              slot->key.bytes);
1787         }
1788     }
1789 #endif /* defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) */
1790 
1791 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1792     /* Finish the transaction for a key creation. This does not
1793      * happen when registering an existing key. Detect this case
1794      * by checking whether a transaction is in progress (actual
1795      * creation of a persistent key in a secure element requires a transaction,
1796      * but registration or volatile key creation doesn't use one). */
1797     if (driver != NULL &&
1798         psa_crypto_transaction.unknown.type == PSA_CRYPTO_TRANSACTION_CREATE_KEY) {
1799         status = psa_save_se_persistent_data(driver);
1800         if (status != PSA_SUCCESS) {
1801             psa_destroy_persistent_key(slot->attr.id);
1802             return status;
1803         }
1804         status = psa_crypto_stop_transaction();
1805     }
1806 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1807 
1808     if (status == PSA_SUCCESS) {
1809         *key = slot->attr.id;
1810         status = psa_unlock_key_slot(slot);
1811         if (status != PSA_SUCCESS) {
1812             *key = MBEDTLS_SVC_KEY_ID_INIT;
1813         }
1814     }
1815 
1816     return status;
1817 }
1818 
1819 /** Abort the creation of a key.
1820  *
1821  * You may call this function after calling psa_start_key_creation(),
1822  * or after psa_finish_key_creation() fails. In other circumstances, this
1823  * function may not clean up persistent storage.
1824  * See the documentation of psa_start_key_creation() for the intended use
1825  * of this function.
1826  *
1827  * \param[in,out] slot  Pointer to the slot with key material.
1828  * \param[in] driver    The secure element driver for the key,
1829  *                      or NULL for a transparent key.
1830  */
psa_fail_key_creation(psa_key_slot_t * slot,psa_se_drv_table_entry_t * driver)1831 static void psa_fail_key_creation(psa_key_slot_t *slot,
1832                                   psa_se_drv_table_entry_t *driver)
1833 {
1834     (void) driver;
1835 
1836     if (slot == NULL) {
1837         return;
1838     }
1839 
1840 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
1841     /* TODO: If the key has already been created in the secure
1842      * element, and the failure happened later (when saving metadata
1843      * to internal storage), we need to destroy the key in the secure
1844      * element.
1845      * https://github.com/ARMmbed/mbed-crypto/issues/217
1846      */
1847 
1848     /* Abort the ongoing transaction if any (there may not be one if
1849      * the creation process failed before starting one, or if the
1850      * key creation is a registration of a key in a secure element).
1851      * Earlier functions must already have done what it takes to undo any
1852      * partial creation. All that's left is to update the transaction data
1853      * itself. */
1854     (void) psa_crypto_stop_transaction();
1855 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
1856 
1857     psa_wipe_key_slot(slot);
1858 }
1859 
1860 /** Validate optional attributes during key creation.
1861  *
1862  * Some key attributes are optional during key creation. If they are
1863  * specified in the attributes structure, check that they are consistent
1864  * with the data in the slot.
1865  *
1866  * This function should be called near the end of key creation, after
1867  * the slot in memory is fully populated but before saving persistent data.
1868  */
psa_validate_optional_attributes(const psa_key_slot_t * slot,const psa_key_attributes_t * attributes)1869 static psa_status_t psa_validate_optional_attributes(
1870     const psa_key_slot_t *slot,
1871     const psa_key_attributes_t *attributes)
1872 {
1873     if (attributes->core.type != 0) {
1874         if (attributes->core.type != slot->attr.type) {
1875             return PSA_ERROR_INVALID_ARGUMENT;
1876         }
1877     }
1878 
1879     if (attributes->domain_parameters_size != 0) {
1880 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) || \
1881         defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY)
1882         if (PSA_KEY_TYPE_IS_RSA(slot->attr.type)) {
1883             mbedtls_rsa_context *rsa = NULL;
1884             mbedtls_mpi actual, required;
1885             int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1886 
1887             psa_status_t status = mbedtls_psa_rsa_load_representation(
1888                 slot->attr.type,
1889                 slot->key.data,
1890                 slot->key.bytes,
1891                 &rsa);
1892             if (status != PSA_SUCCESS) {
1893                 return status;
1894             }
1895 
1896             mbedtls_mpi_init(&actual);
1897             mbedtls_mpi_init(&required);
1898             ret = mbedtls_rsa_export(rsa,
1899                                      NULL, NULL, NULL, NULL, &actual);
1900             mbedtls_rsa_free(rsa);
1901             mbedtls_free(rsa);
1902             if (ret != 0) {
1903                 goto rsa_exit;
1904             }
1905             ret = mbedtls_mpi_read_binary(&required,
1906                                           attributes->domain_parameters,
1907                                           attributes->domain_parameters_size);
1908             if (ret != 0) {
1909                 goto rsa_exit;
1910             }
1911             if (mbedtls_mpi_cmp_mpi(&actual, &required) != 0) {
1912                 ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1913             }
1914 rsa_exit:
1915             mbedtls_mpi_free(&actual);
1916             mbedtls_mpi_free(&required);
1917             if (ret != 0) {
1918                 return mbedtls_to_psa_error(ret);
1919             }
1920         } else
1921 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) ||
1922         * defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY) */
1923         {
1924             return PSA_ERROR_INVALID_ARGUMENT;
1925         }
1926     }
1927 
1928     if (attributes->core.bits != 0) {
1929         if (attributes->core.bits != slot->attr.bits) {
1930             return PSA_ERROR_INVALID_ARGUMENT;
1931         }
1932     }
1933 
1934     return PSA_SUCCESS;
1935 }
1936 
psa_import_key(const psa_key_attributes_t * attributes,const uint8_t * data,size_t data_length,mbedtls_svc_key_id_t * key)1937 psa_status_t psa_import_key(const psa_key_attributes_t *attributes,
1938                             const uint8_t *data,
1939                             size_t data_length,
1940                             mbedtls_svc_key_id_t *key)
1941 {
1942     psa_status_t status;
1943     psa_key_slot_t *slot = NULL;
1944     psa_se_drv_table_entry_t *driver = NULL;
1945     size_t bits;
1946 
1947     *key = MBEDTLS_SVC_KEY_ID_INIT;
1948 
1949     /* Reject zero-length symmetric keys (including raw data key objects).
1950      * This also rejects any key which might be encoded as an empty string,
1951      * which is never valid. */
1952     if (data_length == 0) {
1953         return PSA_ERROR_INVALID_ARGUMENT;
1954     }
1955 
1956     status = psa_start_key_creation(PSA_KEY_CREATION_IMPORT, attributes,
1957                                     &slot, &driver);
1958     if (status != PSA_SUCCESS) {
1959         goto exit;
1960     }
1961 
1962     /* In the case of a transparent key or an opaque key stored in local
1963      * storage (thus not in the case of generating a key in a secure element
1964      * or cryptoprocessor with storage), we have to allocate a buffer to
1965      * hold the generated key material. */
1966     if (slot->key.data == NULL) {
1967         status = psa_allocate_buffer_to_slot(slot, data_length);
1968         if (status != PSA_SUCCESS) {
1969             goto exit;
1970         }
1971     }
1972 
1973     bits = slot->attr.bits;
1974     status = psa_driver_wrapper_import_key(attributes,
1975                                            data, data_length,
1976                                            slot->key.data,
1977                                            slot->key.bytes,
1978                                            &slot->key.bytes, &bits);
1979     if (status != PSA_SUCCESS) {
1980         goto exit;
1981     }
1982 
1983     if (slot->attr.bits == 0) {
1984         slot->attr.bits = (psa_key_bits_t) bits;
1985     } else if (bits != slot->attr.bits) {
1986         status = PSA_ERROR_INVALID_ARGUMENT;
1987         goto exit;
1988     }
1989 
1990     status = psa_validate_optional_attributes(slot, attributes);
1991     if (status != PSA_SUCCESS) {
1992         goto exit;
1993     }
1994 
1995     status = psa_finish_key_creation(slot, driver, key);
1996 exit:
1997     if (status != PSA_SUCCESS) {
1998         psa_fail_key_creation(slot, driver);
1999     }
2000 
2001     return status;
2002 }
2003 
2004 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
mbedtls_psa_register_se_key(const psa_key_attributes_t * attributes)2005 psa_status_t mbedtls_psa_register_se_key(
2006     const psa_key_attributes_t *attributes)
2007 {
2008     psa_status_t status;
2009     psa_key_slot_t *slot = NULL;
2010     psa_se_drv_table_entry_t *driver = NULL;
2011     mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
2012 
2013     /* Leaving attributes unspecified is not currently supported.
2014      * It could make sense to query the key type and size from the
2015      * secure element, but not all secure elements support this
2016      * and the driver HAL doesn't currently support it. */
2017     if (psa_get_key_type(attributes) == PSA_KEY_TYPE_NONE) {
2018         return PSA_ERROR_NOT_SUPPORTED;
2019     }
2020     if (psa_get_key_bits(attributes) == 0) {
2021         return PSA_ERROR_NOT_SUPPORTED;
2022     }
2023 
2024     status = psa_start_key_creation(PSA_KEY_CREATION_REGISTER, attributes,
2025                                     &slot, &driver);
2026     if (status != PSA_SUCCESS) {
2027         goto exit;
2028     }
2029 
2030     status = psa_finish_key_creation(slot, driver, &key);
2031 
2032 exit:
2033     if (status != PSA_SUCCESS) {
2034         psa_fail_key_creation(slot, driver);
2035     }
2036 
2037     /* Registration doesn't keep the key in RAM. */
2038     psa_close_key(key);
2039     return status;
2040 }
2041 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
2042 
psa_copy_key_material(const psa_key_slot_t * source,psa_key_slot_t * target)2043 static psa_status_t psa_copy_key_material(const psa_key_slot_t *source,
2044                                           psa_key_slot_t *target)
2045 {
2046     psa_status_t status = psa_copy_key_material_into_slot(target,
2047                                                           source->key.data,
2048                                                           source->key.bytes);
2049     if (status != PSA_SUCCESS) {
2050         return status;
2051     }
2052 
2053     target->attr.type = source->attr.type;
2054     target->attr.bits = source->attr.bits;
2055 
2056     return PSA_SUCCESS;
2057 }
2058 
psa_copy_key(mbedtls_svc_key_id_t source_key,const psa_key_attributes_t * specified_attributes,mbedtls_svc_key_id_t * target_key)2059 psa_status_t psa_copy_key(mbedtls_svc_key_id_t source_key,
2060                           const psa_key_attributes_t *specified_attributes,
2061                           mbedtls_svc_key_id_t *target_key)
2062 {
2063     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2064     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
2065     psa_key_slot_t *source_slot = NULL;
2066     psa_key_slot_t *target_slot = NULL;
2067     psa_key_attributes_t actual_attributes = *specified_attributes;
2068     psa_se_drv_table_entry_t *driver = NULL;
2069 
2070     *target_key = MBEDTLS_SVC_KEY_ID_INIT;
2071 
2072     status = psa_get_and_lock_transparent_key_slot_with_policy(
2073         source_key, &source_slot, PSA_KEY_USAGE_COPY, 0);
2074     if (status != PSA_SUCCESS) {
2075         goto exit;
2076     }
2077 
2078     status = psa_validate_optional_attributes(source_slot,
2079                                               specified_attributes);
2080     if (status != PSA_SUCCESS) {
2081         goto exit;
2082     }
2083 
2084     status = psa_restrict_key_policy(source_slot->attr.type,
2085                                      &actual_attributes.core.policy,
2086                                      &source_slot->attr.policy);
2087     if (status != PSA_SUCCESS) {
2088         goto exit;
2089     }
2090 
2091     status = psa_start_key_creation(PSA_KEY_CREATION_COPY, &actual_attributes,
2092                                     &target_slot, &driver);
2093     if (status != PSA_SUCCESS) {
2094         goto exit;
2095     }
2096 
2097 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
2098     if (driver != NULL) {
2099         /* Copying to a secure element is not implemented yet. */
2100         status = PSA_ERROR_NOT_SUPPORTED;
2101         goto exit;
2102     }
2103 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
2104 
2105     if (psa_key_lifetime_is_external(actual_attributes.core.lifetime)) {
2106         /*
2107          * Copying through an opaque driver is not implemented yet, consider
2108          * a lifetime with an external location as an invalid parameter for
2109          * now.
2110          */
2111         status = PSA_ERROR_INVALID_ARGUMENT;
2112         goto exit;
2113     }
2114 
2115     status = psa_copy_key_material(source_slot, target_slot);
2116     if (status != PSA_SUCCESS) {
2117         goto exit;
2118     }
2119 
2120     status = psa_finish_key_creation(target_slot, driver, target_key);
2121 exit:
2122     if (status != PSA_SUCCESS) {
2123         psa_fail_key_creation(target_slot, driver);
2124     }
2125 
2126     unlock_status = psa_unlock_key_slot(source_slot);
2127 
2128     return (status == PSA_SUCCESS) ? unlock_status : status;
2129 }
2130 
2131 
2132 
2133 /****************************************************************/
2134 /* Message digests */
2135 /****************************************************************/
2136 
psa_hash_abort(psa_hash_operation_t * operation)2137 psa_status_t psa_hash_abort(psa_hash_operation_t *operation)
2138 {
2139     /* Aborting a non-active operation is allowed */
2140     if (operation->id == 0) {
2141         return PSA_SUCCESS;
2142     }
2143 
2144     psa_status_t status = psa_driver_wrapper_hash_abort(operation);
2145     operation->id = 0;
2146 
2147     return status;
2148 }
2149 
psa_hash_setup(psa_hash_operation_t * operation,psa_algorithm_t alg)2150 psa_status_t psa_hash_setup(psa_hash_operation_t *operation,
2151                             psa_algorithm_t alg)
2152 {
2153     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2154 
2155     /* A context must be freshly initialized before it can be set up. */
2156     if (operation->id != 0) {
2157         status = PSA_ERROR_BAD_STATE;
2158         goto exit;
2159     }
2160 
2161     if (!PSA_ALG_IS_HASH(alg)) {
2162         status = PSA_ERROR_INVALID_ARGUMENT;
2163         goto exit;
2164     }
2165 
2166     /* Ensure all of the context is zeroized, since PSA_HASH_OPERATION_INIT only
2167      * directly zeroes the int-sized dummy member of the context union. */
2168     memset(&operation->ctx, 0, sizeof(operation->ctx));
2169 
2170     status = psa_driver_wrapper_hash_setup(operation, alg);
2171 
2172 exit:
2173     if (status != PSA_SUCCESS) {
2174         psa_hash_abort(operation);
2175     }
2176 
2177     return status;
2178 }
2179 
psa_hash_update(psa_hash_operation_t * operation,const uint8_t * input,size_t input_length)2180 psa_status_t psa_hash_update(psa_hash_operation_t *operation,
2181                              const uint8_t *input,
2182                              size_t input_length)
2183 {
2184     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2185 
2186     if (operation->id == 0) {
2187         status = PSA_ERROR_BAD_STATE;
2188         goto exit;
2189     }
2190 
2191     /* Don't require hash implementations to behave correctly on a
2192      * zero-length input, which may have an invalid pointer. */
2193     if (input_length == 0) {
2194         return PSA_SUCCESS;
2195     }
2196 
2197     status = psa_driver_wrapper_hash_update(operation, input, input_length);
2198 
2199 exit:
2200     if (status != PSA_SUCCESS) {
2201         psa_hash_abort(operation);
2202     }
2203 
2204     return status;
2205 }
2206 
psa_hash_finish(psa_hash_operation_t * operation,uint8_t * hash,size_t hash_size,size_t * hash_length)2207 psa_status_t psa_hash_finish(psa_hash_operation_t *operation,
2208                              uint8_t *hash,
2209                              size_t hash_size,
2210                              size_t *hash_length)
2211 {
2212     *hash_length = 0;
2213     if (operation->id == 0) {
2214         return PSA_ERROR_BAD_STATE;
2215     }
2216 
2217     psa_status_t status = psa_driver_wrapper_hash_finish(
2218         operation, hash, hash_size, hash_length);
2219     psa_hash_abort(operation);
2220     return status;
2221 }
2222 
psa_hash_verify(psa_hash_operation_t * operation,const uint8_t * hash,size_t hash_length)2223 psa_status_t psa_hash_verify(psa_hash_operation_t *operation,
2224                              const uint8_t *hash,
2225                              size_t hash_length)
2226 {
2227     uint8_t actual_hash[PSA_HASH_MAX_SIZE];
2228     size_t actual_hash_length;
2229     psa_status_t status = psa_hash_finish(
2230         operation,
2231         actual_hash, sizeof(actual_hash),
2232         &actual_hash_length);
2233 
2234     if (status != PSA_SUCCESS) {
2235         goto exit;
2236     }
2237 
2238     if (actual_hash_length != hash_length) {
2239         status = PSA_ERROR_INVALID_SIGNATURE;
2240         goto exit;
2241     }
2242 
2243     if (mbedtls_psa_safer_memcmp(hash, actual_hash, actual_hash_length) != 0) {
2244         status = PSA_ERROR_INVALID_SIGNATURE;
2245     }
2246 
2247 exit:
2248     mbedtls_platform_zeroize(actual_hash, sizeof(actual_hash));
2249     if (status != PSA_SUCCESS) {
2250         psa_hash_abort(operation);
2251     }
2252 
2253     return status;
2254 }
2255 
psa_hash_compute(psa_algorithm_t alg,const uint8_t * input,size_t input_length,uint8_t * hash,size_t hash_size,size_t * hash_length)2256 psa_status_t psa_hash_compute(psa_algorithm_t alg,
2257                               const uint8_t *input, size_t input_length,
2258                               uint8_t *hash, size_t hash_size,
2259                               size_t *hash_length)
2260 {
2261     *hash_length = 0;
2262     if (!PSA_ALG_IS_HASH(alg)) {
2263         return PSA_ERROR_INVALID_ARGUMENT;
2264     }
2265 
2266     return psa_driver_wrapper_hash_compute(alg, input, input_length,
2267                                            hash, hash_size, hash_length);
2268 }
2269 
psa_hash_compare(psa_algorithm_t alg,const uint8_t * input,size_t input_length,const uint8_t * hash,size_t hash_length)2270 psa_status_t psa_hash_compare(psa_algorithm_t alg,
2271                               const uint8_t *input, size_t input_length,
2272                               const uint8_t *hash, size_t hash_length)
2273 {
2274     uint8_t actual_hash[PSA_HASH_MAX_SIZE];
2275     size_t actual_hash_length;
2276 
2277     if (!PSA_ALG_IS_HASH(alg)) {
2278         return PSA_ERROR_INVALID_ARGUMENT;
2279     }
2280 
2281     psa_status_t status = psa_driver_wrapper_hash_compute(
2282         alg, input, input_length,
2283         actual_hash, sizeof(actual_hash),
2284         &actual_hash_length);
2285     if (status != PSA_SUCCESS) {
2286         goto exit;
2287     }
2288     if (actual_hash_length != hash_length) {
2289         status = PSA_ERROR_INVALID_SIGNATURE;
2290         goto exit;
2291     }
2292     if (mbedtls_psa_safer_memcmp(hash, actual_hash, actual_hash_length) != 0) {
2293         status = PSA_ERROR_INVALID_SIGNATURE;
2294     }
2295 
2296 exit:
2297     mbedtls_platform_zeroize(actual_hash, sizeof(actual_hash));
2298     return status;
2299 }
2300 
psa_hash_clone(const psa_hash_operation_t * source_operation,psa_hash_operation_t * target_operation)2301 psa_status_t psa_hash_clone(const psa_hash_operation_t *source_operation,
2302                             psa_hash_operation_t *target_operation)
2303 {
2304     if (source_operation->id == 0 ||
2305         target_operation->id != 0) {
2306         return PSA_ERROR_BAD_STATE;
2307     }
2308 
2309     psa_status_t status = psa_driver_wrapper_hash_clone(source_operation,
2310                                                         target_operation);
2311     if (status != PSA_SUCCESS) {
2312         psa_hash_abort(target_operation);
2313     }
2314 
2315     return status;
2316 }
2317 
2318 
2319 /****************************************************************/
2320 /* MAC */
2321 /****************************************************************/
2322 
psa_mac_abort(psa_mac_operation_t * operation)2323 psa_status_t psa_mac_abort(psa_mac_operation_t *operation)
2324 {
2325     /* Aborting a non-active operation is allowed */
2326     if (operation->id == 0) {
2327         return PSA_SUCCESS;
2328     }
2329 
2330     psa_status_t status = psa_driver_wrapper_mac_abort(operation);
2331     operation->mac_size = 0;
2332     operation->is_sign = 0;
2333     operation->id = 0;
2334 
2335     return status;
2336 }
2337 
psa_mac_finalize_alg_and_key_validation(psa_algorithm_t alg,const psa_key_attributes_t * attributes,uint8_t * mac_size)2338 static psa_status_t psa_mac_finalize_alg_and_key_validation(
2339     psa_algorithm_t alg,
2340     const psa_key_attributes_t *attributes,
2341     uint8_t *mac_size)
2342 {
2343     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2344     psa_key_type_t key_type = psa_get_key_type(attributes);
2345     size_t key_bits = psa_get_key_bits(attributes);
2346 
2347     if (!PSA_ALG_IS_MAC(alg)) {
2348         return PSA_ERROR_INVALID_ARGUMENT;
2349     }
2350 
2351     /* Validate the combination of key type and algorithm */
2352     status = psa_mac_key_can_do(alg, key_type);
2353     if (status != PSA_SUCCESS) {
2354         return status;
2355     }
2356 
2357     /* Get the output length for the algorithm and key combination */
2358     *mac_size = PSA_MAC_LENGTH(key_type, key_bits, alg);
2359 
2360     if (*mac_size < 4) {
2361         /* A very short MAC is too short for security since it can be
2362          * brute-forced. Ancient protocols with 32-bit MACs do exist,
2363          * so we make this our minimum, even though 32 bits is still
2364          * too small for security. */
2365         return PSA_ERROR_NOT_SUPPORTED;
2366     }
2367 
2368     if (*mac_size > PSA_MAC_LENGTH(key_type, key_bits,
2369                                    PSA_ALG_FULL_LENGTH_MAC(alg))) {
2370         /* It's impossible to "truncate" to a larger length than the full length
2371          * of the algorithm. */
2372         return PSA_ERROR_INVALID_ARGUMENT;
2373     }
2374 
2375     if (*mac_size > PSA_MAC_MAX_SIZE) {
2376         /* PSA_MAC_LENGTH returns the correct length even for a MAC algorithm
2377          * that is disabled in the compile-time configuration. The result can
2378          * therefore be larger than PSA_MAC_MAX_SIZE, which does take the
2379          * configuration into account. In this case, force a return of
2380          * PSA_ERROR_NOT_SUPPORTED here. Otherwise psa_mac_verify(), or
2381          * psa_mac_compute(mac_size=PSA_MAC_MAX_SIZE), would return
2382          * PSA_ERROR_BUFFER_TOO_SMALL for an unsupported algorithm whose MAC size
2383          * is larger than PSA_MAC_MAX_SIZE, which is misleading and which breaks
2384          * systematically generated tests. */
2385         return PSA_ERROR_NOT_SUPPORTED;
2386     }
2387 
2388     return PSA_SUCCESS;
2389 }
2390 
psa_mac_setup(psa_mac_operation_t * operation,mbedtls_svc_key_id_t key,psa_algorithm_t alg,int is_sign)2391 static psa_status_t psa_mac_setup(psa_mac_operation_t *operation,
2392                                   mbedtls_svc_key_id_t key,
2393                                   psa_algorithm_t alg,
2394                                   int is_sign)
2395 {
2396     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2397     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
2398     psa_key_attributes_t attributes;
2399     psa_key_slot_t *slot = NULL;
2400 
2401     /* A context must be freshly initialized before it can be set up. */
2402     if (operation->id != 0) {
2403         status = PSA_ERROR_BAD_STATE;
2404         goto exit;
2405     }
2406 
2407     status = psa_get_and_lock_key_slot_with_policy(
2408         key,
2409         &slot,
2410         is_sign ? PSA_KEY_USAGE_SIGN_MESSAGE : PSA_KEY_USAGE_VERIFY_MESSAGE,
2411         alg);
2412     if (status != PSA_SUCCESS) {
2413         goto exit;
2414     }
2415 
2416     attributes = (psa_key_attributes_t) {
2417         .core = slot->attr
2418     };
2419 
2420     status = psa_mac_finalize_alg_and_key_validation(alg, &attributes,
2421                                                      &operation->mac_size);
2422     if (status != PSA_SUCCESS) {
2423         goto exit;
2424     }
2425 
2426     operation->is_sign = is_sign;
2427     /* Dispatch the MAC setup call with validated input */
2428     if (is_sign) {
2429         status = psa_driver_wrapper_mac_sign_setup(operation,
2430                                                    &attributes,
2431                                                    slot->key.data,
2432                                                    slot->key.bytes,
2433                                                    alg);
2434     } else {
2435         status = psa_driver_wrapper_mac_verify_setup(operation,
2436                                                      &attributes,
2437                                                      slot->key.data,
2438                                                      slot->key.bytes,
2439                                                      alg);
2440     }
2441 
2442 exit:
2443     if (status != PSA_SUCCESS) {
2444         psa_mac_abort(operation);
2445     }
2446 
2447     unlock_status = psa_unlock_key_slot(slot);
2448 
2449     return (status == PSA_SUCCESS) ? unlock_status : status;
2450 }
2451 
psa_mac_sign_setup(psa_mac_operation_t * operation,mbedtls_svc_key_id_t key,psa_algorithm_t alg)2452 psa_status_t psa_mac_sign_setup(psa_mac_operation_t *operation,
2453                                 mbedtls_svc_key_id_t key,
2454                                 psa_algorithm_t alg)
2455 {
2456     return psa_mac_setup(operation, key, alg, 1);
2457 }
2458 
psa_mac_verify_setup(psa_mac_operation_t * operation,mbedtls_svc_key_id_t key,psa_algorithm_t alg)2459 psa_status_t psa_mac_verify_setup(psa_mac_operation_t *operation,
2460                                   mbedtls_svc_key_id_t key,
2461                                   psa_algorithm_t alg)
2462 {
2463     return psa_mac_setup(operation, key, alg, 0);
2464 }
2465 
psa_mac_update(psa_mac_operation_t * operation,const uint8_t * input,size_t input_length)2466 psa_status_t psa_mac_update(psa_mac_operation_t *operation,
2467                             const uint8_t *input,
2468                             size_t input_length)
2469 {
2470     if (operation->id == 0) {
2471         return PSA_ERROR_BAD_STATE;
2472     }
2473 
2474     /* Don't require hash implementations to behave correctly on a
2475      * zero-length input, which may have an invalid pointer. */
2476     if (input_length == 0) {
2477         return PSA_SUCCESS;
2478     }
2479 
2480     psa_status_t status = psa_driver_wrapper_mac_update(operation,
2481                                                         input, input_length);
2482     if (status != PSA_SUCCESS) {
2483         psa_mac_abort(operation);
2484     }
2485 
2486     return status;
2487 }
2488 
psa_mac_sign_finish(psa_mac_operation_t * operation,uint8_t * mac,size_t mac_size,size_t * mac_length)2489 psa_status_t psa_mac_sign_finish(psa_mac_operation_t *operation,
2490                                  uint8_t *mac,
2491                                  size_t mac_size,
2492                                  size_t *mac_length)
2493 {
2494     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2495     psa_status_t abort_status = PSA_ERROR_CORRUPTION_DETECTED;
2496 
2497     if (operation->id == 0) {
2498         status = PSA_ERROR_BAD_STATE;
2499         goto exit;
2500     }
2501 
2502     if (!operation->is_sign) {
2503         status = PSA_ERROR_BAD_STATE;
2504         goto exit;
2505     }
2506 
2507     /* Sanity check. This will guarantee that mac_size != 0 (and so mac != NULL)
2508      * once all the error checks are done. */
2509     if (operation->mac_size == 0) {
2510         status = PSA_ERROR_BAD_STATE;
2511         goto exit;
2512     }
2513 
2514     if (mac_size < operation->mac_size) {
2515         status = PSA_ERROR_BUFFER_TOO_SMALL;
2516         goto exit;
2517     }
2518 
2519     status = psa_driver_wrapper_mac_sign_finish(operation,
2520                                                 mac, operation->mac_size,
2521                                                 mac_length);
2522 
2523 exit:
2524     /* In case of success, set the potential excess room in the output buffer
2525      * to an invalid value, to avoid potentially leaking a longer MAC.
2526      * In case of error, set the output length and content to a safe default,
2527      * such that in case the caller misses an error check, the output would be
2528      * an unachievable MAC.
2529      */
2530     if (status != PSA_SUCCESS) {
2531         *mac_length = mac_size;
2532         operation->mac_size = 0;
2533     }
2534 
2535     if (mac_size > operation->mac_size) {
2536         memset(&mac[operation->mac_size], '!',
2537                mac_size - operation->mac_size);
2538     }
2539 
2540     abort_status = psa_mac_abort(operation);
2541 
2542     return status == PSA_SUCCESS ? abort_status : status;
2543 }
2544 
psa_mac_verify_finish(psa_mac_operation_t * operation,const uint8_t * mac,size_t mac_length)2545 psa_status_t psa_mac_verify_finish(psa_mac_operation_t *operation,
2546                                    const uint8_t *mac,
2547                                    size_t mac_length)
2548 {
2549     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2550     psa_status_t abort_status = PSA_ERROR_CORRUPTION_DETECTED;
2551 
2552     if (operation->id == 0) {
2553         status = PSA_ERROR_BAD_STATE;
2554         goto exit;
2555     }
2556 
2557     if (operation->is_sign) {
2558         status = PSA_ERROR_BAD_STATE;
2559         goto exit;
2560     }
2561 
2562     if (operation->mac_size != mac_length) {
2563         status = PSA_ERROR_INVALID_SIGNATURE;
2564         goto exit;
2565     }
2566 
2567     status = psa_driver_wrapper_mac_verify_finish(operation,
2568                                                   mac, mac_length);
2569 
2570 exit:
2571     abort_status = psa_mac_abort(operation);
2572 
2573     return status == PSA_SUCCESS ? abort_status : status;
2574 }
2575 
psa_mac_compute_internal(mbedtls_svc_key_id_t key,psa_algorithm_t alg,const uint8_t * input,size_t input_length,uint8_t * mac,size_t mac_size,size_t * mac_length,int is_sign)2576 static psa_status_t psa_mac_compute_internal(mbedtls_svc_key_id_t key,
2577                                              psa_algorithm_t alg,
2578                                              const uint8_t *input,
2579                                              size_t input_length,
2580                                              uint8_t *mac,
2581                                              size_t mac_size,
2582                                              size_t *mac_length,
2583                                              int is_sign)
2584 {
2585     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2586     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
2587     psa_key_attributes_t attributes;
2588     psa_key_slot_t *slot;
2589     uint8_t operation_mac_size = 0;
2590 
2591     status = psa_get_and_lock_key_slot_with_policy(
2592         key,
2593         &slot,
2594         is_sign ? PSA_KEY_USAGE_SIGN_MESSAGE : PSA_KEY_USAGE_VERIFY_MESSAGE,
2595         alg);
2596     if (status != PSA_SUCCESS) {
2597         goto exit;
2598     }
2599 
2600     attributes = (psa_key_attributes_t) {
2601         .core = slot->attr
2602     };
2603 
2604     status = psa_mac_finalize_alg_and_key_validation(alg, &attributes,
2605                                                      &operation_mac_size);
2606     if (status != PSA_SUCCESS) {
2607         goto exit;
2608     }
2609 
2610     if (mac_size < operation_mac_size) {
2611         status = PSA_ERROR_BUFFER_TOO_SMALL;
2612         goto exit;
2613     }
2614 
2615     status = psa_driver_wrapper_mac_compute(
2616         &attributes,
2617         slot->key.data, slot->key.bytes,
2618         alg,
2619         input, input_length,
2620         mac, operation_mac_size, mac_length);
2621 
2622 exit:
2623     /* In case of success, set the potential excess room in the output buffer
2624      * to an invalid value, to avoid potentially leaking a longer MAC.
2625      * In case of error, set the output length and content to a safe default,
2626      * such that in case the caller misses an error check, the output would be
2627      * an unachievable MAC.
2628      */
2629     if (status != PSA_SUCCESS) {
2630         *mac_length = mac_size;
2631         operation_mac_size = 0;
2632     }
2633     if (mac_size > operation_mac_size) {
2634         memset(&mac[operation_mac_size], '!', mac_size - operation_mac_size);
2635     }
2636 
2637     unlock_status = psa_unlock_key_slot(slot);
2638 
2639     return (status == PSA_SUCCESS) ? unlock_status : status;
2640 }
2641 
psa_mac_compute(mbedtls_svc_key_id_t key,psa_algorithm_t alg,const uint8_t * input,size_t input_length,uint8_t * mac,size_t mac_size,size_t * mac_length)2642 psa_status_t psa_mac_compute(mbedtls_svc_key_id_t key,
2643                              psa_algorithm_t alg,
2644                              const uint8_t *input,
2645                              size_t input_length,
2646                              uint8_t *mac,
2647                              size_t mac_size,
2648                              size_t *mac_length)
2649 {
2650     return psa_mac_compute_internal(key, alg,
2651                                     input, input_length,
2652                                     mac, mac_size, mac_length, 1);
2653 }
2654 
psa_mac_verify(mbedtls_svc_key_id_t key,psa_algorithm_t alg,const uint8_t * input,size_t input_length,const uint8_t * mac,size_t mac_length)2655 psa_status_t psa_mac_verify(mbedtls_svc_key_id_t key,
2656                             psa_algorithm_t alg,
2657                             const uint8_t *input,
2658                             size_t input_length,
2659                             const uint8_t *mac,
2660                             size_t mac_length)
2661 {
2662     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2663     uint8_t actual_mac[PSA_MAC_MAX_SIZE];
2664     size_t actual_mac_length;
2665 
2666     status = psa_mac_compute_internal(key, alg,
2667                                       input, input_length,
2668                                       actual_mac, sizeof(actual_mac),
2669                                       &actual_mac_length, 0);
2670     if (status != PSA_SUCCESS) {
2671         goto exit;
2672     }
2673 
2674     if (mac_length != actual_mac_length) {
2675         status = PSA_ERROR_INVALID_SIGNATURE;
2676         goto exit;
2677     }
2678     if (mbedtls_psa_safer_memcmp(mac, actual_mac, actual_mac_length) != 0) {
2679         status = PSA_ERROR_INVALID_SIGNATURE;
2680         goto exit;
2681     }
2682 
2683 exit:
2684     mbedtls_platform_zeroize(actual_mac, sizeof(actual_mac));
2685 
2686     return status;
2687 }
2688 
2689 /****************************************************************/
2690 /* Asymmetric cryptography */
2691 /****************************************************************/
2692 
psa_sign_verify_check_alg(int input_is_message,psa_algorithm_t alg)2693 static psa_status_t psa_sign_verify_check_alg(int input_is_message,
2694                                               psa_algorithm_t alg)
2695 {
2696     if (input_is_message) {
2697         if (!PSA_ALG_IS_SIGN_MESSAGE(alg)) {
2698             return PSA_ERROR_INVALID_ARGUMENT;
2699         }
2700 
2701         if (PSA_ALG_IS_SIGN_HASH(alg)) {
2702             if (!PSA_ALG_IS_HASH(PSA_ALG_SIGN_GET_HASH(alg))) {
2703                 return PSA_ERROR_INVALID_ARGUMENT;
2704             }
2705         }
2706     } else {
2707         if (!PSA_ALG_IS_SIGN_HASH(alg)) {
2708             return PSA_ERROR_INVALID_ARGUMENT;
2709         }
2710     }
2711 
2712     return PSA_SUCCESS;
2713 }
2714 
psa_sign_internal(mbedtls_svc_key_id_t key,int input_is_message,psa_algorithm_t alg,const uint8_t * input,size_t input_length,uint8_t * signature,size_t signature_size,size_t * signature_length)2715 static psa_status_t psa_sign_internal(mbedtls_svc_key_id_t key,
2716                                       int input_is_message,
2717                                       psa_algorithm_t alg,
2718                                       const uint8_t *input,
2719                                       size_t input_length,
2720                                       uint8_t *signature,
2721                                       size_t signature_size,
2722                                       size_t *signature_length)
2723 {
2724     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2725     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
2726     psa_key_attributes_t attributes;
2727     psa_key_slot_t *slot;
2728 
2729     *signature_length = 0;
2730 
2731     status = psa_sign_verify_check_alg(input_is_message, alg);
2732     if (status != PSA_SUCCESS) {
2733         return status;
2734     }
2735 
2736     /* Immediately reject a zero-length signature buffer. This guarantees
2737      * that signature must be a valid pointer. (On the other hand, the input
2738      * buffer can in principle be empty since it doesn't actually have
2739      * to be a hash.) */
2740     if (signature_size == 0) {
2741         return PSA_ERROR_BUFFER_TOO_SMALL;
2742     }
2743 
2744     status = psa_get_and_lock_key_slot_with_policy(
2745         key, &slot,
2746         input_is_message ? PSA_KEY_USAGE_SIGN_MESSAGE :
2747         PSA_KEY_USAGE_SIGN_HASH,
2748         alg);
2749 
2750     if (status != PSA_SUCCESS) {
2751         goto exit;
2752     }
2753 
2754     if (!PSA_KEY_TYPE_IS_KEY_PAIR(slot->attr.type)) {
2755         status = PSA_ERROR_INVALID_ARGUMENT;
2756         goto exit;
2757     }
2758 
2759     attributes = (psa_key_attributes_t)  {
2760         .core = slot->attr
2761     };
2762 
2763     if (input_is_message) {
2764         status = psa_driver_wrapper_sign_message(
2765             &attributes, slot->key.data, slot->key.bytes,
2766             alg, input, input_length,
2767             signature, signature_size, signature_length);
2768     } else {
2769 
2770         status = psa_driver_wrapper_sign_hash(
2771             &attributes, slot->key.data, slot->key.bytes,
2772             alg, input, input_length,
2773             signature, signature_size, signature_length);
2774     }
2775 
2776 
2777 exit:
2778     /* Fill the unused part of the output buffer (the whole buffer on error,
2779      * the trailing part on success) with something that isn't a valid signature
2780      * (barring an attack on the signature and deliberately-crafted input),
2781      * in case the caller doesn't check the return status properly. */
2782     if (status == PSA_SUCCESS) {
2783         memset(signature + *signature_length, '!',
2784                signature_size - *signature_length);
2785     } else {
2786         memset(signature, '!', signature_size);
2787     }
2788     /* If signature_size is 0 then we have nothing to do. We must not call
2789      * memset because signature may be NULL in this case. */
2790 
2791     unlock_status = psa_unlock_key_slot(slot);
2792 
2793     return (status == PSA_SUCCESS) ? unlock_status : status;
2794 }
2795 
psa_verify_internal(mbedtls_svc_key_id_t key,int input_is_message,psa_algorithm_t alg,const uint8_t * input,size_t input_length,const uint8_t * signature,size_t signature_length)2796 static psa_status_t psa_verify_internal(mbedtls_svc_key_id_t key,
2797                                         int input_is_message,
2798                                         psa_algorithm_t alg,
2799                                         const uint8_t *input,
2800                                         size_t input_length,
2801                                         const uint8_t *signature,
2802                                         size_t signature_length)
2803 {
2804     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2805     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
2806     psa_key_slot_t *slot;
2807 
2808     status = psa_sign_verify_check_alg(input_is_message, alg);
2809     if (status != PSA_SUCCESS) {
2810         return status;
2811     }
2812 
2813     status = psa_get_and_lock_key_slot_with_policy(
2814         key, &slot,
2815         input_is_message ? PSA_KEY_USAGE_VERIFY_MESSAGE :
2816         PSA_KEY_USAGE_VERIFY_HASH,
2817         alg);
2818 
2819     if (status != PSA_SUCCESS) {
2820         return status;
2821     }
2822 
2823     psa_key_attributes_t attributes = {
2824         .core = slot->attr
2825     };
2826 
2827     if (input_is_message) {
2828         status = psa_driver_wrapper_verify_message(
2829             &attributes, slot->key.data, slot->key.bytes,
2830             alg, input, input_length,
2831             signature, signature_length);
2832     } else {
2833         status = psa_driver_wrapper_verify_hash(
2834             &attributes, slot->key.data, slot->key.bytes,
2835             alg, input, input_length,
2836             signature, signature_length);
2837     }
2838 
2839     unlock_status = psa_unlock_key_slot(slot);
2840 
2841     return (status == PSA_SUCCESS) ? unlock_status : status;
2842 
2843 }
2844 
psa_sign_message_builtin(const psa_key_attributes_t * attributes,const uint8_t * key_buffer,size_t key_buffer_size,psa_algorithm_t alg,const uint8_t * input,size_t input_length,uint8_t * signature,size_t signature_size,size_t * signature_length)2845 psa_status_t psa_sign_message_builtin(
2846     const psa_key_attributes_t *attributes,
2847     const uint8_t *key_buffer,
2848     size_t key_buffer_size,
2849     psa_algorithm_t alg,
2850     const uint8_t *input,
2851     size_t input_length,
2852     uint8_t *signature,
2853     size_t signature_size,
2854     size_t *signature_length)
2855 {
2856     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2857 
2858     if (PSA_ALG_IS_SIGN_HASH(alg)) {
2859         size_t hash_length;
2860         uint8_t hash[PSA_HASH_MAX_SIZE];
2861 
2862         status = psa_driver_wrapper_hash_compute(
2863             PSA_ALG_SIGN_GET_HASH(alg),
2864             input, input_length,
2865             hash, sizeof(hash), &hash_length);
2866 
2867         if (status != PSA_SUCCESS) {
2868             return status;
2869         }
2870 
2871         return psa_driver_wrapper_sign_hash(
2872             attributes, key_buffer, key_buffer_size,
2873             alg, hash, hash_length,
2874             signature, signature_size, signature_length);
2875     }
2876 
2877     return PSA_ERROR_NOT_SUPPORTED;
2878 }
2879 
psa_sign_message(mbedtls_svc_key_id_t key,psa_algorithm_t alg,const uint8_t * input,size_t input_length,uint8_t * signature,size_t signature_size,size_t * signature_length)2880 psa_status_t psa_sign_message(mbedtls_svc_key_id_t key,
2881                               psa_algorithm_t alg,
2882                               const uint8_t *input,
2883                               size_t input_length,
2884                               uint8_t *signature,
2885                               size_t signature_size,
2886                               size_t *signature_length)
2887 {
2888     return psa_sign_internal(
2889         key, 1, alg, input, input_length,
2890         signature, signature_size, signature_length);
2891 }
2892 
psa_verify_message_builtin(const psa_key_attributes_t * attributes,const uint8_t * key_buffer,size_t key_buffer_size,psa_algorithm_t alg,const uint8_t * input,size_t input_length,const uint8_t * signature,size_t signature_length)2893 psa_status_t psa_verify_message_builtin(
2894     const psa_key_attributes_t *attributes,
2895     const uint8_t *key_buffer,
2896     size_t key_buffer_size,
2897     psa_algorithm_t alg,
2898     const uint8_t *input,
2899     size_t input_length,
2900     const uint8_t *signature,
2901     size_t signature_length)
2902 {
2903     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2904 
2905     if (PSA_ALG_IS_SIGN_HASH(alg)) {
2906         size_t hash_length;
2907         uint8_t hash[PSA_HASH_MAX_SIZE];
2908 
2909         status = psa_driver_wrapper_hash_compute(
2910             PSA_ALG_SIGN_GET_HASH(alg),
2911             input, input_length,
2912             hash, sizeof(hash), &hash_length);
2913 
2914         if (status != PSA_SUCCESS) {
2915             return status;
2916         }
2917 
2918         return psa_driver_wrapper_verify_hash(
2919             attributes, key_buffer, key_buffer_size,
2920             alg, hash, hash_length,
2921             signature, signature_length);
2922     }
2923 
2924     return PSA_ERROR_NOT_SUPPORTED;
2925 }
2926 
psa_verify_message(mbedtls_svc_key_id_t key,psa_algorithm_t alg,const uint8_t * input,size_t input_length,const uint8_t * signature,size_t signature_length)2927 psa_status_t psa_verify_message(mbedtls_svc_key_id_t key,
2928                                 psa_algorithm_t alg,
2929                                 const uint8_t *input,
2930                                 size_t input_length,
2931                                 const uint8_t *signature,
2932                                 size_t signature_length)
2933 {
2934     return psa_verify_internal(
2935         key, 1, alg, input, input_length,
2936         signature, signature_length);
2937 }
2938 
psa_sign_hash_builtin(const psa_key_attributes_t * attributes,const uint8_t * key_buffer,size_t key_buffer_size,psa_algorithm_t alg,const uint8_t * hash,size_t hash_length,uint8_t * signature,size_t signature_size,size_t * signature_length)2939 psa_status_t psa_sign_hash_builtin(
2940     const psa_key_attributes_t *attributes,
2941     const uint8_t *key_buffer, size_t key_buffer_size,
2942     psa_algorithm_t alg, const uint8_t *hash, size_t hash_length,
2943     uint8_t *signature, size_t signature_size, size_t *signature_length)
2944 {
2945     if (attributes->core.type == PSA_KEY_TYPE_RSA_KEY_PAIR) {
2946         if (PSA_ALG_IS_RSA_PKCS1V15_SIGN(alg) ||
2947             PSA_ALG_IS_RSA_PSS(alg)) {
2948 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) || \
2949             defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS)
2950             return mbedtls_psa_rsa_sign_hash(
2951                 attributes,
2952                 key_buffer, key_buffer_size,
2953                 alg, hash, hash_length,
2954                 signature, signature_size, signature_length);
2955 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) ||
2956         * defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS) */
2957         } else {
2958             return PSA_ERROR_INVALID_ARGUMENT;
2959         }
2960     } else if (PSA_KEY_TYPE_IS_ECC(attributes->core.type)) {
2961         if (PSA_ALG_IS_ECDSA(alg)) {
2962 #if defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
2963             defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)
2964             return mbedtls_psa_ecdsa_sign_hash(
2965                 attributes,
2966                 key_buffer, key_buffer_size,
2967                 alg, hash, hash_length,
2968                 signature, signature_size, signature_length);
2969 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
2970         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) */
2971         } else {
2972             return PSA_ERROR_INVALID_ARGUMENT;
2973         }
2974     }
2975 
2976     (void) key_buffer;
2977     (void) key_buffer_size;
2978     (void) hash;
2979     (void) hash_length;
2980     (void) signature;
2981     (void) signature_size;
2982     (void) signature_length;
2983 
2984     return PSA_ERROR_NOT_SUPPORTED;
2985 }
2986 
psa_sign_hash(mbedtls_svc_key_id_t key,psa_algorithm_t alg,const uint8_t * hash,size_t hash_length,uint8_t * signature,size_t signature_size,size_t * signature_length)2987 psa_status_t psa_sign_hash(mbedtls_svc_key_id_t key,
2988                            psa_algorithm_t alg,
2989                            const uint8_t *hash,
2990                            size_t hash_length,
2991                            uint8_t *signature,
2992                            size_t signature_size,
2993                            size_t *signature_length)
2994 {
2995     return psa_sign_internal(
2996         key, 0, alg, hash, hash_length,
2997         signature, signature_size, signature_length);
2998 }
2999 
psa_verify_hash_builtin(const psa_key_attributes_t * attributes,const uint8_t * key_buffer,size_t key_buffer_size,psa_algorithm_t alg,const uint8_t * hash,size_t hash_length,const uint8_t * signature,size_t signature_length)3000 psa_status_t psa_verify_hash_builtin(
3001     const psa_key_attributes_t *attributes,
3002     const uint8_t *key_buffer, size_t key_buffer_size,
3003     psa_algorithm_t alg, const uint8_t *hash, size_t hash_length,
3004     const uint8_t *signature, size_t signature_length)
3005 {
3006     if (PSA_KEY_TYPE_IS_RSA(attributes->core.type)) {
3007         if (PSA_ALG_IS_RSA_PKCS1V15_SIGN(alg) ||
3008             PSA_ALG_IS_RSA_PSS(alg)) {
3009 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) || \
3010             defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS)
3011             return mbedtls_psa_rsa_verify_hash(
3012                 attributes,
3013                 key_buffer, key_buffer_size,
3014                 alg, hash, hash_length,
3015                 signature, signature_length);
3016 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) ||
3017         * defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS) */
3018         } else {
3019             return PSA_ERROR_INVALID_ARGUMENT;
3020         }
3021     } else if (PSA_KEY_TYPE_IS_ECC(attributes->core.type)) {
3022         if (PSA_ALG_IS_ECDSA(alg)) {
3023 #if defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
3024             defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)
3025             return mbedtls_psa_ecdsa_verify_hash(
3026                 attributes,
3027                 key_buffer, key_buffer_size,
3028                 alg, hash, hash_length,
3029                 signature, signature_length);
3030 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
3031         * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) */
3032         } else {
3033             return PSA_ERROR_INVALID_ARGUMENT;
3034         }
3035     }
3036 
3037     (void) key_buffer;
3038     (void) key_buffer_size;
3039     (void) hash;
3040     (void) hash_length;
3041     (void) signature;
3042     (void) signature_length;
3043 
3044     return PSA_ERROR_NOT_SUPPORTED;
3045 }
3046 
psa_verify_hash(mbedtls_svc_key_id_t key,psa_algorithm_t alg,const uint8_t * hash,size_t hash_length,const uint8_t * signature,size_t signature_length)3047 psa_status_t psa_verify_hash(mbedtls_svc_key_id_t key,
3048                              psa_algorithm_t alg,
3049                              const uint8_t *hash,
3050                              size_t hash_length,
3051                              const uint8_t *signature,
3052                              size_t signature_length)
3053 {
3054     return psa_verify_internal(
3055         key, 0, alg, hash, hash_length,
3056         signature, signature_length);
3057 }
3058 
3059 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
psa_rsa_oaep_set_padding_mode(psa_algorithm_t alg,mbedtls_rsa_context * rsa)3060 static void psa_rsa_oaep_set_padding_mode(psa_algorithm_t alg,
3061                                           mbedtls_rsa_context *rsa)
3062 {
3063     psa_algorithm_t hash_alg = PSA_ALG_RSA_OAEP_GET_HASH(alg);
3064     const mbedtls_md_info_t *md_info = mbedtls_md_info_from_psa(hash_alg);
3065     mbedtls_md_type_t md_alg = mbedtls_md_get_type(md_info);
3066     mbedtls_rsa_set_padding(rsa, MBEDTLS_RSA_PKCS_V21, md_alg);
3067 }
3068 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP) */
3069 
psa_asymmetric_encrypt(mbedtls_svc_key_id_t key,psa_algorithm_t alg,const uint8_t * input,size_t input_length,const uint8_t * salt,size_t salt_length,uint8_t * output,size_t output_size,size_t * output_length)3070 psa_status_t psa_asymmetric_encrypt(mbedtls_svc_key_id_t key,
3071                                     psa_algorithm_t alg,
3072                                     const uint8_t *input,
3073                                     size_t input_length,
3074                                     const uint8_t *salt,
3075                                     size_t salt_length,
3076                                     uint8_t *output,
3077                                     size_t output_size,
3078                                     size_t *output_length)
3079 {
3080     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3081     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
3082     psa_key_slot_t *slot;
3083 
3084     (void) input;
3085     (void) input_length;
3086     (void) salt;
3087     (void) output;
3088     (void) output_size;
3089 
3090     *output_length = 0;
3091 
3092     if (!PSA_ALG_IS_RSA_OAEP(alg) && salt_length != 0) {
3093         return PSA_ERROR_INVALID_ARGUMENT;
3094     }
3095 
3096     status = psa_get_and_lock_transparent_key_slot_with_policy(
3097         key, &slot, PSA_KEY_USAGE_ENCRYPT, alg);
3098     if (status != PSA_SUCCESS) {
3099         return status;
3100     }
3101     if (!(PSA_KEY_TYPE_IS_PUBLIC_KEY(slot->attr.type) ||
3102           PSA_KEY_TYPE_IS_KEY_PAIR(slot->attr.type))) {
3103         status = PSA_ERROR_INVALID_ARGUMENT;
3104         goto exit;
3105     }
3106 
3107     if (PSA_KEY_TYPE_IS_RSA(slot->attr.type)) {
3108 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT) || \
3109         defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
3110         mbedtls_rsa_context *rsa = NULL;
3111         status = mbedtls_psa_rsa_load_representation(slot->attr.type,
3112                                                      slot->key.data,
3113                                                      slot->key.bytes,
3114                                                      &rsa);
3115         if (status != PSA_SUCCESS) {
3116             goto rsa_exit;
3117         }
3118 
3119         if (output_size < mbedtls_rsa_get_len(rsa)) {
3120             status = PSA_ERROR_BUFFER_TOO_SMALL;
3121             goto rsa_exit;
3122         }
3123 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT) ||
3124         * defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP) */
3125         if (alg == PSA_ALG_RSA_PKCS1V15_CRYPT) {
3126 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT)
3127             status = mbedtls_to_psa_error(
3128                 mbedtls_rsa_pkcs1_encrypt(rsa,
3129                                           mbedtls_psa_get_random,
3130                                           MBEDTLS_PSA_RANDOM_STATE,
3131                                           MBEDTLS_RSA_PUBLIC,
3132                                           input_length,
3133                                           input,
3134                                           output));
3135 #else
3136             status = PSA_ERROR_NOT_SUPPORTED;
3137 #endif /* MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT */
3138         } else
3139         if (PSA_ALG_IS_RSA_OAEP(alg)) {
3140 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
3141             psa_rsa_oaep_set_padding_mode(alg, rsa);
3142             status = mbedtls_to_psa_error(
3143                 mbedtls_rsa_rsaes_oaep_encrypt(rsa,
3144                                                mbedtls_psa_get_random,
3145                                                MBEDTLS_PSA_RANDOM_STATE,
3146                                                MBEDTLS_RSA_PUBLIC,
3147                                                salt, salt_length,
3148                                                input_length,
3149                                                input,
3150                                                output));
3151 #else
3152             status = PSA_ERROR_NOT_SUPPORTED;
3153 #endif /* MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP */
3154         } else {
3155             status = PSA_ERROR_INVALID_ARGUMENT;
3156         }
3157 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT) || \
3158         defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
3159 rsa_exit:
3160         if (status == PSA_SUCCESS) {
3161             *output_length = mbedtls_rsa_get_len(rsa);
3162         }
3163 
3164         mbedtls_rsa_free(rsa);
3165         mbedtls_free(rsa);
3166 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT) ||
3167         * defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP) */
3168     } else {
3169         status = PSA_ERROR_NOT_SUPPORTED;
3170     }
3171 
3172 exit:
3173     unlock_status = psa_unlock_key_slot(slot);
3174 
3175     return (status == PSA_SUCCESS) ? unlock_status : status;
3176 }
3177 
psa_asymmetric_decrypt(mbedtls_svc_key_id_t key,psa_algorithm_t alg,const uint8_t * input,size_t input_length,const uint8_t * salt,size_t salt_length,uint8_t * output,size_t output_size,size_t * output_length)3178 psa_status_t psa_asymmetric_decrypt(mbedtls_svc_key_id_t key,
3179                                     psa_algorithm_t alg,
3180                                     const uint8_t *input,
3181                                     size_t input_length,
3182                                     const uint8_t *salt,
3183                                     size_t salt_length,
3184                                     uint8_t *output,
3185                                     size_t output_size,
3186                                     size_t *output_length)
3187 {
3188     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3189     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
3190     psa_key_slot_t *slot;
3191 
3192     (void) input;
3193     (void) input_length;
3194     (void) salt;
3195     (void) output;
3196     (void) output_size;
3197 
3198     *output_length = 0;
3199 
3200     if (!PSA_ALG_IS_RSA_OAEP(alg) && salt_length != 0) {
3201         return PSA_ERROR_INVALID_ARGUMENT;
3202     }
3203 
3204     status = psa_get_and_lock_transparent_key_slot_with_policy(
3205         key, &slot, PSA_KEY_USAGE_DECRYPT, alg);
3206     if (status != PSA_SUCCESS) {
3207         return status;
3208     }
3209     if (!PSA_KEY_TYPE_IS_KEY_PAIR(slot->attr.type)) {
3210         status = PSA_ERROR_INVALID_ARGUMENT;
3211         goto exit;
3212     }
3213 
3214     if (slot->attr.type == PSA_KEY_TYPE_RSA_KEY_PAIR) {
3215 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT) || \
3216         defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
3217         mbedtls_rsa_context *rsa = NULL;
3218         status = mbedtls_psa_rsa_load_representation(slot->attr.type,
3219                                                      slot->key.data,
3220                                                      slot->key.bytes,
3221                                                      &rsa);
3222         if (status != PSA_SUCCESS) {
3223             goto exit;
3224         }
3225 
3226         if (input_length != mbedtls_rsa_get_len(rsa)) {
3227             status = PSA_ERROR_INVALID_ARGUMENT;
3228             goto rsa_exit;
3229         }
3230 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT) ||
3231         * defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP) */
3232 
3233         if (alg == PSA_ALG_RSA_PKCS1V15_CRYPT) {
3234 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT)
3235             status = mbedtls_to_psa_error(
3236                 mbedtls_rsa_pkcs1_decrypt(rsa,
3237                                           mbedtls_psa_get_random,
3238                                           MBEDTLS_PSA_RANDOM_STATE,
3239                                           MBEDTLS_RSA_PRIVATE,
3240                                           output_length,
3241                                           input,
3242                                           output,
3243                                           output_size));
3244 #else
3245             status = PSA_ERROR_NOT_SUPPORTED;
3246 #endif /* MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT */
3247         } else
3248         if (PSA_ALG_IS_RSA_OAEP(alg)) {
3249 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
3250             psa_rsa_oaep_set_padding_mode(alg, rsa);
3251             status = mbedtls_to_psa_error(
3252                 mbedtls_rsa_rsaes_oaep_decrypt(rsa,
3253                                                mbedtls_psa_get_random,
3254                                                MBEDTLS_PSA_RANDOM_STATE,
3255                                                MBEDTLS_RSA_PRIVATE,
3256                                                salt, salt_length,
3257                                                output_length,
3258                                                input,
3259                                                output,
3260                                                output_size));
3261 #else
3262             status = PSA_ERROR_NOT_SUPPORTED;
3263 #endif /* MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP */
3264         } else {
3265             status = PSA_ERROR_INVALID_ARGUMENT;
3266         }
3267 
3268 #if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT) || \
3269         defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
3270 rsa_exit:
3271         mbedtls_rsa_free(rsa);
3272         mbedtls_free(rsa);
3273 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT) ||
3274         * defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP) */
3275     } else {
3276         status = PSA_ERROR_NOT_SUPPORTED;
3277     }
3278 
3279 exit:
3280     unlock_status = psa_unlock_key_slot(slot);
3281 
3282     return (status == PSA_SUCCESS) ? unlock_status : status;
3283 }
3284 
3285 
3286 
3287 /****************************************************************/
3288 /* Symmetric cryptography */
3289 /****************************************************************/
3290 
psa_cipher_setup(psa_cipher_operation_t * operation,mbedtls_svc_key_id_t key,psa_algorithm_t alg,mbedtls_operation_t cipher_operation)3291 static psa_status_t psa_cipher_setup(psa_cipher_operation_t *operation,
3292                                      mbedtls_svc_key_id_t key,
3293                                      psa_algorithm_t alg,
3294                                      mbedtls_operation_t cipher_operation)
3295 {
3296     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3297     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
3298     psa_key_attributes_t attributes;
3299     psa_key_slot_t *slot = NULL;
3300     psa_key_usage_t usage = (cipher_operation == MBEDTLS_ENCRYPT ?
3301                              PSA_KEY_USAGE_ENCRYPT :
3302                              PSA_KEY_USAGE_DECRYPT);
3303 
3304     /* A context must be freshly initialized before it can be set up. */
3305     if (operation->id != 0) {
3306         status = PSA_ERROR_BAD_STATE;
3307         goto exit;
3308     }
3309 
3310     if (!PSA_ALG_IS_CIPHER(alg)) {
3311         status = PSA_ERROR_INVALID_ARGUMENT;
3312         goto exit;
3313     }
3314 
3315     status = psa_get_and_lock_key_slot_with_policy(key, &slot, usage, alg);
3316     if (status != PSA_SUCCESS) {
3317         goto exit;
3318     }
3319 
3320     /* Initialize the operation struct members, except for id. The id member
3321      * is used to indicate to psa_cipher_abort that there are resources to free,
3322      * so we only set it (in the driver wrapper) after resources have been
3323      * allocated/initialized. */
3324     operation->iv_set = 0;
3325     if (alg == PSA_ALG_ECB_NO_PADDING) {
3326         operation->iv_required = 0;
3327     } else if (slot->attr.type == PSA_KEY_TYPE_ARC4) {
3328         operation->iv_required = 0;
3329     } else {
3330         operation->iv_required = 1;
3331     }
3332     operation->default_iv_length = PSA_CIPHER_IV_LENGTH(slot->attr.type, alg);
3333 
3334     attributes = (psa_key_attributes_t) {
3335         .core = slot->attr
3336     };
3337 
3338     /* Try doing the operation through a driver before using software fallback. */
3339     if (cipher_operation == MBEDTLS_ENCRYPT) {
3340         status = psa_driver_wrapper_cipher_encrypt_setup(operation,
3341                                                          &attributes,
3342                                                          slot->key.data,
3343                                                          slot->key.bytes,
3344                                                          alg);
3345     } else {
3346         status = psa_driver_wrapper_cipher_decrypt_setup(operation,
3347                                                          &attributes,
3348                                                          slot->key.data,
3349                                                          slot->key.bytes,
3350                                                          alg);
3351     }
3352 
3353 exit:
3354     if (status != PSA_SUCCESS) {
3355         psa_cipher_abort(operation);
3356     }
3357 
3358     unlock_status = psa_unlock_key_slot(slot);
3359 
3360     return (status == PSA_SUCCESS) ? unlock_status : status;
3361 }
3362 
psa_cipher_encrypt_setup(psa_cipher_operation_t * operation,mbedtls_svc_key_id_t key,psa_algorithm_t alg)3363 psa_status_t psa_cipher_encrypt_setup(psa_cipher_operation_t *operation,
3364                                       mbedtls_svc_key_id_t key,
3365                                       psa_algorithm_t alg)
3366 {
3367     return psa_cipher_setup(operation, key, alg, MBEDTLS_ENCRYPT);
3368 }
3369 
psa_cipher_decrypt_setup(psa_cipher_operation_t * operation,mbedtls_svc_key_id_t key,psa_algorithm_t alg)3370 psa_status_t psa_cipher_decrypt_setup(psa_cipher_operation_t *operation,
3371                                       mbedtls_svc_key_id_t key,
3372                                       psa_algorithm_t alg)
3373 {
3374     return psa_cipher_setup(operation, key, alg, MBEDTLS_DECRYPT);
3375 }
3376 
psa_cipher_generate_iv(psa_cipher_operation_t * operation,uint8_t * iv,size_t iv_size,size_t * iv_length)3377 psa_status_t psa_cipher_generate_iv(psa_cipher_operation_t *operation,
3378                                     uint8_t *iv,
3379                                     size_t iv_size,
3380                                     size_t *iv_length)
3381 {
3382     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3383     uint8_t local_iv[PSA_CIPHER_IV_MAX_SIZE];
3384     size_t default_iv_length = 0;
3385 
3386     if (operation->id == 0) {
3387         status = PSA_ERROR_BAD_STATE;
3388         goto exit;
3389     }
3390 
3391     if (operation->iv_set || !operation->iv_required) {
3392         status = PSA_ERROR_BAD_STATE;
3393         goto exit;
3394     }
3395 
3396     default_iv_length = operation->default_iv_length;
3397     if (iv_size < default_iv_length) {
3398         status = PSA_ERROR_BUFFER_TOO_SMALL;
3399         goto exit;
3400     }
3401 
3402     if (default_iv_length > PSA_CIPHER_IV_MAX_SIZE) {
3403         status = PSA_ERROR_GENERIC_ERROR;
3404         goto exit;
3405     }
3406 
3407     status = psa_generate_random(local_iv, default_iv_length);
3408     if (status != PSA_SUCCESS) {
3409         goto exit;
3410     }
3411 
3412     status = psa_driver_wrapper_cipher_set_iv(operation,
3413                                               local_iv, default_iv_length);
3414 
3415 exit:
3416     if (status == PSA_SUCCESS) {
3417         memcpy(iv, local_iv, default_iv_length);
3418         *iv_length = default_iv_length;
3419         operation->iv_set = 1;
3420     } else {
3421         *iv_length = 0;
3422         psa_cipher_abort(operation);
3423     }
3424 
3425     return status;
3426 }
3427 
psa_cipher_set_iv(psa_cipher_operation_t * operation,const uint8_t * iv,size_t iv_length)3428 psa_status_t psa_cipher_set_iv(psa_cipher_operation_t *operation,
3429                                const uint8_t *iv,
3430                                size_t iv_length)
3431 {
3432     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3433 
3434     if (operation->id == 0) {
3435         status = PSA_ERROR_BAD_STATE;
3436         goto exit;
3437     }
3438 
3439     if (operation->iv_set || !operation->iv_required) {
3440         status = PSA_ERROR_BAD_STATE;
3441         goto exit;
3442     }
3443 
3444     if (iv_length > PSA_CIPHER_IV_MAX_SIZE) {
3445         status = PSA_ERROR_INVALID_ARGUMENT;
3446         goto exit;
3447     }
3448 
3449     status = psa_driver_wrapper_cipher_set_iv(operation,
3450                                               iv,
3451                                               iv_length);
3452 
3453 exit:
3454     if (status == PSA_SUCCESS) {
3455         operation->iv_set = 1;
3456     } else {
3457         psa_cipher_abort(operation);
3458     }
3459     return status;
3460 }
3461 
psa_cipher_update(psa_cipher_operation_t * operation,const uint8_t * input,size_t input_length,uint8_t * output,size_t output_size,size_t * output_length)3462 psa_status_t psa_cipher_update(psa_cipher_operation_t *operation,
3463                                const uint8_t *input,
3464                                size_t input_length,
3465                                uint8_t *output,
3466                                size_t output_size,
3467                                size_t *output_length)
3468 {
3469     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3470 
3471     if (operation->id == 0) {
3472         status = PSA_ERROR_BAD_STATE;
3473         goto exit;
3474     }
3475 
3476     if (operation->iv_required && !operation->iv_set) {
3477         status = PSA_ERROR_BAD_STATE;
3478         goto exit;
3479     }
3480 
3481     status = psa_driver_wrapper_cipher_update(operation,
3482                                               input,
3483                                               input_length,
3484                                               output,
3485                                               output_size,
3486                                               output_length);
3487 
3488 exit:
3489     if (status != PSA_SUCCESS) {
3490         psa_cipher_abort(operation);
3491     }
3492 
3493     return status;
3494 }
3495 
psa_cipher_finish(psa_cipher_operation_t * operation,uint8_t * output,size_t output_size,size_t * output_length)3496 psa_status_t psa_cipher_finish(psa_cipher_operation_t *operation,
3497                                uint8_t *output,
3498                                size_t output_size,
3499                                size_t *output_length)
3500 {
3501     psa_status_t status = PSA_ERROR_GENERIC_ERROR;
3502 
3503     if (operation->id == 0) {
3504         status = PSA_ERROR_BAD_STATE;
3505         goto exit;
3506     }
3507 
3508     if (operation->iv_required && !operation->iv_set) {
3509         status = PSA_ERROR_BAD_STATE;
3510         goto exit;
3511     }
3512 
3513     status = psa_driver_wrapper_cipher_finish(operation,
3514                                               output,
3515                                               output_size,
3516                                               output_length);
3517 
3518 exit:
3519     if (status == PSA_SUCCESS) {
3520         return psa_cipher_abort(operation);
3521     } else {
3522         *output_length = 0;
3523         (void) psa_cipher_abort(operation);
3524 
3525         return status;
3526     }
3527 }
3528 
psa_cipher_abort(psa_cipher_operation_t * operation)3529 psa_status_t psa_cipher_abort(psa_cipher_operation_t *operation)
3530 {
3531     if (operation->id == 0) {
3532         /* The object has (apparently) been initialized but it is not (yet)
3533          * in use. It's ok to call abort on such an object, and there's
3534          * nothing to do. */
3535         return PSA_SUCCESS;
3536     }
3537 
3538     psa_driver_wrapper_cipher_abort(operation);
3539 
3540     operation->id = 0;
3541     operation->iv_set = 0;
3542     operation->iv_required = 0;
3543 
3544     return PSA_SUCCESS;
3545 }
3546 
psa_cipher_encrypt(mbedtls_svc_key_id_t key,psa_algorithm_t alg,const uint8_t * input,size_t input_length,uint8_t * output,size_t output_size,size_t * output_length)3547 psa_status_t psa_cipher_encrypt(mbedtls_svc_key_id_t key,
3548                                 psa_algorithm_t alg,
3549                                 const uint8_t *input,
3550                                 size_t input_length,
3551                                 uint8_t *output,
3552                                 size_t output_size,
3553                                 size_t *output_length)
3554 {
3555     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3556     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
3557     psa_key_attributes_t attributes;
3558     psa_key_slot_t *slot = NULL;
3559     uint8_t local_iv[PSA_CIPHER_IV_MAX_SIZE];
3560     size_t default_iv_length = 0;
3561 
3562     if (!PSA_ALG_IS_CIPHER(alg)) {
3563         status = PSA_ERROR_INVALID_ARGUMENT;
3564         goto exit;
3565     }
3566 
3567     status = psa_get_and_lock_key_slot_with_policy(key, &slot,
3568                                                    PSA_KEY_USAGE_ENCRYPT,
3569                                                    alg);
3570     if (status != PSA_SUCCESS) {
3571         goto exit;
3572     }
3573 
3574     attributes = (psa_key_attributes_t) {
3575         .core = slot->attr
3576     };
3577 
3578     default_iv_length = PSA_CIPHER_IV_LENGTH(slot->attr.type, alg);
3579     if (default_iv_length > PSA_CIPHER_IV_MAX_SIZE) {
3580         status = PSA_ERROR_GENERIC_ERROR;
3581         goto exit;
3582     }
3583 
3584     if (default_iv_length > 0) {
3585         if (output_size < default_iv_length) {
3586             status = PSA_ERROR_BUFFER_TOO_SMALL;
3587             goto exit;
3588         }
3589 
3590         status = psa_generate_random(local_iv, default_iv_length);
3591         if (status != PSA_SUCCESS) {
3592             goto exit;
3593         }
3594     }
3595 
3596     status = psa_driver_wrapper_cipher_encrypt(
3597         &attributes, slot->key.data, slot->key.bytes,
3598         alg, local_iv, default_iv_length, input, input_length,
3599         mbedtls_buffer_offset(output, default_iv_length),
3600         output_size - default_iv_length, output_length);
3601 
3602 exit:
3603     unlock_status = psa_unlock_key_slot(slot);
3604     if (status == PSA_SUCCESS) {
3605         status = unlock_status;
3606     }
3607 
3608     if (status == PSA_SUCCESS) {
3609         if (default_iv_length > 0) {
3610             memcpy(output, local_iv, default_iv_length);
3611         }
3612         *output_length += default_iv_length;
3613     } else {
3614         *output_length = 0;
3615     }
3616 
3617     return status;
3618 }
3619 
psa_cipher_decrypt(mbedtls_svc_key_id_t key,psa_algorithm_t alg,const uint8_t * input,size_t input_length,uint8_t * output,size_t output_size,size_t * output_length)3620 psa_status_t psa_cipher_decrypt(mbedtls_svc_key_id_t key,
3621                                 psa_algorithm_t alg,
3622                                 const uint8_t *input,
3623                                 size_t input_length,
3624                                 uint8_t *output,
3625                                 size_t output_size,
3626                                 size_t *output_length)
3627 {
3628     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3629     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
3630     psa_key_attributes_t attributes;
3631     psa_key_slot_t *slot = NULL;
3632 
3633     if (!PSA_ALG_IS_CIPHER(alg)) {
3634         status = PSA_ERROR_INVALID_ARGUMENT;
3635         goto exit;
3636     }
3637 
3638     status = psa_get_and_lock_key_slot_with_policy(key, &slot,
3639                                                    PSA_KEY_USAGE_DECRYPT,
3640                                                    alg);
3641     if (status != PSA_SUCCESS) {
3642         goto exit;
3643     }
3644 
3645     attributes = (psa_key_attributes_t) {
3646         .core = slot->attr
3647     };
3648 
3649     if (input_length < PSA_CIPHER_IV_LENGTH(slot->attr.type, alg)) {
3650         status = PSA_ERROR_INVALID_ARGUMENT;
3651         goto exit;
3652     }
3653 
3654     status = psa_driver_wrapper_cipher_decrypt(
3655         &attributes, slot->key.data, slot->key.bytes,
3656         alg, input, input_length,
3657         output, output_size, output_length);
3658 
3659 exit:
3660     unlock_status = psa_unlock_key_slot(slot);
3661     if (status == PSA_SUCCESS) {
3662         status = unlock_status;
3663     }
3664 
3665     if (status != PSA_SUCCESS) {
3666         *output_length = 0;
3667     }
3668 
3669     return status;
3670 }
3671 
3672 
3673 /****************************************************************/
3674 /* AEAD */
3675 /****************************************************************/
3676 
psa_aead_encrypt(mbedtls_svc_key_id_t key,psa_algorithm_t alg,const uint8_t * nonce,size_t nonce_length,const uint8_t * additional_data,size_t additional_data_length,const uint8_t * plaintext,size_t plaintext_length,uint8_t * ciphertext,size_t ciphertext_size,size_t * ciphertext_length)3677 psa_status_t psa_aead_encrypt(mbedtls_svc_key_id_t key,
3678                               psa_algorithm_t alg,
3679                               const uint8_t *nonce,
3680                               size_t nonce_length,
3681                               const uint8_t *additional_data,
3682                               size_t additional_data_length,
3683                               const uint8_t *plaintext,
3684                               size_t plaintext_length,
3685                               uint8_t *ciphertext,
3686                               size_t ciphertext_size,
3687                               size_t *ciphertext_length)
3688 {
3689     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3690     psa_key_slot_t *slot;
3691 
3692     *ciphertext_length = 0;
3693 
3694     if (!PSA_ALG_IS_AEAD(alg) || PSA_ALG_IS_WILDCARD(alg)) {
3695         return PSA_ERROR_NOT_SUPPORTED;
3696     }
3697 
3698     status = psa_get_and_lock_key_slot_with_policy(
3699         key, &slot, PSA_KEY_USAGE_ENCRYPT, alg);
3700     if (status != PSA_SUCCESS) {
3701         return status;
3702     }
3703 
3704     psa_key_attributes_t attributes = {
3705         .core = slot->attr
3706     };
3707 
3708     status = psa_driver_wrapper_aead_encrypt(
3709         &attributes, slot->key.data, slot->key.bytes,
3710         alg,
3711         nonce, nonce_length,
3712         additional_data, additional_data_length,
3713         plaintext, plaintext_length,
3714         ciphertext, ciphertext_size, ciphertext_length);
3715 
3716     if (status != PSA_SUCCESS && ciphertext_size != 0) {
3717         memset(ciphertext, 0, ciphertext_size);
3718     }
3719 
3720     psa_unlock_key_slot(slot);
3721 
3722     return status;
3723 }
3724 
psa_aead_decrypt(mbedtls_svc_key_id_t key,psa_algorithm_t alg,const uint8_t * nonce,size_t nonce_length,const uint8_t * additional_data,size_t additional_data_length,const uint8_t * ciphertext,size_t ciphertext_length,uint8_t * plaintext,size_t plaintext_size,size_t * plaintext_length)3725 psa_status_t psa_aead_decrypt(mbedtls_svc_key_id_t key,
3726                               psa_algorithm_t alg,
3727                               const uint8_t *nonce,
3728                               size_t nonce_length,
3729                               const uint8_t *additional_data,
3730                               size_t additional_data_length,
3731                               const uint8_t *ciphertext,
3732                               size_t ciphertext_length,
3733                               uint8_t *plaintext,
3734                               size_t plaintext_size,
3735                               size_t *plaintext_length)
3736 {
3737     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3738     psa_key_slot_t *slot;
3739 
3740     *plaintext_length = 0;
3741 
3742     if (!PSA_ALG_IS_AEAD(alg) || PSA_ALG_IS_WILDCARD(alg)) {
3743         return PSA_ERROR_NOT_SUPPORTED;
3744     }
3745 
3746     status = psa_get_and_lock_key_slot_with_policy(
3747         key, &slot, PSA_KEY_USAGE_DECRYPT, alg);
3748     if (status != PSA_SUCCESS) {
3749         return status;
3750     }
3751 
3752     psa_key_attributes_t attributes = {
3753         .core = slot->attr
3754     };
3755 
3756     status = psa_driver_wrapper_aead_decrypt(
3757         &attributes, slot->key.data, slot->key.bytes,
3758         alg,
3759         nonce, nonce_length,
3760         additional_data, additional_data_length,
3761         ciphertext, ciphertext_length,
3762         plaintext, plaintext_size, plaintext_length);
3763 
3764     if (status != PSA_SUCCESS && plaintext_size != 0) {
3765         memset(plaintext, 0, plaintext_size);
3766     }
3767 
3768     psa_unlock_key_slot(slot);
3769 
3770     return status;
3771 }
3772 
3773 /****************************************************************/
3774 /* Generators */
3775 /****************************************************************/
3776 
3777 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF) || \
3778     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
3779     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
3780 #define AT_LEAST_ONE_BUILTIN_KDF
3781 #endif /* At least one builtin KDF */
3782 
3783 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF) || \
3784     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
3785     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
psa_key_derivation_start_hmac(psa_mac_operation_t * operation,psa_algorithm_t hash_alg,const uint8_t * hmac_key,size_t hmac_key_length)3786 static psa_status_t psa_key_derivation_start_hmac(
3787     psa_mac_operation_t *operation,
3788     psa_algorithm_t hash_alg,
3789     const uint8_t *hmac_key,
3790     size_t hmac_key_length)
3791 {
3792     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3793     psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
3794     psa_set_key_type(&attributes, PSA_KEY_TYPE_HMAC);
3795     psa_set_key_bits(&attributes, PSA_BYTES_TO_BITS(hmac_key_length));
3796     psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_HASH);
3797 
3798     operation->is_sign = 1;
3799     operation->mac_size = PSA_HASH_LENGTH(hash_alg);
3800 
3801     status = psa_driver_wrapper_mac_sign_setup(operation,
3802                                                &attributes,
3803                                                hmac_key, hmac_key_length,
3804                                                PSA_ALG_HMAC(hash_alg));
3805 
3806     psa_reset_key_attributes(&attributes);
3807     return status;
3808 }
3809 #endif /* KDF algorithms reliant on HMAC */
3810 
3811 #define HKDF_STATE_INIT 0 /* no input yet */
3812 #define HKDF_STATE_STARTED 1 /* got salt */
3813 #define HKDF_STATE_KEYED 2 /* got key */
3814 #define HKDF_STATE_OUTPUT 3 /* output started */
3815 
psa_key_derivation_get_kdf_alg(const psa_key_derivation_operation_t * operation)3816 static psa_algorithm_t psa_key_derivation_get_kdf_alg(
3817     const psa_key_derivation_operation_t *operation)
3818 {
3819     if (PSA_ALG_IS_KEY_AGREEMENT(operation->alg)) {
3820         return PSA_ALG_KEY_AGREEMENT_GET_KDF(operation->alg);
3821     } else {
3822         return operation->alg;
3823     }
3824 }
3825 
psa_key_derivation_abort(psa_key_derivation_operation_t * operation)3826 psa_status_t psa_key_derivation_abort(psa_key_derivation_operation_t *operation)
3827 {
3828     psa_status_t status = PSA_SUCCESS;
3829     psa_algorithm_t kdf_alg = psa_key_derivation_get_kdf_alg(operation);
3830     if (kdf_alg == 0) {
3831         /* The object has (apparently) been initialized but it is not
3832          * in use. It's ok to call abort on such an object, and there's
3833          * nothing to do. */
3834     } else
3835 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF)
3836     if (PSA_ALG_IS_HKDF(kdf_alg)) {
3837         mbedtls_free(operation->ctx.hkdf.info);
3838         status = psa_mac_abort(&operation->ctx.hkdf.hmac);
3839     } else
3840 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF */
3841 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
3842     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
3843     if (PSA_ALG_IS_TLS12_PRF(kdf_alg) ||
3844         /* TLS-1.2 PSK-to-MS KDF uses the same core as TLS-1.2 PRF */
3845         PSA_ALG_IS_TLS12_PSK_TO_MS(kdf_alg)) {
3846         if (operation->ctx.tls12_prf.secret != NULL) {
3847             mbedtls_platform_zeroize(operation->ctx.tls12_prf.secret,
3848                                      operation->ctx.tls12_prf.secret_length);
3849             mbedtls_free(operation->ctx.tls12_prf.secret);
3850         }
3851 
3852         if (operation->ctx.tls12_prf.seed != NULL) {
3853             mbedtls_platform_zeroize(operation->ctx.tls12_prf.seed,
3854                                      operation->ctx.tls12_prf.seed_length);
3855             mbedtls_free(operation->ctx.tls12_prf.seed);
3856         }
3857 
3858         if (operation->ctx.tls12_prf.label != NULL) {
3859             mbedtls_platform_zeroize(operation->ctx.tls12_prf.label,
3860                                      operation->ctx.tls12_prf.label_length);
3861             mbedtls_free(operation->ctx.tls12_prf.label);
3862         }
3863 
3864         status = PSA_SUCCESS;
3865 
3866         /* We leave the fields Ai and output_block to be erased safely by the
3867          * mbedtls_platform_zeroize() in the end of this function. */
3868     } else
3869 #endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) ||
3870         * defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS) */
3871     {
3872         status = PSA_ERROR_BAD_STATE;
3873     }
3874     mbedtls_platform_zeroize(operation, sizeof(*operation));
3875     return status;
3876 }
3877 
psa_key_derivation_get_capacity(const psa_key_derivation_operation_t * operation,size_t * capacity)3878 psa_status_t psa_key_derivation_get_capacity(const psa_key_derivation_operation_t *operation,
3879                                              size_t *capacity)
3880 {
3881     if (operation->alg == 0) {
3882         /* This is a blank key derivation operation. */
3883         return PSA_ERROR_BAD_STATE;
3884     }
3885 
3886     *capacity = operation->capacity;
3887     return PSA_SUCCESS;
3888 }
3889 
psa_key_derivation_set_capacity(psa_key_derivation_operation_t * operation,size_t capacity)3890 psa_status_t psa_key_derivation_set_capacity(psa_key_derivation_operation_t *operation,
3891                                              size_t capacity)
3892 {
3893     if (operation->alg == 0) {
3894         return PSA_ERROR_BAD_STATE;
3895     }
3896     if (capacity > operation->capacity) {
3897         return PSA_ERROR_INVALID_ARGUMENT;
3898     }
3899     operation->capacity = capacity;
3900     return PSA_SUCCESS;
3901 }
3902 
3903 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF)
3904 /* Read some bytes from an HKDF-based operation. This performs a chunk
3905  * of the expand phase of the HKDF algorithm. */
psa_key_derivation_hkdf_read(psa_hkdf_key_derivation_t * hkdf,psa_algorithm_t hash_alg,uint8_t * output,size_t output_length)3906 static psa_status_t psa_key_derivation_hkdf_read(psa_hkdf_key_derivation_t *hkdf,
3907                                                  psa_algorithm_t hash_alg,
3908                                                  uint8_t *output,
3909                                                  size_t output_length)
3910 {
3911     uint8_t hash_length = PSA_HASH_LENGTH(hash_alg);
3912     size_t hmac_output_length;
3913     psa_status_t status;
3914 
3915     if (hkdf->state < HKDF_STATE_KEYED || !hkdf->info_set) {
3916         return PSA_ERROR_BAD_STATE;
3917     }
3918     hkdf->state = HKDF_STATE_OUTPUT;
3919 
3920     while (output_length != 0) {
3921         /* Copy what remains of the current block */
3922         uint8_t n = hash_length - hkdf->offset_in_block;
3923         if (n > output_length) {
3924             n = (uint8_t) output_length;
3925         }
3926         memcpy(output, hkdf->output_block + hkdf->offset_in_block, n);
3927         output += n;
3928         output_length -= n;
3929         hkdf->offset_in_block += n;
3930         if (output_length == 0) {
3931             break;
3932         }
3933         /* We can't be wanting more output after block 0xff, otherwise
3934          * the capacity check in psa_key_derivation_output_bytes() would have
3935          * prevented this call. It could happen only if the operation
3936          * object was corrupted or if this function is called directly
3937          * inside the library. */
3938         if (hkdf->block_number == 0xff) {
3939             return PSA_ERROR_BAD_STATE;
3940         }
3941 
3942         /* We need a new block */
3943         ++hkdf->block_number;
3944         hkdf->offset_in_block = 0;
3945 
3946         status = psa_key_derivation_start_hmac(&hkdf->hmac,
3947                                                hash_alg,
3948                                                hkdf->prk,
3949                                                hash_length);
3950         if (status != PSA_SUCCESS) {
3951             return status;
3952         }
3953 
3954         if (hkdf->block_number != 1) {
3955             status = psa_mac_update(&hkdf->hmac,
3956                                     hkdf->output_block,
3957                                     hash_length);
3958             if (status != PSA_SUCCESS) {
3959                 return status;
3960             }
3961         }
3962         status = psa_mac_update(&hkdf->hmac,
3963                                 hkdf->info,
3964                                 hkdf->info_length);
3965         if (status != PSA_SUCCESS) {
3966             return status;
3967         }
3968         status = psa_mac_update(&hkdf->hmac,
3969                                 &hkdf->block_number, 1);
3970         if (status != PSA_SUCCESS) {
3971             return status;
3972         }
3973         status = psa_mac_sign_finish(&hkdf->hmac,
3974                                      hkdf->output_block,
3975                                      sizeof(hkdf->output_block),
3976                                      &hmac_output_length);
3977         if (status != PSA_SUCCESS) {
3978             return status;
3979         }
3980     }
3981 
3982     return PSA_SUCCESS;
3983 }
3984 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF */
3985 
3986 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
3987     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
psa_key_derivation_tls12_prf_generate_next_block(psa_tls12_prf_key_derivation_t * tls12_prf,psa_algorithm_t alg)3988 static psa_status_t psa_key_derivation_tls12_prf_generate_next_block(
3989     psa_tls12_prf_key_derivation_t *tls12_prf,
3990     psa_algorithm_t alg)
3991 {
3992     psa_algorithm_t hash_alg = PSA_ALG_HKDF_GET_HASH(alg);
3993     uint8_t hash_length = PSA_HASH_LENGTH(hash_alg);
3994     psa_mac_operation_t hmac = PSA_MAC_OPERATION_INIT;
3995     size_t hmac_output_length;
3996     psa_status_t status, cleanup_status;
3997 
3998     /* We can't be wanting more output after block 0xff, otherwise
3999      * the capacity check in psa_key_derivation_output_bytes() would have
4000      * prevented this call. It could happen only if the operation
4001      * object was corrupted or if this function is called directly
4002      * inside the library. */
4003     if (tls12_prf->block_number == 0xff) {
4004         return PSA_ERROR_CORRUPTION_DETECTED;
4005     }
4006 
4007     /* We need a new block */
4008     ++tls12_prf->block_number;
4009     tls12_prf->left_in_block = hash_length;
4010 
4011     /* Recall the definition of the TLS-1.2-PRF from RFC 5246:
4012      *
4013      * PRF(secret, label, seed) = P_<hash>(secret, label + seed)
4014      *
4015      * P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
4016      *                        HMAC_hash(secret, A(2) + seed) +
4017      *                        HMAC_hash(secret, A(3) + seed) + ...
4018      *
4019      * A(0) = seed
4020      * A(i) = HMAC_hash(secret, A(i-1))
4021      *
4022      * The `psa_tls12_prf_key_derivation` structure saves the block
4023      * `HMAC_hash(secret, A(i) + seed)` from which the output
4024      * is currently extracted as `output_block` and where i is
4025      * `block_number`.
4026      */
4027 
4028     status = psa_key_derivation_start_hmac(&hmac,
4029                                            hash_alg,
4030                                            tls12_prf->secret,
4031                                            tls12_prf->secret_length);
4032     if (status != PSA_SUCCESS) {
4033         goto cleanup;
4034     }
4035 
4036     /* Calculate A(i) where i = tls12_prf->block_number. */
4037     if (tls12_prf->block_number == 1) {
4038         /* A(1) = HMAC_hash(secret, A(0)), where A(0) = seed. (The RFC overloads
4039          * the variable seed and in this instance means it in the context of the
4040          * P_hash function, where seed = label + seed.) */
4041         status = psa_mac_update(&hmac,
4042                                 tls12_prf->label,
4043                                 tls12_prf->label_length);
4044         if (status != PSA_SUCCESS) {
4045             goto cleanup;
4046         }
4047         status = psa_mac_update(&hmac,
4048                                 tls12_prf->seed,
4049                                 tls12_prf->seed_length);
4050         if (status != PSA_SUCCESS) {
4051             goto cleanup;
4052         }
4053     } else {
4054         /* A(i) = HMAC_hash(secret, A(i-1)) */
4055         status = psa_mac_update(&hmac, tls12_prf->Ai, hash_length);
4056         if (status != PSA_SUCCESS) {
4057             goto cleanup;
4058         }
4059     }
4060 
4061     status = psa_mac_sign_finish(&hmac,
4062                                  tls12_prf->Ai, hash_length,
4063                                  &hmac_output_length);
4064     if (hmac_output_length != hash_length) {
4065         status = PSA_ERROR_CORRUPTION_DETECTED;
4066     }
4067     if (status != PSA_SUCCESS) {
4068         goto cleanup;
4069     }
4070 
4071     /* Calculate HMAC_hash(secret, A(i) + label + seed). */
4072     status = psa_key_derivation_start_hmac(&hmac,
4073                                            hash_alg,
4074                                            tls12_prf->secret,
4075                                            tls12_prf->secret_length);
4076     if (status != PSA_SUCCESS) {
4077         goto cleanup;
4078     }
4079     status = psa_mac_update(&hmac, tls12_prf->Ai, hash_length);
4080     if (status != PSA_SUCCESS) {
4081         goto cleanup;
4082     }
4083     status = psa_mac_update(&hmac, tls12_prf->label, tls12_prf->label_length);
4084     if (status != PSA_SUCCESS) {
4085         goto cleanup;
4086     }
4087     status = psa_mac_update(&hmac, tls12_prf->seed, tls12_prf->seed_length);
4088     if (status != PSA_SUCCESS) {
4089         goto cleanup;
4090     }
4091     status = psa_mac_sign_finish(&hmac,
4092                                  tls12_prf->output_block, hash_length,
4093                                  &hmac_output_length);
4094     if (status != PSA_SUCCESS) {
4095         goto cleanup;
4096     }
4097 
4098 
4099 cleanup:
4100     cleanup_status = psa_mac_abort(&hmac);
4101     if (status == PSA_SUCCESS && cleanup_status != PSA_SUCCESS) {
4102         status = cleanup_status;
4103     }
4104 
4105     return status;
4106 }
4107 
psa_key_derivation_tls12_prf_read(psa_tls12_prf_key_derivation_t * tls12_prf,psa_algorithm_t alg,uint8_t * output,size_t output_length)4108 static psa_status_t psa_key_derivation_tls12_prf_read(
4109     psa_tls12_prf_key_derivation_t *tls12_prf,
4110     psa_algorithm_t alg,
4111     uint8_t *output,
4112     size_t output_length)
4113 {
4114     psa_algorithm_t hash_alg = PSA_ALG_TLS12_PRF_GET_HASH(alg);
4115     uint8_t hash_length = PSA_HASH_LENGTH(hash_alg);
4116     psa_status_t status;
4117     uint8_t offset, length;
4118 
4119     switch (tls12_prf->state) {
4120         case PSA_TLS12_PRF_STATE_LABEL_SET:
4121             tls12_prf->state = PSA_TLS12_PRF_STATE_OUTPUT;
4122             break;
4123         case PSA_TLS12_PRF_STATE_OUTPUT:
4124             break;
4125         default:
4126             return PSA_ERROR_BAD_STATE;
4127     }
4128 
4129     while (output_length != 0) {
4130         /* Check if we have fully processed the current block. */
4131         if (tls12_prf->left_in_block == 0) {
4132             status = psa_key_derivation_tls12_prf_generate_next_block(tls12_prf,
4133                                                                       alg);
4134             if (status != PSA_SUCCESS) {
4135                 return status;
4136             }
4137 
4138             continue;
4139         }
4140 
4141         if (tls12_prf->left_in_block > output_length) {
4142             length = (uint8_t) output_length;
4143         } else {
4144             length = tls12_prf->left_in_block;
4145         }
4146 
4147         offset = hash_length - tls12_prf->left_in_block;
4148         memcpy(output, tls12_prf->output_block + offset, length);
4149         output += length;
4150         output_length -= length;
4151         tls12_prf->left_in_block -= length;
4152     }
4153 
4154     return PSA_SUCCESS;
4155 }
4156 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF ||
4157         * MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
4158 
psa_key_derivation_output_bytes(psa_key_derivation_operation_t * operation,uint8_t * output,size_t output_length)4159 psa_status_t psa_key_derivation_output_bytes(
4160     psa_key_derivation_operation_t *operation,
4161     uint8_t *output,
4162     size_t output_length)
4163 {
4164     psa_status_t status;
4165     psa_algorithm_t kdf_alg = psa_key_derivation_get_kdf_alg(operation);
4166 
4167     if (operation->alg == 0) {
4168         /* This is a blank operation. */
4169         return PSA_ERROR_BAD_STATE;
4170     }
4171 
4172     if (output_length > operation->capacity) {
4173         operation->capacity = 0;
4174         /* Go through the error path to wipe all confidential data now
4175          * that the operation object is useless. */
4176         status = PSA_ERROR_INSUFFICIENT_DATA;
4177         goto exit;
4178     }
4179     if (output_length == 0 && operation->capacity == 0) {
4180         /* Edge case: this is a finished operation, and 0 bytes
4181          * were requested. The right error in this case could
4182          * be either INSUFFICIENT_CAPACITY or BAD_STATE. Return
4183          * INSUFFICIENT_CAPACITY, which is right for a finished
4184          * operation, for consistency with the case when
4185          * output_length > 0. */
4186         return PSA_ERROR_INSUFFICIENT_DATA;
4187     }
4188     operation->capacity -= output_length;
4189 
4190 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF)
4191     if (PSA_ALG_IS_HKDF(kdf_alg)) {
4192         psa_algorithm_t hash_alg = PSA_ALG_HKDF_GET_HASH(kdf_alg);
4193         status = psa_key_derivation_hkdf_read(&operation->ctx.hkdf, hash_alg,
4194                                               output, output_length);
4195     } else
4196 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF */
4197 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
4198     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
4199     if (PSA_ALG_IS_TLS12_PRF(kdf_alg) ||
4200         PSA_ALG_IS_TLS12_PSK_TO_MS(kdf_alg)) {
4201         status = psa_key_derivation_tls12_prf_read(&operation->ctx.tls12_prf,
4202                                                    kdf_alg, output,
4203                                                    output_length);
4204     } else
4205 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF ||
4206         * MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
4207     {
4208         (void) kdf_alg;
4209         return PSA_ERROR_BAD_STATE;
4210     }
4211 
4212 exit:
4213     if (status != PSA_SUCCESS) {
4214         /* Preserve the algorithm upon errors, but clear all sensitive state.
4215          * This allows us to differentiate between exhausted operations and
4216          * blank operations, so we can return PSA_ERROR_BAD_STATE on blank
4217          * operations. */
4218         psa_algorithm_t alg = operation->alg;
4219         psa_key_derivation_abort(operation);
4220         operation->alg = alg;
4221         memset(output, '!', output_length);
4222     }
4223     return status;
4224 }
4225 
4226 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES)
psa_des_set_key_parity(uint8_t * data,size_t data_size)4227 static void psa_des_set_key_parity(uint8_t *data, size_t data_size)
4228 {
4229     if (data_size >= 8) {
4230         mbedtls_des_key_set_parity(data);
4231     }
4232     if (data_size >= 16) {
4233         mbedtls_des_key_set_parity(data + 8);
4234     }
4235     if (data_size >= 24) {
4236         mbedtls_des_key_set_parity(data + 16);
4237     }
4238 }
4239 #endif /* MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES */
4240 
psa_generate_derived_key_internal(psa_key_slot_t * slot,size_t bits,psa_key_derivation_operation_t * operation)4241 static psa_status_t psa_generate_derived_key_internal(
4242     psa_key_slot_t *slot,
4243     size_t bits,
4244     psa_key_derivation_operation_t *operation)
4245 {
4246     uint8_t *data = NULL;
4247     size_t bytes = PSA_BITS_TO_BYTES(bits);
4248     psa_status_t status;
4249     psa_key_attributes_t attributes;
4250 
4251     if (!key_type_is_raw_bytes(slot->attr.type)) {
4252         return PSA_ERROR_INVALID_ARGUMENT;
4253     }
4254     if (bits % 8 != 0) {
4255         return PSA_ERROR_INVALID_ARGUMENT;
4256     }
4257     data = mbedtls_calloc(1, bytes);
4258     if (data == NULL) {
4259         return PSA_ERROR_INSUFFICIENT_MEMORY;
4260     }
4261 
4262     status = psa_key_derivation_output_bytes(operation, data, bytes);
4263     if (status != PSA_SUCCESS) {
4264         goto exit;
4265     }
4266 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES)
4267     if (slot->attr.type == PSA_KEY_TYPE_DES) {
4268         psa_des_set_key_parity(data, bytes);
4269     }
4270 #endif /* MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES */
4271 
4272     status = psa_allocate_buffer_to_slot(slot, bytes);
4273     if (status != PSA_SUCCESS) {
4274         goto exit;
4275     }
4276 
4277     slot->attr.bits = (psa_key_bits_t) bits;
4278     attributes = (psa_key_attributes_t) {
4279         .core = slot->attr
4280     };
4281 
4282     status = psa_driver_wrapper_import_key(&attributes,
4283                                            data, bytes,
4284                                            slot->key.data,
4285                                            slot->key.bytes,
4286                                            &slot->key.bytes, &bits);
4287     if (bits != slot->attr.bits) {
4288         status = PSA_ERROR_INVALID_ARGUMENT;
4289     }
4290 
4291 exit:
4292     mbedtls_free(data);
4293     return status;
4294 }
4295 
psa_key_derivation_output_key(const psa_key_attributes_t * attributes,psa_key_derivation_operation_t * operation,mbedtls_svc_key_id_t * key)4296 psa_status_t psa_key_derivation_output_key(const psa_key_attributes_t *attributes,
4297                                            psa_key_derivation_operation_t *operation,
4298                                            mbedtls_svc_key_id_t *key)
4299 {
4300     psa_status_t status;
4301     psa_key_slot_t *slot = NULL;
4302     psa_se_drv_table_entry_t *driver = NULL;
4303 
4304     *key = MBEDTLS_SVC_KEY_ID_INIT;
4305 
4306     /* Reject any attempt to create a zero-length key so that we don't
4307      * risk tripping up later, e.g. on a malloc(0) that returns NULL. */
4308     if (psa_get_key_bits(attributes) == 0) {
4309         return PSA_ERROR_INVALID_ARGUMENT;
4310     }
4311 
4312     if (operation->alg == PSA_ALG_NONE) {
4313         return PSA_ERROR_BAD_STATE;
4314     }
4315 
4316     if (!operation->can_output_key) {
4317         return PSA_ERROR_NOT_PERMITTED;
4318     }
4319 
4320     status = psa_start_key_creation(PSA_KEY_CREATION_DERIVE, attributes,
4321                                     &slot, &driver);
4322 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
4323     if (driver != NULL) {
4324         /* Deriving a key in a secure element is not implemented yet. */
4325         status = PSA_ERROR_NOT_SUPPORTED;
4326     }
4327 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
4328     if (status == PSA_SUCCESS) {
4329         status = psa_generate_derived_key_internal(slot,
4330                                                    attributes->core.bits,
4331                                                    operation);
4332     }
4333     if (status == PSA_SUCCESS) {
4334         status = psa_finish_key_creation(slot, driver, key);
4335     }
4336     if (status != PSA_SUCCESS) {
4337         psa_fail_key_creation(slot, driver);
4338     }
4339 
4340     return status;
4341 }
4342 
4343 
4344 
4345 /****************************************************************/
4346 /* Key derivation */
4347 /****************************************************************/
4348 
4349 #if defined(AT_LEAST_ONE_BUILTIN_KDF)
is_kdf_alg_supported(psa_algorithm_t kdf_alg)4350 static int is_kdf_alg_supported(psa_algorithm_t kdf_alg)
4351 {
4352 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF)
4353     if (PSA_ALG_IS_HKDF(kdf_alg)) {
4354         return 1;
4355     }
4356 #endif
4357 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF)
4358     if (PSA_ALG_IS_TLS12_PRF(kdf_alg)) {
4359         return 1;
4360     }
4361 #endif
4362 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
4363     if (PSA_ALG_IS_TLS12_PSK_TO_MS(kdf_alg)) {
4364         return 1;
4365     }
4366 #endif
4367     return 0;
4368 }
4369 
psa_hash_try_support(psa_algorithm_t alg)4370 static psa_status_t psa_hash_try_support(psa_algorithm_t alg)
4371 {
4372     psa_hash_operation_t operation = PSA_HASH_OPERATION_INIT;
4373     psa_status_t status = psa_hash_setup(&operation, alg);
4374     psa_hash_abort(&operation);
4375     return status;
4376 }
4377 
psa_key_derivation_setup_kdf(psa_key_derivation_operation_t * operation,psa_algorithm_t kdf_alg)4378 static psa_status_t psa_key_derivation_setup_kdf(
4379     psa_key_derivation_operation_t *operation,
4380     psa_algorithm_t kdf_alg)
4381 {
4382     /* Make sure that operation->ctx is properly zero-initialised. (Macro
4383      * initialisers for this union leave some bytes unspecified.) */
4384     memset(&operation->ctx, 0, sizeof(operation->ctx));
4385 
4386     /* Make sure that kdf_alg is a supported key derivation algorithm. */
4387     if (!is_kdf_alg_supported(kdf_alg)) {
4388         return PSA_ERROR_NOT_SUPPORTED;
4389     }
4390 
4391     /* All currently supported key derivation algorithms are based on a
4392      * hash algorithm. */
4393     psa_algorithm_t hash_alg = PSA_ALG_HKDF_GET_HASH(kdf_alg);
4394     size_t hash_size = PSA_HASH_LENGTH(hash_alg);
4395     if (hash_size == 0) {
4396         return PSA_ERROR_NOT_SUPPORTED;
4397     }
4398 
4399     /* Make sure that hash_alg is a supported hash algorithm. Otherwise
4400      * we might fail later, which is somewhat unfriendly and potentially
4401      * risk-prone. */
4402     psa_status_t status = psa_hash_try_support(hash_alg);
4403     if (status != PSA_SUCCESS) {
4404         return status;
4405     }
4406 
4407     if ((PSA_ALG_IS_TLS12_PRF(kdf_alg) ||
4408          PSA_ALG_IS_TLS12_PSK_TO_MS(kdf_alg)) &&
4409         !(hash_alg == PSA_ALG_SHA_256 || hash_alg == PSA_ALG_SHA_384)) {
4410         return PSA_ERROR_NOT_SUPPORTED;
4411     }
4412 
4413     operation->capacity = 255 * hash_size;
4414     return PSA_SUCCESS;
4415 }
4416 
psa_key_agreement_try_support(psa_algorithm_t alg)4417 static psa_status_t psa_key_agreement_try_support(psa_algorithm_t alg)
4418 {
4419 #if defined(PSA_WANT_ALG_ECDH)
4420     if (alg == PSA_ALG_ECDH) {
4421         return PSA_SUCCESS;
4422     }
4423 #endif
4424     (void) alg;
4425     return PSA_ERROR_NOT_SUPPORTED;
4426 }
4427 #endif /* AT_LEAST_ONE_BUILTIN_KDF */
4428 
psa_key_derivation_setup(psa_key_derivation_operation_t * operation,psa_algorithm_t alg)4429 psa_status_t psa_key_derivation_setup(psa_key_derivation_operation_t *operation,
4430                                       psa_algorithm_t alg)
4431 {
4432     psa_status_t status;
4433 
4434     if (operation->alg != 0) {
4435         return PSA_ERROR_BAD_STATE;
4436     }
4437 
4438     if (PSA_ALG_IS_RAW_KEY_AGREEMENT(alg)) {
4439         return PSA_ERROR_INVALID_ARGUMENT;
4440     } else if (PSA_ALG_IS_KEY_AGREEMENT(alg)) {
4441 #if defined(AT_LEAST_ONE_BUILTIN_KDF)
4442         psa_algorithm_t kdf_alg = PSA_ALG_KEY_AGREEMENT_GET_KDF(alg);
4443         psa_algorithm_t ka_alg = PSA_ALG_KEY_AGREEMENT_GET_BASE(alg);
4444         status = psa_key_agreement_try_support(ka_alg);
4445         if (status != PSA_SUCCESS) {
4446             return status;
4447         }
4448         status = psa_key_derivation_setup_kdf(operation, kdf_alg);
4449 #else
4450         return PSA_ERROR_NOT_SUPPORTED;
4451 #endif /* AT_LEAST_ONE_BUILTIN_KDF */
4452     } else if (PSA_ALG_IS_KEY_DERIVATION(alg)) {
4453 #if defined(AT_LEAST_ONE_BUILTIN_KDF)
4454         status = psa_key_derivation_setup_kdf(operation, alg);
4455 #else
4456         return PSA_ERROR_NOT_SUPPORTED;
4457 #endif /* AT_LEAST_ONE_BUILTIN_KDF */
4458     } else {
4459         return PSA_ERROR_INVALID_ARGUMENT;
4460     }
4461 
4462     if (status == PSA_SUCCESS) {
4463         operation->alg = alg;
4464     }
4465     return status;
4466 }
4467 
4468 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF)
psa_hkdf_input(psa_hkdf_key_derivation_t * hkdf,psa_algorithm_t hash_alg,psa_key_derivation_step_t step,const uint8_t * data,size_t data_length)4469 static psa_status_t psa_hkdf_input(psa_hkdf_key_derivation_t *hkdf,
4470                                    psa_algorithm_t hash_alg,
4471                                    psa_key_derivation_step_t step,
4472                                    const uint8_t *data,
4473                                    size_t data_length)
4474 {
4475     psa_status_t status;
4476     switch (step) {
4477         case PSA_KEY_DERIVATION_INPUT_SALT:
4478             if (hkdf->state != HKDF_STATE_INIT) {
4479                 return PSA_ERROR_BAD_STATE;
4480             } else {
4481                 status = psa_key_derivation_start_hmac(&hkdf->hmac,
4482                                                        hash_alg,
4483                                                        data, data_length);
4484                 if (status != PSA_SUCCESS) {
4485                     return status;
4486                 }
4487                 hkdf->state = HKDF_STATE_STARTED;
4488                 return PSA_SUCCESS;
4489             }
4490         case PSA_KEY_DERIVATION_INPUT_SECRET:
4491             /* If no salt was provided, use an empty salt. */
4492             if (hkdf->state == HKDF_STATE_INIT) {
4493                 status = psa_key_derivation_start_hmac(&hkdf->hmac,
4494                                                        hash_alg,
4495                                                        NULL, 0);
4496                 if (status != PSA_SUCCESS) {
4497                     return status;
4498                 }
4499                 hkdf->state = HKDF_STATE_STARTED;
4500             }
4501             if (hkdf->state != HKDF_STATE_STARTED) {
4502                 return PSA_ERROR_BAD_STATE;
4503             }
4504             status = psa_mac_update(&hkdf->hmac,
4505                                     data, data_length);
4506             if (status != PSA_SUCCESS) {
4507                 return status;
4508             }
4509             status = psa_mac_sign_finish(&hkdf->hmac,
4510                                          hkdf->prk,
4511                                          sizeof(hkdf->prk),
4512                                          &data_length);
4513             if (status != PSA_SUCCESS) {
4514                 return status;
4515             }
4516             hkdf->offset_in_block = PSA_HASH_LENGTH(hash_alg);
4517             hkdf->block_number = 0;
4518             hkdf->state = HKDF_STATE_KEYED;
4519             return PSA_SUCCESS;
4520         case PSA_KEY_DERIVATION_INPUT_INFO:
4521             if (hkdf->state == HKDF_STATE_OUTPUT) {
4522                 return PSA_ERROR_BAD_STATE;
4523             }
4524             if (hkdf->info_set) {
4525                 return PSA_ERROR_BAD_STATE;
4526             }
4527             hkdf->info_length = data_length;
4528             if (data_length != 0) {
4529                 hkdf->info = mbedtls_calloc(1, data_length);
4530                 if (hkdf->info == NULL) {
4531                     return PSA_ERROR_INSUFFICIENT_MEMORY;
4532                 }
4533                 memcpy(hkdf->info, data, data_length);
4534             }
4535             hkdf->info_set = 1;
4536             return PSA_SUCCESS;
4537         default:
4538             return PSA_ERROR_INVALID_ARGUMENT;
4539     }
4540 }
4541 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF */
4542 
4543 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
4544     defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
psa_tls12_prf_set_seed(psa_tls12_prf_key_derivation_t * prf,const uint8_t * data,size_t data_length)4545 static psa_status_t psa_tls12_prf_set_seed(psa_tls12_prf_key_derivation_t *prf,
4546                                            const uint8_t *data,
4547                                            size_t data_length)
4548 {
4549     if (prf->state != PSA_TLS12_PRF_STATE_INIT) {
4550         return PSA_ERROR_BAD_STATE;
4551     }
4552 
4553     if (data_length != 0) {
4554         prf->seed = mbedtls_calloc(1, data_length);
4555         if (prf->seed == NULL) {
4556             return PSA_ERROR_INSUFFICIENT_MEMORY;
4557         }
4558 
4559         memcpy(prf->seed, data, data_length);
4560         prf->seed_length = data_length;
4561     }
4562 
4563     prf->state = PSA_TLS12_PRF_STATE_SEED_SET;
4564 
4565     return PSA_SUCCESS;
4566 }
4567 
psa_tls12_prf_set_key(psa_tls12_prf_key_derivation_t * prf,const uint8_t * data,size_t data_length)4568 static psa_status_t psa_tls12_prf_set_key(psa_tls12_prf_key_derivation_t *prf,
4569                                           const uint8_t *data,
4570                                           size_t data_length)
4571 {
4572     if (prf->state != PSA_TLS12_PRF_STATE_SEED_SET) {
4573         return PSA_ERROR_BAD_STATE;
4574     }
4575 
4576     if (data_length != 0) {
4577         prf->secret = mbedtls_calloc(1, data_length);
4578         if (prf->secret == NULL) {
4579             return PSA_ERROR_INSUFFICIENT_MEMORY;
4580         }
4581 
4582         memcpy(prf->secret, data, data_length);
4583         prf->secret_length = data_length;
4584     }
4585 
4586     prf->state = PSA_TLS12_PRF_STATE_KEY_SET;
4587 
4588     return PSA_SUCCESS;
4589 }
4590 
psa_tls12_prf_set_label(psa_tls12_prf_key_derivation_t * prf,const uint8_t * data,size_t data_length)4591 static psa_status_t psa_tls12_prf_set_label(psa_tls12_prf_key_derivation_t *prf,
4592                                             const uint8_t *data,
4593                                             size_t data_length)
4594 {
4595     if (prf->state != PSA_TLS12_PRF_STATE_KEY_SET) {
4596         return PSA_ERROR_BAD_STATE;
4597     }
4598 
4599     if (data_length != 0) {
4600         prf->label = mbedtls_calloc(1, data_length);
4601         if (prf->label == NULL) {
4602             return PSA_ERROR_INSUFFICIENT_MEMORY;
4603         }
4604 
4605         memcpy(prf->label, data, data_length);
4606         prf->label_length = data_length;
4607     }
4608 
4609     prf->state = PSA_TLS12_PRF_STATE_LABEL_SET;
4610 
4611     return PSA_SUCCESS;
4612 }
4613 
psa_tls12_prf_input(psa_tls12_prf_key_derivation_t * prf,psa_key_derivation_step_t step,const uint8_t * data,size_t data_length)4614 static psa_status_t psa_tls12_prf_input(psa_tls12_prf_key_derivation_t *prf,
4615                                         psa_key_derivation_step_t step,
4616                                         const uint8_t *data,
4617                                         size_t data_length)
4618 {
4619     switch (step) {
4620         case PSA_KEY_DERIVATION_INPUT_SEED:
4621             return psa_tls12_prf_set_seed(prf, data, data_length);
4622         case PSA_KEY_DERIVATION_INPUT_SECRET:
4623             return psa_tls12_prf_set_key(prf, data, data_length);
4624         case PSA_KEY_DERIVATION_INPUT_LABEL:
4625             return psa_tls12_prf_set_label(prf, data, data_length);
4626         default:
4627             return PSA_ERROR_INVALID_ARGUMENT;
4628     }
4629 }
4630 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) ||
4631         * MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
4632 
4633 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
psa_tls12_prf_psk_to_ms_set_key(psa_tls12_prf_key_derivation_t * prf,const uint8_t * data,size_t data_length)4634 static psa_status_t psa_tls12_prf_psk_to_ms_set_key(
4635     psa_tls12_prf_key_derivation_t *prf,
4636     const uint8_t *data,
4637     size_t data_length)
4638 {
4639     psa_status_t status;
4640     uint8_t pms[4 + 2 * PSA_TLS12_PSK_TO_MS_PSK_MAX_SIZE];
4641     uint8_t *cur = pms;
4642 
4643     if (data_length > PSA_TLS12_PSK_TO_MS_PSK_MAX_SIZE) {
4644         return PSA_ERROR_INVALID_ARGUMENT;
4645     }
4646 
4647     /* Quoting RFC 4279, Section 2:
4648      *
4649      * The premaster secret is formed as follows: if the PSK is N octets
4650      * long, concatenate a uint16 with the value N, N zero octets, a second
4651      * uint16 with the value N, and the PSK itself.
4652      */
4653 
4654     *cur++ = MBEDTLS_BYTE_1(data_length);
4655     *cur++ = MBEDTLS_BYTE_0(data_length);
4656     memset(cur, 0, data_length);
4657     cur += data_length;
4658     *cur++ = pms[0];
4659     *cur++ = pms[1];
4660     memcpy(cur, data, data_length);
4661     cur += data_length;
4662 
4663     status = psa_tls12_prf_set_key(prf, pms, cur - pms);
4664 
4665     mbedtls_platform_zeroize(pms, sizeof(pms));
4666     return status;
4667 }
4668 
psa_tls12_prf_psk_to_ms_input(psa_tls12_prf_key_derivation_t * prf,psa_key_derivation_step_t step,const uint8_t * data,size_t data_length)4669 static psa_status_t psa_tls12_prf_psk_to_ms_input(
4670     psa_tls12_prf_key_derivation_t *prf,
4671     psa_key_derivation_step_t step,
4672     const uint8_t *data,
4673     size_t data_length)
4674 {
4675     if (step == PSA_KEY_DERIVATION_INPUT_SECRET) {
4676         return psa_tls12_prf_psk_to_ms_set_key(prf,
4677                                                data, data_length);
4678     }
4679 
4680     return psa_tls12_prf_input(prf, step, data, data_length);
4681 }
4682 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
4683 
4684 /** Check whether the given key type is acceptable for the given
4685  * input step of a key derivation.
4686  *
4687  * Secret inputs must have the type #PSA_KEY_TYPE_DERIVE.
4688  * Non-secret inputs must have the type #PSA_KEY_TYPE_RAW_DATA.
4689  * Both secret and non-secret inputs can alternatively have the type
4690  * #PSA_KEY_TYPE_NONE, which is never the type of a key object, meaning
4691  * that the input was passed as a buffer rather than via a key object.
4692  */
psa_key_derivation_check_input_type(psa_key_derivation_step_t step,psa_key_type_t key_type)4693 static int psa_key_derivation_check_input_type(
4694     psa_key_derivation_step_t step,
4695     psa_key_type_t key_type)
4696 {
4697     switch (step) {
4698         case PSA_KEY_DERIVATION_INPUT_SECRET:
4699             if (key_type == PSA_KEY_TYPE_DERIVE) {
4700                 return PSA_SUCCESS;
4701             }
4702             if (key_type == PSA_KEY_TYPE_NONE) {
4703                 return PSA_SUCCESS;
4704             }
4705             break;
4706         case PSA_KEY_DERIVATION_INPUT_LABEL:
4707         case PSA_KEY_DERIVATION_INPUT_SALT:
4708         case PSA_KEY_DERIVATION_INPUT_INFO:
4709         case PSA_KEY_DERIVATION_INPUT_SEED:
4710             if (key_type == PSA_KEY_TYPE_RAW_DATA) {
4711                 return PSA_SUCCESS;
4712             }
4713             if (key_type == PSA_KEY_TYPE_NONE) {
4714                 return PSA_SUCCESS;
4715             }
4716             break;
4717     }
4718     return PSA_ERROR_INVALID_ARGUMENT;
4719 }
4720 
psa_key_derivation_input_internal(psa_key_derivation_operation_t * operation,psa_key_derivation_step_t step,psa_key_type_t key_type,const uint8_t * data,size_t data_length)4721 static psa_status_t psa_key_derivation_input_internal(
4722     psa_key_derivation_operation_t *operation,
4723     psa_key_derivation_step_t step,
4724     psa_key_type_t key_type,
4725     const uint8_t *data,
4726     size_t data_length)
4727 {
4728     psa_status_t status;
4729     psa_algorithm_t kdf_alg = psa_key_derivation_get_kdf_alg(operation);
4730 
4731     status = psa_key_derivation_check_input_type(step, key_type);
4732     if (status != PSA_SUCCESS) {
4733         goto exit;
4734     }
4735 
4736 #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF)
4737     if (PSA_ALG_IS_HKDF(kdf_alg)) {
4738         status = psa_hkdf_input(&operation->ctx.hkdf,
4739                                 PSA_ALG_HKDF_GET_HASH(kdf_alg),
4740                                 step, data, data_length);
4741     } else
4742 #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF */
4743 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF)
4744     if (PSA_ALG_IS_TLS12_PRF(kdf_alg)) {
4745         status = psa_tls12_prf_input(&operation->ctx.tls12_prf,
4746                                      step, data, data_length);
4747     } else
4748 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF */
4749 #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
4750     if (PSA_ALG_IS_TLS12_PSK_TO_MS(kdf_alg)) {
4751         status = psa_tls12_prf_psk_to_ms_input(&operation->ctx.tls12_prf,
4752                                                step, data, data_length);
4753     } else
4754 #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
4755     {
4756         /* This can't happen unless the operation object was not initialized */
4757         (void) data;
4758         (void) data_length;
4759         (void) kdf_alg;
4760         return PSA_ERROR_BAD_STATE;
4761     }
4762 
4763 exit:
4764     if (status != PSA_SUCCESS) {
4765         psa_key_derivation_abort(operation);
4766     }
4767     return status;
4768 }
4769 
psa_key_derivation_input_bytes(psa_key_derivation_operation_t * operation,psa_key_derivation_step_t step,const uint8_t * data,size_t data_length)4770 psa_status_t psa_key_derivation_input_bytes(
4771     psa_key_derivation_operation_t *operation,
4772     psa_key_derivation_step_t step,
4773     const uint8_t *data,
4774     size_t data_length)
4775 {
4776     return psa_key_derivation_input_internal(operation, step,
4777                                              PSA_KEY_TYPE_NONE,
4778                                              data, data_length);
4779 }
4780 
psa_key_derivation_input_key(psa_key_derivation_operation_t * operation,psa_key_derivation_step_t step,mbedtls_svc_key_id_t key)4781 psa_status_t psa_key_derivation_input_key(
4782     psa_key_derivation_operation_t *operation,
4783     psa_key_derivation_step_t step,
4784     mbedtls_svc_key_id_t key)
4785 {
4786     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4787     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
4788     psa_key_slot_t *slot;
4789 
4790     status = psa_get_and_lock_transparent_key_slot_with_policy(
4791         key, &slot, PSA_KEY_USAGE_DERIVE, operation->alg);
4792     if (status != PSA_SUCCESS) {
4793         psa_key_derivation_abort(operation);
4794         return status;
4795     }
4796 
4797     /* Passing a key object as a SECRET input unlocks the permission
4798      * to output to a key object. */
4799     if (step == PSA_KEY_DERIVATION_INPUT_SECRET) {
4800         operation->can_output_key = 1;
4801     }
4802 
4803     status = psa_key_derivation_input_internal(operation,
4804                                                step, slot->attr.type,
4805                                                slot->key.data,
4806                                                slot->key.bytes);
4807 
4808     unlock_status = psa_unlock_key_slot(slot);
4809 
4810     return (status == PSA_SUCCESS) ? unlock_status : status;
4811 }
4812 
4813 
4814 
4815 /****************************************************************/
4816 /* Key agreement */
4817 /****************************************************************/
4818 
4819 #if defined(MBEDTLS_PSA_BUILTIN_ALG_ECDH)
psa_key_agreement_ecdh(const uint8_t * peer_key,size_t peer_key_length,const mbedtls_ecp_keypair * our_key,uint8_t * shared_secret,size_t shared_secret_size,size_t * shared_secret_length)4820 static psa_status_t psa_key_agreement_ecdh(const uint8_t *peer_key,
4821                                            size_t peer_key_length,
4822                                            const mbedtls_ecp_keypair *our_key,
4823                                            uint8_t *shared_secret,
4824                                            size_t shared_secret_size,
4825                                            size_t *shared_secret_length)
4826 {
4827     mbedtls_ecp_keypair *their_key = NULL;
4828     mbedtls_ecdh_context ecdh;
4829     psa_status_t status;
4830     size_t bits = 0;
4831     psa_ecc_family_t curve = mbedtls_ecc_group_to_psa(our_key->grp.id, &bits);
4832     mbedtls_ecdh_init(&ecdh);
4833 
4834     status = mbedtls_psa_ecp_load_representation(
4835         PSA_KEY_TYPE_ECC_PUBLIC_KEY(curve),
4836         bits,
4837         peer_key,
4838         peer_key_length,
4839         &their_key);
4840     if (status != PSA_SUCCESS) {
4841         goto exit;
4842     }
4843 
4844     status = mbedtls_to_psa_error(
4845         mbedtls_ecdh_get_params(&ecdh, their_key, MBEDTLS_ECDH_THEIRS));
4846     if (status != PSA_SUCCESS) {
4847         goto exit;
4848     }
4849     status = mbedtls_to_psa_error(
4850         mbedtls_ecdh_get_params(&ecdh, our_key, MBEDTLS_ECDH_OURS));
4851     if (status != PSA_SUCCESS) {
4852         goto exit;
4853     }
4854 
4855     status = mbedtls_to_psa_error(
4856         mbedtls_ecdh_calc_secret(&ecdh,
4857                                  shared_secret_length,
4858                                  shared_secret, shared_secret_size,
4859                                  mbedtls_psa_get_random,
4860                                  MBEDTLS_PSA_RANDOM_STATE));
4861     if (status != PSA_SUCCESS) {
4862         goto exit;
4863     }
4864     if (PSA_BITS_TO_BYTES(bits) != *shared_secret_length) {
4865         status = PSA_ERROR_CORRUPTION_DETECTED;
4866     }
4867 
4868 exit:
4869     if (status != PSA_SUCCESS) {
4870         mbedtls_platform_zeroize(shared_secret, shared_secret_size);
4871     }
4872     mbedtls_ecdh_free(&ecdh);
4873     mbedtls_ecp_keypair_free(their_key);
4874     mbedtls_free(their_key);
4875 
4876     return status;
4877 }
4878 #endif /* MBEDTLS_PSA_BUILTIN_ALG_ECDH */
4879 
4880 #define PSA_KEY_AGREEMENT_MAX_SHARED_SECRET_SIZE MBEDTLS_ECP_MAX_BYTES
4881 
psa_key_agreement_raw_internal(psa_algorithm_t alg,psa_key_slot_t * private_key,const uint8_t * peer_key,size_t peer_key_length,uint8_t * shared_secret,size_t shared_secret_size,size_t * shared_secret_length)4882 static psa_status_t psa_key_agreement_raw_internal(psa_algorithm_t alg,
4883                                                    psa_key_slot_t *private_key,
4884                                                    const uint8_t *peer_key,
4885                                                    size_t peer_key_length,
4886                                                    uint8_t *shared_secret,
4887                                                    size_t shared_secret_size,
4888                                                    size_t *shared_secret_length)
4889 {
4890     mbedtls_ecp_keypair *ecp = NULL;
4891     psa_status_t status;
4892 
4893     switch (alg) {
4894 #if defined(MBEDTLS_PSA_BUILTIN_ALG_ECDH)
4895         case PSA_ALG_ECDH:
4896             if (!PSA_KEY_TYPE_IS_ECC_KEY_PAIR(private_key->attr.type)) {
4897                 return PSA_ERROR_INVALID_ARGUMENT;
4898             }
4899             status = mbedtls_psa_ecp_load_representation(
4900                 private_key->attr.type,
4901                 private_key->attr.bits,
4902                 private_key->key.data,
4903                 private_key->key.bytes,
4904                 &ecp);
4905             if (status != PSA_SUCCESS) {
4906                 return status;
4907             }
4908             status = psa_key_agreement_ecdh(peer_key, peer_key_length,
4909                                             ecp,
4910                                             shared_secret, shared_secret_size,
4911                                             shared_secret_length);
4912             mbedtls_ecp_keypair_free(ecp);
4913             mbedtls_free(ecp);
4914             return status;
4915 #endif /* MBEDTLS_PSA_BUILTIN_ALG_ECDH */
4916         default:
4917             (void) ecp;
4918             (void) status;
4919             (void) private_key;
4920             (void) peer_key;
4921             (void) peer_key_length;
4922             (void) shared_secret;
4923             (void) shared_secret_size;
4924             (void) shared_secret_length;
4925             return PSA_ERROR_NOT_SUPPORTED;
4926     }
4927 }
4928 
4929 /* Note that if this function fails, you must call psa_key_derivation_abort()
4930  * to potentially free embedded data structures and wipe confidential data.
4931  */
psa_key_agreement_internal(psa_key_derivation_operation_t * operation,psa_key_derivation_step_t step,psa_key_slot_t * private_key,const uint8_t * peer_key,size_t peer_key_length)4932 static psa_status_t psa_key_agreement_internal(psa_key_derivation_operation_t *operation,
4933                                                psa_key_derivation_step_t step,
4934                                                psa_key_slot_t *private_key,
4935                                                const uint8_t *peer_key,
4936                                                size_t peer_key_length)
4937 {
4938     psa_status_t status;
4939     uint8_t shared_secret[PSA_KEY_AGREEMENT_MAX_SHARED_SECRET_SIZE];
4940     size_t shared_secret_length = 0;
4941     psa_algorithm_t ka_alg = PSA_ALG_KEY_AGREEMENT_GET_BASE(operation->alg);
4942 
4943     /* Step 1: run the secret agreement algorithm to generate the shared
4944      * secret. */
4945     status = psa_key_agreement_raw_internal(ka_alg,
4946                                             private_key,
4947                                             peer_key, peer_key_length,
4948                                             shared_secret,
4949                                             sizeof(shared_secret),
4950                                             &shared_secret_length);
4951     if (status != PSA_SUCCESS) {
4952         goto exit;
4953     }
4954 
4955     /* Step 2: set up the key derivation to generate key material from
4956      * the shared secret. A shared secret is permitted wherever a key
4957      * of type DERIVE is permitted. */
4958     status = psa_key_derivation_input_internal(operation, step,
4959                                                PSA_KEY_TYPE_DERIVE,
4960                                                shared_secret,
4961                                                shared_secret_length);
4962 exit:
4963     mbedtls_platform_zeroize(shared_secret, shared_secret_length);
4964     return status;
4965 }
4966 
psa_key_derivation_key_agreement(psa_key_derivation_operation_t * operation,psa_key_derivation_step_t step,mbedtls_svc_key_id_t private_key,const uint8_t * peer_key,size_t peer_key_length)4967 psa_status_t psa_key_derivation_key_agreement(psa_key_derivation_operation_t *operation,
4968                                               psa_key_derivation_step_t step,
4969                                               mbedtls_svc_key_id_t private_key,
4970                                               const uint8_t *peer_key,
4971                                               size_t peer_key_length)
4972 {
4973     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
4974     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
4975     psa_key_slot_t *slot;
4976 
4977     if (!PSA_ALG_IS_KEY_AGREEMENT(operation->alg)) {
4978         return PSA_ERROR_INVALID_ARGUMENT;
4979     }
4980     status = psa_get_and_lock_transparent_key_slot_with_policy(
4981         private_key, &slot, PSA_KEY_USAGE_DERIVE, operation->alg);
4982     if (status != PSA_SUCCESS) {
4983         return status;
4984     }
4985     status = psa_key_agreement_internal(operation, step,
4986                                         slot,
4987                                         peer_key, peer_key_length);
4988     if (status != PSA_SUCCESS) {
4989         psa_key_derivation_abort(operation);
4990     } else {
4991         /* If a private key has been added as SECRET, we allow the derived
4992          * key material to be used as a key in PSA Crypto. */
4993         if (step == PSA_KEY_DERIVATION_INPUT_SECRET) {
4994             operation->can_output_key = 1;
4995         }
4996     }
4997 
4998     unlock_status = psa_unlock_key_slot(slot);
4999 
5000     return (status == PSA_SUCCESS) ? unlock_status : status;
5001 }
5002 
psa_raw_key_agreement(psa_algorithm_t alg,mbedtls_svc_key_id_t private_key,const uint8_t * peer_key,size_t peer_key_length,uint8_t * output,size_t output_size,size_t * output_length)5003 psa_status_t psa_raw_key_agreement(psa_algorithm_t alg,
5004                                    mbedtls_svc_key_id_t private_key,
5005                                    const uint8_t *peer_key,
5006                                    size_t peer_key_length,
5007                                    uint8_t *output,
5008                                    size_t output_size,
5009                                    size_t *output_length)
5010 {
5011     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
5012     psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
5013     psa_key_slot_t *slot = NULL;
5014     size_t expected_length;
5015 
5016     if (!PSA_ALG_IS_KEY_AGREEMENT(alg)) {
5017         status = PSA_ERROR_INVALID_ARGUMENT;
5018         goto exit;
5019     }
5020     status = psa_get_and_lock_transparent_key_slot_with_policy(
5021         private_key, &slot, PSA_KEY_USAGE_DERIVE, alg);
5022     if (status != PSA_SUCCESS) {
5023         goto exit;
5024     }
5025 
5026     /* PSA_RAW_KEY_AGREEMENT_OUTPUT_SIZE() is in general an upper bound
5027      * for the output size. The PSA specification only guarantees that this
5028      * function works if output_size >= PSA_RAW_KEY_AGREEMENT_OUTPUT_SIZE(...),
5029      * but it might be nice to allow smaller buffers if the output fits.
5030      * At the time of writing this comment, with only ECDH implemented,
5031      * PSA_RAW_KEY_AGREEMENT_OUTPUT_SIZE() is exact so the point is moot.
5032      * If FFDH is implemented, PSA_RAW_KEY_AGREEMENT_OUTPUT_SIZE() can easily
5033      * be exact for it as well. */
5034     expected_length =
5035         PSA_RAW_KEY_AGREEMENT_OUTPUT_SIZE(slot->attr.type, slot->attr.bits);
5036     if (output_size < expected_length) {
5037         status = PSA_ERROR_BUFFER_TOO_SMALL;
5038         goto exit;
5039     }
5040 
5041     status = psa_key_agreement_raw_internal(alg, slot,
5042                                             peer_key, peer_key_length,
5043                                             output, output_size,
5044                                             output_length);
5045 
5046 exit:
5047     if (status != PSA_SUCCESS) {
5048         /* If an error happens and is not handled properly, the output
5049          * may be used as a key to protect sensitive data. Arrange for such
5050          * a key to be random, which is likely to result in decryption or
5051          * verification errors. This is better than filling the buffer with
5052          * some constant data such as zeros, which would result in the data
5053          * being protected with a reproducible, easily knowable key.
5054          */
5055         psa_generate_random(output, output_size);
5056         *output_length = output_size;
5057     }
5058 
5059     unlock_status = psa_unlock_key_slot(slot);
5060 
5061     return (status == PSA_SUCCESS) ? unlock_status : status;
5062 }
5063 
5064 
5065 
5066 /****************************************************************/
5067 /* Random generation */
5068 /****************************************************************/
5069 
5070 #if defined(MBEDTLS_PSA_INJECT_ENTROPY)
5071 #include "mbedtls/entropy_poll.h"
5072 #endif
5073 
5074 /** Initialize the PSA random generator.
5075  */
mbedtls_psa_random_init(mbedtls_psa_random_context_t * rng)5076 static void mbedtls_psa_random_init(mbedtls_psa_random_context_t *rng)
5077 {
5078 #if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
5079     memset(rng, 0, sizeof(*rng));
5080 #else /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
5081 
5082     /* Set default configuration if
5083      * mbedtls_psa_crypto_configure_entropy_sources() hasn't been called. */
5084     if (rng->entropy_init == NULL) {
5085         rng->entropy_init = mbedtls_entropy_init;
5086     }
5087     if (rng->entropy_free == NULL) {
5088         rng->entropy_free = mbedtls_entropy_free;
5089     }
5090 
5091     rng->entropy_init(&rng->entropy);
5092 #if defined(MBEDTLS_PSA_INJECT_ENTROPY) && \
5093     defined(MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES)
5094     /* The PSA entropy injection feature depends on using NV seed as an entropy
5095      * source. Add NV seed as an entropy source for PSA entropy injection. */
5096     mbedtls_entropy_add_source(&rng->entropy,
5097                                mbedtls_nv_seed_poll, NULL,
5098                                MBEDTLS_ENTROPY_BLOCK_SIZE,
5099                                MBEDTLS_ENTROPY_SOURCE_STRONG);
5100 #endif
5101 
5102     mbedtls_psa_drbg_init(MBEDTLS_PSA_RANDOM_STATE);
5103 #endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
5104 }
5105 
5106 /** Deinitialize the PSA random generator.
5107  */
mbedtls_psa_random_free(mbedtls_psa_random_context_t * rng)5108 static void mbedtls_psa_random_free(mbedtls_psa_random_context_t *rng)
5109 {
5110 #if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
5111     memset(rng, 0, sizeof(*rng));
5112 #else /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
5113     mbedtls_psa_drbg_free(MBEDTLS_PSA_RANDOM_STATE);
5114     rng->entropy_free(&rng->entropy);
5115 #endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
5116 }
5117 
5118 /** Seed the PSA random generator.
5119  */
mbedtls_psa_random_seed(mbedtls_psa_random_context_t * rng)5120 static psa_status_t mbedtls_psa_random_seed(mbedtls_psa_random_context_t *rng)
5121 {
5122 #if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
5123     /* Do nothing: the external RNG seeds itself. */
5124     (void) rng;
5125     return PSA_SUCCESS;
5126 #else /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
5127     const unsigned char drbg_seed[] = "PSA";
5128     int ret = mbedtls_psa_drbg_seed(&rng->entropy,
5129                                     drbg_seed, sizeof(drbg_seed) - 1);
5130     return mbedtls_to_psa_error(ret);
5131 #endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
5132 }
5133 
psa_generate_random(uint8_t * output,size_t output_size)5134 psa_status_t psa_generate_random(uint8_t *output,
5135                                  size_t output_size)
5136 {
5137     GUARD_MODULE_INITIALIZED;
5138 
5139 #if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
5140 
5141     size_t output_length = 0;
5142     psa_status_t status = mbedtls_psa_external_get_random(&global_data.rng,
5143                                                           output, output_size,
5144                                                           &output_length);
5145     if (status != PSA_SUCCESS) {
5146         return status;
5147     }
5148     /* Breaking up a request into smaller chunks is currently not supported
5149      * for the external RNG interface. */
5150     if (output_length != output_size) {
5151         return PSA_ERROR_INSUFFICIENT_ENTROPY;
5152     }
5153     return PSA_SUCCESS;
5154 
5155 #else /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
5156 
5157     while (output_size > 0) {
5158         size_t request_size =
5159             (output_size > MBEDTLS_PSA_RANDOM_MAX_REQUEST ?
5160              MBEDTLS_PSA_RANDOM_MAX_REQUEST :
5161              output_size);
5162         int ret = mbedtls_psa_get_random(MBEDTLS_PSA_RANDOM_STATE,
5163                                          output, request_size);
5164         if (ret != 0) {
5165             return mbedtls_to_psa_error(ret);
5166         }
5167         output_size -= request_size;
5168         output += request_size;
5169     }
5170     return PSA_SUCCESS;
5171 #endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
5172 }
5173 
5174 /* Wrapper function allowing the classic API to use the PSA RNG.
5175  *
5176  * `mbedtls_psa_get_random(MBEDTLS_PSA_RANDOM_STATE, ...)` calls
5177  * `psa_generate_random(...)`. The state parameter is ignored since the
5178  * PSA API doesn't support passing an explicit state.
5179  *
5180  * In the non-external case, psa_generate_random() calls an
5181  * `mbedtls_xxx_drbg_random` function which has exactly the same signature
5182  * and semantics as mbedtls_psa_get_random(). As an optimization,
5183  * instead of doing this back-and-forth between the PSA API and the
5184  * classic API, psa_crypto_random_impl.h defines `mbedtls_psa_get_random`
5185  * as a constant function pointer to `mbedtls_xxx_drbg_random`.
5186  */
5187 #if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
mbedtls_psa_get_random(void * p_rng,unsigned char * output,size_t output_size)5188 int mbedtls_psa_get_random(void *p_rng,
5189                            unsigned char *output,
5190                            size_t output_size)
5191 {
5192     /* This function takes a pointer to the RNG state because that's what
5193      * classic mbedtls functions using an RNG expect. The PSA RNG manages
5194      * its own state internally and doesn't let the caller access that state.
5195      * So we just ignore the state parameter, and in practice we'll pass
5196      * NULL. */
5197     (void) p_rng;
5198     psa_status_t status = psa_generate_random(output, output_size);
5199     if (status == PSA_SUCCESS) {
5200         return 0;
5201     } else {
5202         return MBEDTLS_ERR_ENTROPY_SOURCE_FAILED;
5203     }
5204 }
5205 #endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
5206 
5207 #if defined(MBEDTLS_PSA_INJECT_ENTROPY)
mbedtls_psa_inject_entropy(const uint8_t * seed,size_t seed_size)5208 psa_status_t mbedtls_psa_inject_entropy(const uint8_t *seed,
5209                                         size_t seed_size)
5210 {
5211     if (global_data.initialized) {
5212         return PSA_ERROR_NOT_PERMITTED;
5213     }
5214 
5215     if (((seed_size < MBEDTLS_ENTROPY_MIN_PLATFORM) ||
5216          (seed_size < MBEDTLS_ENTROPY_BLOCK_SIZE)) ||
5217         (seed_size > MBEDTLS_ENTROPY_MAX_SEED_SIZE)) {
5218         return PSA_ERROR_INVALID_ARGUMENT;
5219     }
5220 
5221     return mbedtls_psa_storage_inject_entropy(seed, seed_size);
5222 }
5223 #endif /* MBEDTLS_PSA_INJECT_ENTROPY */
5224 
5225 /** Validate the key type and size for key generation
5226  *
5227  * \param  type  The key type
5228  * \param  bits  The number of bits of the key
5229  *
5230  * \retval #PSA_SUCCESS
5231  *         The key type and size are valid.
5232  * \retval #PSA_ERROR_INVALID_ARGUMENT
5233  *         The size in bits of the key is not valid.
5234  * \retval #PSA_ERROR_NOT_SUPPORTED
5235  *         The type and/or the size in bits of the key or the combination of
5236  *         the two is not supported.
5237  */
psa_validate_key_type_and_size_for_key_generation(psa_key_type_t type,size_t bits)5238 static psa_status_t psa_validate_key_type_and_size_for_key_generation(
5239     psa_key_type_t type, size_t bits)
5240 {
5241     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
5242 
5243     if (key_type_is_raw_bytes(type)) {
5244         status = validate_unstructured_key_bit_size(type, bits);
5245         if (status != PSA_SUCCESS) {
5246             return status;
5247         }
5248     } else
5249 #if defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR)
5250     if (PSA_KEY_TYPE_IS_RSA(type) && PSA_KEY_TYPE_IS_KEY_PAIR(type)) {
5251         if (bits > PSA_VENDOR_RSA_MAX_KEY_BITS) {
5252             return PSA_ERROR_NOT_SUPPORTED;
5253         }
5254 
5255         /* Accept only byte-aligned keys, for the same reasons as
5256          * in psa_import_rsa_key(). */
5257         if (bits % 8 != 0) {
5258             return PSA_ERROR_NOT_SUPPORTED;
5259         }
5260     } else
5261 #endif /* defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR) */
5262 
5263 #if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR)
5264     if (PSA_KEY_TYPE_IS_ECC(type) && PSA_KEY_TYPE_IS_KEY_PAIR(type)) {
5265         /* To avoid empty block, return successfully here. */
5266         return PSA_SUCCESS;
5267     } else
5268 #endif /* defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR) */
5269     {
5270         return PSA_ERROR_NOT_SUPPORTED;
5271     }
5272 
5273     return PSA_SUCCESS;
5274 }
5275 
psa_generate_key_internal(const psa_key_attributes_t * attributes,uint8_t * key_buffer,size_t key_buffer_size,size_t * key_buffer_length)5276 psa_status_t psa_generate_key_internal(
5277     const psa_key_attributes_t *attributes,
5278     uint8_t *key_buffer, size_t key_buffer_size, size_t *key_buffer_length)
5279 {
5280     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
5281     psa_key_type_t type = attributes->core.type;
5282 
5283     if ((attributes->domain_parameters == NULL) &&
5284         (attributes->domain_parameters_size != 0)) {
5285         return PSA_ERROR_INVALID_ARGUMENT;
5286     }
5287 
5288     if (key_type_is_raw_bytes(type)) {
5289         status = psa_generate_random(key_buffer, key_buffer_size);
5290         if (status != PSA_SUCCESS) {
5291             return status;
5292         }
5293 
5294 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES)
5295         if (type == PSA_KEY_TYPE_DES) {
5296             psa_des_set_key_parity(key_buffer, key_buffer_size);
5297         }
5298 #endif /* MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES */
5299     } else
5300 
5301 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) && \
5302     defined(MBEDTLS_GENPRIME)
5303     if (type == PSA_KEY_TYPE_RSA_KEY_PAIR) {
5304         return mbedtls_psa_rsa_generate_key(attributes,
5305                                             key_buffer,
5306                                             key_buffer_size,
5307                                             key_buffer_length);
5308     } else
5309 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR)
5310         * defined(MBEDTLS_GENPRIME) */
5311 
5312 #if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR)
5313     if (PSA_KEY_TYPE_IS_ECC(type) && PSA_KEY_TYPE_IS_KEY_PAIR(type)) {
5314         return mbedtls_psa_ecp_generate_key(attributes,
5315                                             key_buffer,
5316                                             key_buffer_size,
5317                                             key_buffer_length);
5318     } else
5319 #endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) */
5320     {
5321         (void) key_buffer_length;
5322         return PSA_ERROR_NOT_SUPPORTED;
5323     }
5324 
5325     return PSA_SUCCESS;
5326 }
5327 
psa_generate_key(const psa_key_attributes_t * attributes,mbedtls_svc_key_id_t * key)5328 psa_status_t psa_generate_key(const psa_key_attributes_t *attributes,
5329                               mbedtls_svc_key_id_t *key)
5330 {
5331     psa_status_t status;
5332     psa_key_slot_t *slot = NULL;
5333     psa_se_drv_table_entry_t *driver = NULL;
5334     size_t key_buffer_size;
5335 
5336     *key = MBEDTLS_SVC_KEY_ID_INIT;
5337 
5338     /* Reject any attempt to create a zero-length key so that we don't
5339      * risk tripping up later, e.g. on a malloc(0) that returns NULL. */
5340     if (psa_get_key_bits(attributes) == 0) {
5341         return PSA_ERROR_INVALID_ARGUMENT;
5342     }
5343 
5344     /* Reject any attempt to create a public key. */
5345     if (PSA_KEY_TYPE_IS_PUBLIC_KEY(attributes->core.type)) {
5346         return PSA_ERROR_INVALID_ARGUMENT;
5347     }
5348 
5349     status = psa_start_key_creation(PSA_KEY_CREATION_GENERATE, attributes,
5350                                     &slot, &driver);
5351     if (status != PSA_SUCCESS) {
5352         goto exit;
5353     }
5354 
5355     /* In the case of a transparent key or an opaque key stored in local
5356      * storage (thus not in the case of generating a key in a secure element
5357      * or cryptoprocessor with storage), we have to allocate a buffer to
5358      * hold the generated key material. */
5359     if (slot->key.data == NULL) {
5360         if (PSA_KEY_LIFETIME_GET_LOCATION(attributes->core.lifetime) ==
5361             PSA_KEY_LOCATION_LOCAL_STORAGE) {
5362             status = psa_validate_key_type_and_size_for_key_generation(
5363                 attributes->core.type, attributes->core.bits);
5364             if (status != PSA_SUCCESS) {
5365                 goto exit;
5366             }
5367 
5368             key_buffer_size = PSA_EXPORT_KEY_OUTPUT_SIZE(
5369                 attributes->core.type,
5370                 attributes->core.bits);
5371         } else {
5372             status = psa_driver_wrapper_get_key_buffer_size(
5373                 attributes, &key_buffer_size);
5374             if (status != PSA_SUCCESS) {
5375                 goto exit;
5376             }
5377         }
5378 
5379         status = psa_allocate_buffer_to_slot(slot, key_buffer_size);
5380         if (status != PSA_SUCCESS) {
5381             goto exit;
5382         }
5383     }
5384 
5385     status = psa_driver_wrapper_generate_key(attributes,
5386                                              slot->key.data, slot->key.bytes, &slot->key.bytes);
5387 
5388     if (status != PSA_SUCCESS) {
5389         psa_remove_key_data_from_memory(slot);
5390     }
5391 
5392 exit:
5393     if (status == PSA_SUCCESS) {
5394         status = psa_finish_key_creation(slot, driver, key);
5395     }
5396     if (status != PSA_SUCCESS) {
5397         psa_fail_key_creation(slot, driver);
5398     }
5399 
5400     return status;
5401 }
5402 
5403 /****************************************************************/
5404 /* Module setup */
5405 /****************************************************************/
5406 
5407 #if !defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
mbedtls_psa_crypto_configure_entropy_sources(void (* entropy_init)(mbedtls_entropy_context * ctx),void (* entropy_free)(mbedtls_entropy_context * ctx))5408 psa_status_t mbedtls_psa_crypto_configure_entropy_sources(
5409     void (* entropy_init)(mbedtls_entropy_context *ctx),
5410     void (* entropy_free)(mbedtls_entropy_context *ctx))
5411 {
5412     if (global_data.rng_state != RNG_NOT_INITIALIZED) {
5413         return PSA_ERROR_BAD_STATE;
5414     }
5415     global_data.rng.entropy_init = entropy_init;
5416     global_data.rng.entropy_free = entropy_free;
5417     return PSA_SUCCESS;
5418 }
5419 #endif /* !defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG) */
5420 
mbedtls_psa_crypto_free(void)5421 void mbedtls_psa_crypto_free(void)
5422 {
5423     psa_wipe_all_key_slots();
5424     if (global_data.rng_state != RNG_NOT_INITIALIZED) {
5425         mbedtls_psa_random_free(&global_data.rng);
5426     }
5427     /* Wipe all remaining data, including configuration.
5428      * In particular, this sets all state indicator to the value
5429      * indicating "uninitialized". */
5430     mbedtls_platform_zeroize(&global_data, sizeof(global_data));
5431 
5432     /* Terminate drivers */
5433     psa_driver_wrapper_free();
5434 }
5435 
5436 #if defined(PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS)
5437 /** Recover a transaction that was interrupted by a power failure.
5438  *
5439  * This function is called during initialization, before psa_crypto_init()
5440  * returns. If this function returns a failure status, the initialization
5441  * fails.
5442  */
psa_crypto_recover_transaction(const psa_crypto_transaction_t * transaction)5443 static psa_status_t psa_crypto_recover_transaction(
5444     const psa_crypto_transaction_t *transaction)
5445 {
5446     switch (transaction->unknown.type) {
5447         case PSA_CRYPTO_TRANSACTION_CREATE_KEY:
5448         case PSA_CRYPTO_TRANSACTION_DESTROY_KEY:
5449         /* TODO - fall through to the failure case until this
5450          * is implemented.
5451          * https://github.com/ARMmbed/mbed-crypto/issues/218
5452          */
5453         default:
5454             /* We found an unsupported transaction in the storage.
5455              * We don't know what state the storage is in. Give up. */
5456             return PSA_ERROR_DATA_INVALID;
5457     }
5458 }
5459 #endif /* PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS */
5460 
psa_crypto_init(void)5461 psa_status_t psa_crypto_init(void)
5462 {
5463     psa_status_t status;
5464 
5465     /* Double initialization is explicitly allowed. */
5466     if (global_data.initialized != 0) {
5467         return PSA_SUCCESS;
5468     }
5469 
5470     /* Initialize and seed the random generator. */
5471     mbedtls_psa_random_init(&global_data.rng);
5472     global_data.rng_state = RNG_INITIALIZED;
5473     status = mbedtls_psa_random_seed(&global_data.rng);
5474     if (status != PSA_SUCCESS) {
5475         goto exit;
5476     }
5477     global_data.rng_state = RNG_SEEDED;
5478 
5479     status = psa_initialize_key_slots();
5480     if (status != PSA_SUCCESS) {
5481         goto exit;
5482     }
5483 
5484     /* Init drivers */
5485     status = psa_driver_wrapper_init();
5486     if (status != PSA_SUCCESS) {
5487         goto exit;
5488     }
5489 
5490 #if defined(PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS)
5491     status = psa_crypto_load_transaction();
5492     if (status == PSA_SUCCESS) {
5493         status = psa_crypto_recover_transaction(&psa_crypto_transaction);
5494         if (status != PSA_SUCCESS) {
5495             goto exit;
5496         }
5497         status = psa_crypto_stop_transaction();
5498     } else if (status == PSA_ERROR_DOES_NOT_EXIST) {
5499         /* There's no transaction to complete. It's all good. */
5500         status = PSA_SUCCESS;
5501     }
5502 #endif /* PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS */
5503 
5504     /* All done. */
5505     global_data.initialized = 1;
5506 
5507 exit:
5508     if (status != PSA_SUCCESS) {
5509         mbedtls_psa_crypto_free();
5510     }
5511     return status;
5512 }
5513 
5514 #endif /* MBEDTLS_PSA_CRYPTO_C */
5515