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