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