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