Kenji Arai / mbed-os_TYBLE16

Dependents:   TYBLE16_simple_data_logger TYBLE16_MP3_Air

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers psa_crypto.c Source File

psa_crypto.c

00001 /*
00002  *  PSA crypto layer on top of Mbed TLS crypto
00003  */
00004 /*  Copyright (C) 2018, ARM Limited, All Rights Reserved
00005  *  SPDX-License-Identifier: Apache-2.0
00006  *
00007  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
00008  *  not use this file except in compliance with the License.
00009  *  You may obtain a copy of the License at
00010  *
00011  *  http://www.apache.org/licenses/LICENSE-2.0
00012  *
00013  *  Unless required by applicable law or agreed to in writing, software
00014  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
00015  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00016  *  See the License for the specific language governing permissions and
00017  *  limitations under the License.
00018  *
00019  *  This file is part of mbed TLS (https://tls.mbed.org)
00020  */
00021 
00022 #if !defined(MBEDTLS_CONFIG_FILE)
00023 #include "mbedtls/config.h"
00024 #else
00025 #include MBEDTLS_CONFIG_FILE
00026 #endif
00027 
00028 #if defined(MBEDTLS_PSA_CRYPTO_C)
00029 
00030 #include "psa_crypto_service_integration.h"
00031 #include "psa/crypto.h"
00032 
00033 #include "psa_crypto_core.h"
00034 #include "psa_crypto_invasive.h"
00035 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
00036 #include "psa_crypto_se.h"
00037 #endif
00038 #include "psa_crypto_slot_management.h"
00039 /* Include internal declarations that are useful for implementing persistently
00040  * stored keys. */
00041 #include "psa_crypto_storage.h"
00042 
00043 #include <assert.h>
00044 #include <stdlib.h>
00045 #include <string.h>
00046 #include "mbedtls/platform.h"
00047 #if !defined(MBEDTLS_PLATFORM_C)
00048 #define mbedtls_calloc calloc
00049 #define mbedtls_free   free
00050 #endif
00051 
00052 #include "mbedtls/arc4.h"
00053 #include "mbedtls/asn1.h"
00054 #include "mbedtls/asn1write.h"
00055 #include "mbedtls/bignum.h"
00056 #include "mbedtls/blowfish.h"
00057 #include "mbedtls/camellia.h"
00058 #include "mbedtls/chacha20.h"
00059 #include "mbedtls/chachapoly.h"
00060 #include "mbedtls/cipher.h"
00061 #include "mbedtls/ccm.h"
00062 #include "mbedtls/cmac.h"
00063 #include "mbedtls/ctr_drbg.h"
00064 #include "mbedtls/des.h"
00065 #include "mbedtls/ecdh.h"
00066 #include "mbedtls/ecp.h"
00067 #include "mbedtls/entropy.h"
00068 #include "mbedtls/error.h"
00069 #include "mbedtls/gcm.h"
00070 #include "mbedtls/md2.h"
00071 #include "mbedtls/md4.h"
00072 #include "mbedtls/md5.h"
00073 #include "mbedtls/md.h"
00074 #include "mbedtls/md_internal.h"
00075 #include "mbedtls/pk.h"
00076 #include "mbedtls/pk_internal.h"
00077 #include "mbedtls/platform_util.h"
00078 #include "mbedtls/ripemd160.h"
00079 #include "mbedtls/rsa.h"
00080 #include "mbedtls/sha1.h"
00081 #include "mbedtls/sha256.h"
00082 #include "mbedtls/sha512.h"
00083 #include "mbedtls/xtea.h"
00084 
00085 #define ARRAY_LENGTH( array ) ( sizeof( array ) / sizeof( *( array ) ) )
00086 
00087 /* constant-time buffer comparison */
00088 static inline int safer_memcmp( const uint8_t *a, const uint8_t *b, size_t n )
00089 {
00090     size_t i;
00091     unsigned char diff = 0;
00092 
00093     for( i = 0; i < n; i++ )
00094         diff |= a[i] ^ b[i];
00095 
00096     return( diff );
00097 }
00098 
00099 
00100 
00101 /****************************************************************/
00102 /* Global data, support functions and library management */
00103 /****************************************************************/
00104 
00105 static int key_type_is_raw_bytes( psa_key_type_t type )
00106 {
00107     return( PSA_KEY_TYPE_IS_UNSTRUCTURED( type ) );
00108 }
00109 
00110 /* Values for psa_global_data_t::rng_state */
00111 #define RNG_NOT_INITIALIZED 0
00112 #define RNG_INITIALIZED 1
00113 #define RNG_SEEDED 2
00114 
00115 typedef struct
00116 {
00117     void (* entropy_init )( mbedtls_entropy_context *ctx );
00118     void (* entropy_free )( mbedtls_entropy_context *ctx );
00119     mbedtls_entropy_context entropy;
00120     mbedtls_ctr_drbg_context ctr_drbg;
00121     unsigned initialized : 1;
00122     unsigned rng_state : 2;
00123 } psa_global_data_t;
00124 
00125 static psa_global_data_t global_data;
00126 
00127 #define GUARD_MODULE_INITIALIZED        \
00128     if( global_data.initialized == 0 )  \
00129         return( PSA_ERROR_BAD_STATE );
00130 
00131 static psa_status_t mbedtls_to_psa_error( int ret )
00132 {
00133     /* If there's both a high-level code and low-level code, dispatch on
00134      * the high-level code. */
00135     switch( ret < -0x7f ? - ( -ret & 0x7f80 ) : ret )
00136     {
00137         case 0:
00138             return( PSA_SUCCESS );
00139 
00140         case MBEDTLS_ERR_AES_INVALID_KEY_LENGTH:
00141         case MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH:
00142         case MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE:
00143             return( PSA_ERROR_NOT_SUPPORTED );
00144         case MBEDTLS_ERR_AES_HW_ACCEL_FAILED:
00145             return( PSA_ERROR_HARDWARE_FAILURE );
00146 
00147         case MBEDTLS_ERR_ARC4_HW_ACCEL_FAILED:
00148             return( PSA_ERROR_HARDWARE_FAILURE );
00149 
00150         case MBEDTLS_ERR_ASN1_OUT_OF_DATA:
00151         case MBEDTLS_ERR_ASN1_UNEXPECTED_TAG:
00152         case MBEDTLS_ERR_ASN1_INVALID_LENGTH:
00153         case MBEDTLS_ERR_ASN1_LENGTH_MISMATCH:
00154         case MBEDTLS_ERR_ASN1_INVALID_DATA:
00155             return( PSA_ERROR_INVALID_ARGUMENT );
00156         case MBEDTLS_ERR_ASN1_ALLOC_FAILED:
00157             return( PSA_ERROR_INSUFFICIENT_MEMORY );
00158         case MBEDTLS_ERR_ASN1_BUF_TOO_SMALL:
00159             return( PSA_ERROR_BUFFER_TOO_SMALL );
00160 
00161 #if defined(MBEDTLS_ERR_BLOWFISH_BAD_INPUT_DATA)
00162         case MBEDTLS_ERR_BLOWFISH_BAD_INPUT_DATA:
00163 #elif defined(MBEDTLS_ERR_BLOWFISH_INVALID_KEY_LENGTH)
00164         case MBEDTLS_ERR_BLOWFISH_INVALID_KEY_LENGTH:
00165 #endif
00166         case MBEDTLS_ERR_BLOWFISH_INVALID_INPUT_LENGTH:
00167             return( PSA_ERROR_NOT_SUPPORTED );
00168         case MBEDTLS_ERR_BLOWFISH_HW_ACCEL_FAILED:
00169             return( PSA_ERROR_HARDWARE_FAILURE );
00170 
00171 #if defined(MBEDTLS_ERR_CAMELLIA_BAD_INPUT_DATA)
00172         case MBEDTLS_ERR_CAMELLIA_BAD_INPUT_DATA:
00173 #elif defined(MBEDTLS_ERR_CAMELLIA_INVALID_KEY_LENGTH)
00174         case MBEDTLS_ERR_CAMELLIA_INVALID_KEY_LENGTH:
00175 #endif
00176         case MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH:
00177             return( PSA_ERROR_NOT_SUPPORTED );
00178         case MBEDTLS_ERR_CAMELLIA_HW_ACCEL_FAILED:
00179             return( PSA_ERROR_HARDWARE_FAILURE );
00180 
00181         case MBEDTLS_ERR_CCM_BAD_INPUT:
00182             return( PSA_ERROR_INVALID_ARGUMENT );
00183         case MBEDTLS_ERR_CCM_AUTH_FAILED:
00184             return( PSA_ERROR_INVALID_SIGNATURE );
00185         case MBEDTLS_ERR_CCM_HW_ACCEL_FAILED:
00186             return( PSA_ERROR_HARDWARE_FAILURE );
00187 
00188         case MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA:
00189             return( PSA_ERROR_INVALID_ARGUMENT );
00190 
00191         case MBEDTLS_ERR_CHACHAPOLY_BAD_STATE:
00192             return( PSA_ERROR_BAD_STATE );
00193         case MBEDTLS_ERR_CHACHAPOLY_AUTH_FAILED:
00194             return( PSA_ERROR_INVALID_SIGNATURE );
00195 
00196         case MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE:
00197             return( PSA_ERROR_NOT_SUPPORTED );
00198         case MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA:
00199             return( PSA_ERROR_INVALID_ARGUMENT );
00200         case MBEDTLS_ERR_CIPHER_ALLOC_FAILED:
00201             return( PSA_ERROR_INSUFFICIENT_MEMORY );
00202         case MBEDTLS_ERR_CIPHER_INVALID_PADDING:
00203             return( PSA_ERROR_INVALID_PADDING );
00204         case MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED:
00205             return( PSA_ERROR_BAD_STATE );
00206         case MBEDTLS_ERR_CIPHER_AUTH_FAILED:
00207             return( PSA_ERROR_INVALID_SIGNATURE );
00208         case MBEDTLS_ERR_CIPHER_INVALID_CONTEXT:
00209             return( PSA_ERROR_CORRUPTION_DETECTED );
00210         case MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED:
00211             return( PSA_ERROR_HARDWARE_FAILURE );
00212 
00213         case MBEDTLS_ERR_CMAC_HW_ACCEL_FAILED:
00214             return( PSA_ERROR_HARDWARE_FAILURE );
00215 
00216         case MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED:
00217             return( PSA_ERROR_INSUFFICIENT_ENTROPY );
00218         case MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG:
00219         case MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG:
00220             return( PSA_ERROR_NOT_SUPPORTED );
00221         case MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR:
00222             return( PSA_ERROR_INSUFFICIENT_ENTROPY );
00223 
00224         case MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH:
00225             return( PSA_ERROR_NOT_SUPPORTED );
00226         case MBEDTLS_ERR_DES_HW_ACCEL_FAILED:
00227             return( PSA_ERROR_HARDWARE_FAILURE );
00228 
00229         case MBEDTLS_ERR_ENTROPY_NO_SOURCES_DEFINED:
00230         case MBEDTLS_ERR_ENTROPY_NO_STRONG_SOURCE:
00231         case MBEDTLS_ERR_ENTROPY_SOURCE_FAILED:
00232             return( PSA_ERROR_INSUFFICIENT_ENTROPY );
00233 
00234         case MBEDTLS_ERR_GCM_AUTH_FAILED:
00235             return( PSA_ERROR_INVALID_SIGNATURE );
00236         case MBEDTLS_ERR_GCM_BAD_INPUT:
00237             return( PSA_ERROR_INVALID_ARGUMENT );
00238         case MBEDTLS_ERR_GCM_HW_ACCEL_FAILED:
00239             return( PSA_ERROR_HARDWARE_FAILURE );
00240 
00241         case MBEDTLS_ERR_MD2_HW_ACCEL_FAILED:
00242         case MBEDTLS_ERR_MD4_HW_ACCEL_FAILED:
00243         case MBEDTLS_ERR_MD5_HW_ACCEL_FAILED:
00244             return( PSA_ERROR_HARDWARE_FAILURE );
00245 
00246         case MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE:
00247             return( PSA_ERROR_NOT_SUPPORTED );
00248         case MBEDTLS_ERR_MD_BAD_INPUT_DATA:
00249             return( PSA_ERROR_INVALID_ARGUMENT );
00250         case MBEDTLS_ERR_MD_ALLOC_FAILED:
00251             return( PSA_ERROR_INSUFFICIENT_MEMORY );
00252         case MBEDTLS_ERR_MD_FILE_IO_ERROR:
00253             return( PSA_ERROR_STORAGE_FAILURE );
00254         case MBEDTLS_ERR_MD_HW_ACCEL_FAILED:
00255             return( PSA_ERROR_HARDWARE_FAILURE );
00256 
00257         case MBEDTLS_ERR_MPI_FILE_IO_ERROR:
00258             return( PSA_ERROR_STORAGE_FAILURE );
00259         case MBEDTLS_ERR_MPI_BAD_INPUT_DATA:
00260             return( PSA_ERROR_INVALID_ARGUMENT );
00261         case MBEDTLS_ERR_MPI_INVALID_CHARACTER:
00262             return( PSA_ERROR_INVALID_ARGUMENT );
00263         case MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL:
00264             return( PSA_ERROR_BUFFER_TOO_SMALL );
00265         case MBEDTLS_ERR_MPI_NEGATIVE_VALUE:
00266             return( PSA_ERROR_INVALID_ARGUMENT );
00267         case MBEDTLS_ERR_MPI_DIVISION_BY_ZERO:
00268             return( PSA_ERROR_INVALID_ARGUMENT );
00269         case MBEDTLS_ERR_MPI_NOT_ACCEPTABLE:
00270             return( PSA_ERROR_INVALID_ARGUMENT );
00271         case MBEDTLS_ERR_MPI_ALLOC_FAILED:
00272             return( PSA_ERROR_INSUFFICIENT_MEMORY );
00273 
00274         case MBEDTLS_ERR_PK_ALLOC_FAILED:
00275             return( PSA_ERROR_INSUFFICIENT_MEMORY );
00276         case MBEDTLS_ERR_PK_TYPE_MISMATCH:
00277         case MBEDTLS_ERR_PK_BAD_INPUT_DATA:
00278             return( PSA_ERROR_INVALID_ARGUMENT );
00279         case MBEDTLS_ERR_PK_FILE_IO_ERROR:
00280             return( PSA_ERROR_STORAGE_FAILURE );
00281         case MBEDTLS_ERR_PK_KEY_INVALID_VERSION:
00282         case MBEDTLS_ERR_PK_KEY_INVALID_FORMAT:
00283             return( PSA_ERROR_INVALID_ARGUMENT );
00284         case MBEDTLS_ERR_PK_UNKNOWN_PK_ALG:
00285             return( PSA_ERROR_NOT_SUPPORTED );
00286         case MBEDTLS_ERR_PK_PASSWORD_REQUIRED:
00287         case MBEDTLS_ERR_PK_PASSWORD_MISMATCH:
00288             return( PSA_ERROR_NOT_PERMITTED );
00289         case MBEDTLS_ERR_PK_INVALID_PUBKEY:
00290             return( PSA_ERROR_INVALID_ARGUMENT );
00291         case MBEDTLS_ERR_PK_INVALID_ALG:
00292         case MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE:
00293         case MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE:
00294             return( PSA_ERROR_NOT_SUPPORTED );
00295         case MBEDTLS_ERR_PK_SIG_LEN_MISMATCH:
00296             return( PSA_ERROR_INVALID_SIGNATURE );
00297         case MBEDTLS_ERR_PK_HW_ACCEL_FAILED:
00298             return( PSA_ERROR_HARDWARE_FAILURE );
00299 
00300         case MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED:
00301             return( PSA_ERROR_HARDWARE_FAILURE );
00302         case MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED:
00303             return( PSA_ERROR_NOT_SUPPORTED );
00304 
00305         case MBEDTLS_ERR_RIPEMD160_HW_ACCEL_FAILED:
00306             return( PSA_ERROR_HARDWARE_FAILURE );
00307 
00308         case MBEDTLS_ERR_RSA_BAD_INPUT_DATA:
00309             return( PSA_ERROR_INVALID_ARGUMENT );
00310         case MBEDTLS_ERR_RSA_INVALID_PADDING:
00311             return( PSA_ERROR_INVALID_PADDING );
00312         case MBEDTLS_ERR_RSA_KEY_GEN_FAILED:
00313             return( PSA_ERROR_HARDWARE_FAILURE );
00314         case MBEDTLS_ERR_RSA_KEY_CHECK_FAILED:
00315             return( PSA_ERROR_INVALID_ARGUMENT );
00316         case MBEDTLS_ERR_RSA_PUBLIC_FAILED:
00317         case MBEDTLS_ERR_RSA_PRIVATE_FAILED:
00318             return( PSA_ERROR_CORRUPTION_DETECTED );
00319         case MBEDTLS_ERR_RSA_VERIFY_FAILED:
00320             return( PSA_ERROR_INVALID_SIGNATURE );
00321         case MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE:
00322             return( PSA_ERROR_BUFFER_TOO_SMALL );
00323         case MBEDTLS_ERR_RSA_RNG_FAILED:
00324             return( PSA_ERROR_INSUFFICIENT_MEMORY );
00325         case MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION:
00326             return( PSA_ERROR_NOT_SUPPORTED );
00327         case MBEDTLS_ERR_RSA_HW_ACCEL_FAILED:
00328             return( PSA_ERROR_HARDWARE_FAILURE );
00329 
00330         case MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED:
00331         case MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED:
00332         case MBEDTLS_ERR_SHA512_HW_ACCEL_FAILED:
00333             return( PSA_ERROR_HARDWARE_FAILURE );
00334 
00335         case MBEDTLS_ERR_XTEA_INVALID_INPUT_LENGTH:
00336             return( PSA_ERROR_INVALID_ARGUMENT );
00337         case MBEDTLS_ERR_XTEA_HW_ACCEL_FAILED:
00338             return( PSA_ERROR_HARDWARE_FAILURE );
00339 
00340         case MBEDTLS_ERR_ECP_BAD_INPUT_DATA:
00341         case MBEDTLS_ERR_ECP_INVALID_KEY:
00342             return( PSA_ERROR_INVALID_ARGUMENT );
00343         case MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL:
00344             return( PSA_ERROR_BUFFER_TOO_SMALL );
00345         case MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE:
00346             return( PSA_ERROR_NOT_SUPPORTED );
00347         case MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH:
00348         case MBEDTLS_ERR_ECP_VERIFY_FAILED:
00349             return( PSA_ERROR_INVALID_SIGNATURE );
00350         case MBEDTLS_ERR_ECP_ALLOC_FAILED:
00351             return( PSA_ERROR_INSUFFICIENT_MEMORY );
00352         case MBEDTLS_ERR_ECP_HW_ACCEL_FAILED:
00353             return( PSA_ERROR_HARDWARE_FAILURE );
00354 
00355         default:
00356             return( PSA_ERROR_GENERIC_ERROR );
00357     }
00358 }
00359 
00360 
00361 
00362 
00363 /****************************************************************/
00364 /* Key management */
00365 /****************************************************************/
00366 
00367 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
00368 static inline int psa_key_slot_is_external( const psa_key_slot_t *slot )
00369 {
00370     return( psa_key_lifetime_is_external( slot->attr.lifetime ) );
00371 }
00372 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
00373 
00374 #if defined(MBEDTLS_ECP_C)
00375 static psa_ecc_curve_t mbedtls_ecc_group_to_psa( mbedtls_ecp_group_id grpid )
00376 {
00377     switch( grpid )
00378     {
00379         case MBEDTLS_ECP_DP_SECP192R1:
00380             return( PSA_ECC_CURVE_SECP192R1 );
00381         case MBEDTLS_ECP_DP_SECP224R1:
00382             return( PSA_ECC_CURVE_SECP224R1 );
00383         case MBEDTLS_ECP_DP_SECP256R1:
00384             return( PSA_ECC_CURVE_SECP256R1 );
00385         case MBEDTLS_ECP_DP_SECP384R1:
00386             return( PSA_ECC_CURVE_SECP384R1 );
00387         case MBEDTLS_ECP_DP_SECP521R1:
00388             return( PSA_ECC_CURVE_SECP521R1 );
00389         case MBEDTLS_ECP_DP_BP256R1:
00390             return( PSA_ECC_CURVE_BRAINPOOL_P256R1 );
00391         case MBEDTLS_ECP_DP_BP384R1:
00392             return( PSA_ECC_CURVE_BRAINPOOL_P384R1 );
00393         case MBEDTLS_ECP_DP_BP512R1:
00394             return( PSA_ECC_CURVE_BRAINPOOL_P512R1 );
00395         case MBEDTLS_ECP_DP_CURVE25519:
00396             return( PSA_ECC_CURVE_CURVE25519 );
00397         case MBEDTLS_ECP_DP_SECP192K1:
00398             return( PSA_ECC_CURVE_SECP192K1 );
00399         case MBEDTLS_ECP_DP_SECP224K1:
00400             return( PSA_ECC_CURVE_SECP224K1 );
00401         case MBEDTLS_ECP_DP_SECP256K1:
00402             return( PSA_ECC_CURVE_SECP256K1 );
00403         case MBEDTLS_ECP_DP_CURVE448:
00404             return( PSA_ECC_CURVE_CURVE448 );
00405         default:
00406             return( 0 );
00407     }
00408 }
00409 
00410 static mbedtls_ecp_group_id mbedtls_ecc_group_of_psa( psa_ecc_curve_t curve )
00411 {
00412     switch( curve )
00413     {
00414         case PSA_ECC_CURVE_SECP192R1:
00415             return( MBEDTLS_ECP_DP_SECP192R1 );
00416         case PSA_ECC_CURVE_SECP224R1:
00417             return( MBEDTLS_ECP_DP_SECP224R1 );
00418         case PSA_ECC_CURVE_SECP256R1:
00419             return( MBEDTLS_ECP_DP_SECP256R1 );
00420         case PSA_ECC_CURVE_SECP384R1:
00421             return( MBEDTLS_ECP_DP_SECP384R1 );
00422         case PSA_ECC_CURVE_SECP521R1:
00423             return( MBEDTLS_ECP_DP_SECP521R1 );
00424         case PSA_ECC_CURVE_BRAINPOOL_P256R1:
00425             return( MBEDTLS_ECP_DP_BP256R1 );
00426         case PSA_ECC_CURVE_BRAINPOOL_P384R1:
00427             return( MBEDTLS_ECP_DP_BP384R1 );
00428         case PSA_ECC_CURVE_BRAINPOOL_P512R1:
00429             return( MBEDTLS_ECP_DP_BP512R1 );
00430         case PSA_ECC_CURVE_CURVE25519:
00431             return( MBEDTLS_ECP_DP_CURVE25519 );
00432         case PSA_ECC_CURVE_SECP192K1:
00433             return( MBEDTLS_ECP_DP_SECP192K1 );
00434         case PSA_ECC_CURVE_SECP224K1:
00435             return( MBEDTLS_ECP_DP_SECP224K1 );
00436         case PSA_ECC_CURVE_SECP256K1:
00437             return( MBEDTLS_ECP_DP_SECP256K1 );
00438         case PSA_ECC_CURVE_CURVE448:
00439             return( MBEDTLS_ECP_DP_CURVE448 );
00440         default:
00441             return( MBEDTLS_ECP_DP_NONE );
00442     }
00443 }
00444 #endif /* defined(MBEDTLS_ECP_C) */
00445 
00446 static psa_status_t prepare_raw_data_slot( psa_key_type_t type,
00447                                            size_t bits,
00448                                            struct raw_data *raw )
00449 {
00450     /* Check that the bit size is acceptable for the key type */
00451     switch( type )
00452     {
00453         case PSA_KEY_TYPE_RAW_DATA:
00454 #if defined(MBEDTLS_MD_C)
00455         case PSA_KEY_TYPE_HMAC:
00456 #endif
00457         case PSA_KEY_TYPE_DERIVE:
00458             break;
00459 #if defined(MBEDTLS_AES_C)
00460         case PSA_KEY_TYPE_AES:
00461             if( bits != 128 && bits != 192 && bits != 256 )
00462                 return( PSA_ERROR_INVALID_ARGUMENT );
00463             break;
00464 #endif
00465 #if defined(MBEDTLS_CAMELLIA_C)
00466         case PSA_KEY_TYPE_CAMELLIA:
00467             if( bits != 128 && bits != 192 && bits != 256 )
00468                 return( PSA_ERROR_INVALID_ARGUMENT );
00469             break;
00470 #endif
00471 #if defined(MBEDTLS_DES_C)
00472         case PSA_KEY_TYPE_DES:
00473             if( bits != 64 && bits != 128 && bits != 192 )
00474                 return( PSA_ERROR_INVALID_ARGUMENT );
00475             break;
00476 #endif
00477 #if defined(MBEDTLS_ARC4_C)
00478         case PSA_KEY_TYPE_ARC4:
00479             if( bits < 8 || bits > 2048 )
00480                 return( PSA_ERROR_INVALID_ARGUMENT );
00481             break;
00482 #endif
00483 #if defined(MBEDTLS_CHACHA20_C)
00484         case PSA_KEY_TYPE_CHACHA20:
00485             if( bits != 256 )
00486                 return( PSA_ERROR_INVALID_ARGUMENT );
00487             break;
00488 #endif
00489         default:
00490             return( PSA_ERROR_NOT_SUPPORTED );
00491     }
00492     if( bits % 8 != 0 )
00493         return( PSA_ERROR_INVALID_ARGUMENT );
00494 
00495     /* Allocate memory for the key */
00496     raw->bytes = PSA_BITS_TO_BYTES( bits );
00497     raw->data = mbedtls_calloc( 1, raw->bytes );
00498     if( raw->data == NULL )
00499     {
00500         raw->bytes = 0;
00501         return( PSA_ERROR_INSUFFICIENT_MEMORY );
00502     }
00503     return( PSA_SUCCESS );
00504 }
00505 
00506 #if defined(MBEDTLS_RSA_C) && defined(MBEDTLS_PK_PARSE_C)
00507 /* Mbed TLS doesn't support non-byte-aligned key sizes (i.e. key sizes
00508  * that are not a multiple of 8) well. For example, there is only
00509  * mbedtls_rsa_get_len(), which returns a number of bytes, and no
00510  * way to return the exact bit size of a key.
00511  * To keep things simple, reject non-byte-aligned key sizes. */
00512 static psa_status_t psa_check_rsa_key_byte_aligned(
00513     const mbedtls_rsa_context *rsa )
00514 {
00515     mbedtls_mpi n;
00516     psa_status_t status;
00517     mbedtls_mpi_init( &n );
00518     status = mbedtls_to_psa_error(
00519         mbedtls_rsa_export( rsa, &n, NULL, NULL, NULL, NULL ) );
00520     if( status == PSA_SUCCESS )
00521     {
00522         if( mbedtls_mpi_bitlen( &n ) % 8 != 0 )
00523             status = PSA_ERROR_NOT_SUPPORTED;
00524     }
00525     mbedtls_mpi_free( &n );
00526     return( status );
00527 }
00528 
00529 static psa_status_t psa_import_rsa_key( psa_key_type_t type,
00530                                         const uint8_t *data,
00531                                         size_t data_length,
00532                                         mbedtls_rsa_context **p_rsa )
00533 {
00534     psa_status_t status;
00535     mbedtls_pk_context pk;
00536     mbedtls_rsa_context *rsa;
00537     size_t bits;
00538 
00539     mbedtls_pk_init( &pk );
00540 
00541     /* Parse the data. */
00542     if( PSA_KEY_TYPE_IS_KEY_PAIR( type ) )
00543         status = mbedtls_to_psa_error(
00544             mbedtls_pk_parse_key( &pk, data, data_length, NULL, 0 ) );
00545     else
00546         status = mbedtls_to_psa_error(
00547             mbedtls_pk_parse_public_key( &pk, data, data_length ) );
00548     if( status != PSA_SUCCESS )
00549         goto exit;
00550 
00551     /* We have something that the pkparse module recognizes. If it is a
00552      * valid RSA key, store it. */
00553     if( mbedtls_pk_get_type( &pk ) != MBEDTLS_PK_RSA )
00554     {
00555         status = PSA_ERROR_INVALID_ARGUMENT;
00556         goto exit;
00557     }
00558 
00559     rsa = mbedtls_pk_rsa( pk );
00560     /* The size of an RSA key doesn't have to be a multiple of 8. Mbed TLS
00561      * supports non-byte-aligned key sizes, but not well. For example,
00562      * mbedtls_rsa_get_len() returns the key size in bytes, not in bits. */
00563     bits = PSA_BYTES_TO_BITS( mbedtls_rsa_get_len( rsa ) );
00564     if( bits > PSA_VENDOR_RSA_MAX_KEY_BITS )
00565     {
00566         status = PSA_ERROR_NOT_SUPPORTED;
00567         goto exit;
00568     }
00569     status = psa_check_rsa_key_byte_aligned( rsa );
00570 
00571 exit:
00572     /* Free the content of the pk object only on error. */
00573     if( status != PSA_SUCCESS )
00574     {
00575         mbedtls_pk_free( &pk );
00576         return( status );
00577     }
00578 
00579     /* On success, store the content of the object in the RSA context. */
00580     *p_rsa = rsa;
00581 
00582     return( PSA_SUCCESS );
00583 }
00584 #endif /* defined(MBEDTLS_RSA_C) && defined(MBEDTLS_PK_PARSE_C) */
00585 
00586 #if defined(MBEDTLS_ECP_C)
00587 
00588 /* Import a public key given as the uncompressed representation defined by SEC1
00589  * 2.3.3 as the content of an ECPoint. */
00590 static psa_status_t psa_import_ec_public_key( psa_ecc_curve_t curve,
00591                                               const uint8_t *data,
00592                                               size_t data_length,
00593                                               mbedtls_ecp_keypair **p_ecp )
00594 {
00595     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
00596     mbedtls_ecp_keypair *ecp = NULL;
00597     mbedtls_ecp_group_id grp_id = mbedtls_ecc_group_of_psa( curve );
00598 
00599     *p_ecp = NULL;
00600     ecp = mbedtls_calloc( 1, sizeof( *ecp ) );
00601     if( ecp == NULL )
00602         return( PSA_ERROR_INSUFFICIENT_MEMORY );
00603     mbedtls_ecp_keypair_init( ecp );
00604 
00605     /* Load the group. */
00606     status = mbedtls_to_psa_error(
00607         mbedtls_ecp_group_load( &ecp->grp , grp_id ) );
00608     if( status != PSA_SUCCESS )
00609         goto exit;
00610     /* Load the public value. */
00611     status = mbedtls_to_psa_error(
00612         mbedtls_ecp_point_read_binary( &ecp->grp , &ecp->Q ,
00613                                        data, data_length ) );
00614     if( status != PSA_SUCCESS )
00615         goto exit;
00616 
00617     /* Check that the point is on the curve. */
00618     status = mbedtls_to_psa_error(
00619         mbedtls_ecp_check_pubkey( &ecp->grp , &ecp->Q  ) );
00620     if( status != PSA_SUCCESS )
00621         goto exit;
00622 
00623     *p_ecp = ecp;
00624     return( PSA_SUCCESS );
00625 
00626 exit:
00627     if( ecp != NULL )
00628     {
00629         mbedtls_ecp_keypair_free( ecp );
00630         mbedtls_free( ecp );
00631     }
00632     return( status );
00633 }
00634 #endif /* defined(MBEDTLS_ECP_C) */
00635 
00636 #if defined(MBEDTLS_ECP_C)
00637 /* Import a private key given as a byte string which is the private value
00638  * in big-endian order. */
00639 static psa_status_t psa_import_ec_private_key( psa_ecc_curve_t curve,
00640                                                const uint8_t *data,
00641                                                size_t data_length,
00642                                                mbedtls_ecp_keypair **p_ecp )
00643 {
00644     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
00645     mbedtls_ecp_keypair *ecp = NULL;
00646     mbedtls_ecp_group_id grp_id = mbedtls_ecc_group_of_psa( curve );
00647 
00648     if( PSA_BITS_TO_BYTES( PSA_ECC_CURVE_BITS( curve ) ) != data_length )
00649         return( PSA_ERROR_INVALID_ARGUMENT );
00650 
00651     *p_ecp = NULL;
00652     ecp = mbedtls_calloc( 1, sizeof( mbedtls_ecp_keypair ) );
00653     if( ecp == NULL )
00654         return( PSA_ERROR_INSUFFICIENT_MEMORY );
00655     mbedtls_ecp_keypair_init( ecp );
00656 
00657     /* Load the group. */
00658     status = mbedtls_to_psa_error(
00659         mbedtls_ecp_group_load( &ecp->grp , grp_id ) );
00660     if( status != PSA_SUCCESS )
00661         goto exit;
00662     /* Load the secret value. */
00663     status = mbedtls_to_psa_error(
00664         mbedtls_mpi_read_binary( &ecp->d , data, data_length ) );
00665     if( status != PSA_SUCCESS )
00666         goto exit;
00667     /* Validate the private key. */
00668     status = mbedtls_to_psa_error(
00669         mbedtls_ecp_check_privkey( &ecp->grp , &ecp->d  ) );
00670     if( status != PSA_SUCCESS )
00671         goto exit;
00672     /* Calculate the public key from the private key. */
00673     status = mbedtls_to_psa_error(
00674         mbedtls_ecp_mul( &ecp->grp , &ecp->Q , &ecp->d , &ecp->grp .G ,
00675                          mbedtls_ctr_drbg_random, &global_data.ctr_drbg ) );
00676     if( status != PSA_SUCCESS )
00677         goto exit;
00678 
00679     *p_ecp = ecp;
00680     return( PSA_SUCCESS );
00681 
00682 exit:
00683     if( ecp != NULL )
00684     {
00685         mbedtls_ecp_keypair_free( ecp );
00686         mbedtls_free( ecp );
00687     }
00688     return( status );
00689 }
00690 #endif /* defined(MBEDTLS_ECP_C) */
00691 
00692 
00693 /** Return the size of the key in the given slot, in bits.
00694  *
00695  * \param[in] slot      A key slot.
00696  *
00697  * \return The key size in bits, read from the metadata in the slot.
00698  */
00699 static inline size_t psa_get_key_slot_bits( const psa_key_slot_t *slot )
00700 {
00701     return( slot->attr.bits );
00702 }
00703 
00704 /** Calculate the size of the key in the given slot, in bits.
00705  *
00706  * \param[in] slot      A key slot containing a transparent key.
00707  *
00708  * \return The key size in bits, calculated from the key data.
00709  */
00710 static psa_key_bits_t psa_calculate_key_bits( const psa_key_slot_t *slot )
00711 {
00712     size_t bits = 0; /* return 0 on an empty slot */
00713 
00714     if( key_type_is_raw_bytes( slot->attr.type ) )
00715         bits = PSA_BYTES_TO_BITS( slot->data.raw.bytes );
00716 #if defined(MBEDTLS_RSA_C)
00717     else if( PSA_KEY_TYPE_IS_RSA( slot->attr.type ) )
00718         bits = PSA_BYTES_TO_BITS( mbedtls_rsa_get_len( slot->data.rsa ) );
00719 #endif /* defined(MBEDTLS_RSA_C) */
00720 #if defined(MBEDTLS_ECP_C)
00721     else if( PSA_KEY_TYPE_IS_ECC( slot->attr.type ) )
00722         bits = slot->data.ecp->grp.pbits;
00723 #endif /* defined(MBEDTLS_ECP_C) */
00724 
00725     /* We know that the size fits in psa_key_bits_t thanks to checks
00726      * when the key was created. */
00727     return( (psa_key_bits_t) bits );
00728 }
00729 
00730 /** Import key data into a slot. `slot->attr.type` must have been set
00731  * previously. This function assumes that the slot does not contain
00732  * any key material yet. On failure, the slot content is unchanged. */
00733 psa_status_t psa_import_key_into_slot( psa_key_slot_t *slot,
00734                                        const uint8_t *data,
00735                                        size_t data_length )
00736 {
00737     psa_status_t status = PSA_SUCCESS;
00738 
00739     if( key_type_is_raw_bytes( slot->attr.type ) )
00740     {
00741         size_t bit_size = PSA_BYTES_TO_BITS( data_length );
00742         /* Ensure that the bytes-to-bit conversion didn't overflow. */
00743         if( data_length > SIZE_MAX / 8 )
00744             return( PSA_ERROR_NOT_SUPPORTED );
00745         /* Enforce a size limit, and in particular ensure that the bit
00746          * size fits in its representation type. */
00747         if( bit_size > PSA_MAX_KEY_BITS )
00748             return( PSA_ERROR_NOT_SUPPORTED );
00749         status = prepare_raw_data_slot( slot->attr.type, bit_size,
00750                                         &slot->data.raw );
00751         if( status != PSA_SUCCESS )
00752             return( status );
00753         if( data_length != 0 )
00754             memcpy( slot->data.raw.data, data, data_length );
00755     }
00756     else
00757 #if defined(MBEDTLS_ECP_C)
00758     if( PSA_KEY_TYPE_IS_ECC_KEY_PAIR( slot->attr.type ) )
00759     {
00760         status = psa_import_ec_private_key( PSA_KEY_TYPE_GET_CURVE( slot->attr.type ),
00761                                             data, data_length,
00762                                             &slot->data.ecp );
00763     }
00764     else if( PSA_KEY_TYPE_IS_ECC_PUBLIC_KEY( slot->attr.type ) )
00765     {
00766         status = psa_import_ec_public_key(
00767             PSA_KEY_TYPE_GET_CURVE( slot->attr.type ),
00768             data, data_length,
00769             &slot->data.ecp );
00770     }
00771     else
00772 #endif /* MBEDTLS_ECP_C */
00773 #if defined(MBEDTLS_RSA_C) && defined(MBEDTLS_PK_PARSE_C)
00774     if( PSA_KEY_TYPE_IS_RSA( slot->attr.type ) )
00775     {
00776         status = psa_import_rsa_key( slot->attr.type,
00777             data, data_length,
00778             &slot->data.rsa );
00779     }
00780     else
00781 #endif /* defined(MBEDTLS_RSA_C) && defined(MBEDTLS_PK_PARSE_C) */
00782     {
00783         return( PSA_ERROR_NOT_SUPPORTED );
00784     }
00785 
00786     if( status == PSA_SUCCESS )
00787     {
00788         /* Write the actual key size to the slot.
00789          * psa_start_key_creation() wrote the size declared by the
00790          * caller, which may be 0 (meaning unspecified) or wrong. */
00791         slot->attr.bits = psa_calculate_key_bits( slot );
00792     }
00793     return( status );
00794 }
00795 
00796 /** Calculate the intersection of two algorithm usage policies.
00797  *
00798  * Return 0 (which allows no operation) on incompatibility.
00799  */
00800 static psa_algorithm_t psa_key_policy_algorithm_intersection(
00801     psa_algorithm_t alg1,
00802     psa_algorithm_t alg2 )
00803 {
00804     /* Common case: both sides actually specify the same policy. */
00805     if( alg1 == alg2 )
00806         return( alg1 );
00807     /* If the policies are from the same hash-and-sign family, check
00808      * if one is a wildcard. If so the other has the specific algorithm. */
00809     if( PSA_ALG_IS_HASH_AND_SIGN( alg1 ) &&
00810         PSA_ALG_IS_HASH_AND_SIGN( alg2 ) &&
00811         ( alg1 & ~PSA_ALG_HASH_MASK ) == ( alg2 & ~PSA_ALG_HASH_MASK ) )
00812     {
00813         if( PSA_ALG_SIGN_GET_HASH( alg1 ) == PSA_ALG_ANY_HASH )
00814             return( alg2 );
00815         if( PSA_ALG_SIGN_GET_HASH( alg2 ) == PSA_ALG_ANY_HASH )
00816             return( alg1 );
00817     }
00818     /* If the policies are incompatible, allow nothing. */
00819     return( 0 );
00820 }
00821 
00822 static int psa_key_algorithm_permits( psa_algorithm_t policy_alg,
00823                                       psa_algorithm_t requested_alg )
00824 {
00825     /* Common case: the policy only allows requested_alg. */
00826     if( requested_alg == policy_alg )
00827         return( 1 );
00828     /* If policy_alg is a hash-and-sign with a wildcard for the hash,
00829      * and requested_alg is the same hash-and-sign family with any hash,
00830      * then requested_alg is compliant with policy_alg. */
00831     if( PSA_ALG_IS_HASH_AND_SIGN( requested_alg ) &&
00832         PSA_ALG_SIGN_GET_HASH( policy_alg ) == PSA_ALG_ANY_HASH )
00833     {
00834         return( ( policy_alg & ~PSA_ALG_HASH_MASK ) ==
00835                 ( requested_alg & ~PSA_ALG_HASH_MASK ) );
00836     }
00837     /* If it isn't permitted, it's forbidden. */
00838     return( 0 );
00839 }
00840 
00841 /** Test whether a policy permits an algorithm.
00842  *
00843  * The caller must test usage flags separately.
00844  */
00845 static int psa_key_policy_permits( const psa_key_policy_t *policy,
00846                                    psa_algorithm_t alg )
00847 {
00848     return( psa_key_algorithm_permits( policy->alg, alg ) ||
00849             psa_key_algorithm_permits( policy->alg2, alg ) );
00850 }
00851 
00852 /** Restrict a key policy based on a constraint.
00853  *
00854  * \param[in,out] policy    The policy to restrict.
00855  * \param[in] constraint    The policy constraint to apply.
00856  *
00857  * \retval #PSA_SUCCESS
00858  *         \c *policy contains the intersection of the original value of
00859  *         \c *policy and \c *constraint.
00860  * \retval #PSA_ERROR_INVALID_ARGUMENT
00861  *         \c *policy and \c *constraint are incompatible.
00862  *         \c *policy is unchanged.
00863  */
00864 static psa_status_t psa_restrict_key_policy(
00865     psa_key_policy_t *policy,
00866     const psa_key_policy_t *constraint )
00867 {
00868     psa_algorithm_t intersection_alg =
00869         psa_key_policy_algorithm_intersection( policy->alg, constraint->alg );
00870     psa_algorithm_t intersection_alg2 =
00871         psa_key_policy_algorithm_intersection( policy->alg2, constraint->alg2 );
00872     if( intersection_alg == 0 && policy->alg != 0 && constraint->alg != 0 )
00873         return( PSA_ERROR_INVALID_ARGUMENT );
00874     if( intersection_alg2 == 0 && policy->alg2 != 0 && constraint->alg2 != 0 )
00875         return( PSA_ERROR_INVALID_ARGUMENT );
00876     policy->usage &= constraint->usage;
00877     policy->alg = intersection_alg;
00878     policy->alg2 = intersection_alg2;
00879     return( PSA_SUCCESS );
00880 }
00881 
00882 /** Retrieve a slot which must contain a key. The key must have allow all the
00883  * usage flags set in \p usage. If \p alg is nonzero, the key must allow
00884  * operations with this algorithm. */
00885 static psa_status_t psa_get_key_from_slot( psa_key_handle_t handle,
00886                                            psa_key_slot_t **p_slot,
00887                                            psa_key_usage_t usage,
00888                                            psa_algorithm_t alg )
00889 {
00890     psa_status_t status;
00891     psa_key_slot_t *slot = NULL;
00892 
00893     *p_slot = NULL;
00894 
00895     status = psa_get_key_slot( handle, &slot );
00896     if( status != PSA_SUCCESS )
00897         return( status );
00898 
00899     /* Enforce that usage policy for the key slot contains all the flags
00900      * required by the usage parameter. There is one exception: public
00901      * keys can always be exported, so we treat public key objects as
00902      * if they had the export flag. */
00903     if( PSA_KEY_TYPE_IS_PUBLIC_KEY( slot->attr.type ) )
00904         usage &= ~PSA_KEY_USAGE_EXPORT;
00905     if( ( slot->attr.policy.usage & usage ) != usage )
00906         return( PSA_ERROR_NOT_PERMITTED );
00907 
00908     /* Enforce that the usage policy permits the requested algortihm. */
00909     if( alg != 0 && ! psa_key_policy_permits( &slot->attr.policy, alg ) )
00910         return( PSA_ERROR_NOT_PERMITTED );
00911 
00912     *p_slot = slot;
00913     return( PSA_SUCCESS );
00914 }
00915 
00916 /** Retrieve a slot which must contain a transparent key.
00917  *
00918  * A transparent key is a key for which the key material is directly
00919  * available, as opposed to a key in a secure element.
00920  *
00921  * This is a temporary function to use instead of psa_get_key_from_slot()
00922  * until secure element support is fully implemented.
00923  */
00924 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
00925 static psa_status_t psa_get_transparent_key( psa_key_handle_t handle,
00926                                              psa_key_slot_t **p_slot,
00927                                              psa_key_usage_t usage,
00928                                              psa_algorithm_t alg )
00929 {
00930     psa_status_t status = psa_get_key_from_slot( handle, p_slot, usage, alg );
00931     if( status != PSA_SUCCESS )
00932         return( status );
00933     if( psa_key_slot_is_external( *p_slot ) )
00934     {
00935         *p_slot = NULL;
00936         return( PSA_ERROR_NOT_SUPPORTED );
00937     }
00938     return( PSA_SUCCESS );
00939 }
00940 #else /* MBEDTLS_PSA_CRYPTO_SE_C */
00941 /* With no secure element support, all keys are transparent. */
00942 #define psa_get_transparent_key( handle, p_slot, usage, alg )   \
00943     psa_get_key_from_slot( handle, p_slot, usage, alg )
00944 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
00945 
00946 /** Wipe key data from a slot. Preserve metadata such as the policy. */
00947 static psa_status_t psa_remove_key_data_from_memory( psa_key_slot_t *slot )
00948 {
00949 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
00950     if( psa_key_slot_is_external( slot ) )
00951     {
00952         /* No key material to clean. */
00953     }
00954     else
00955 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
00956     if( slot->attr.type == PSA_KEY_TYPE_NONE )
00957     {
00958         /* No key material to clean. */
00959     }
00960     else if( key_type_is_raw_bytes( slot->attr.type ) )
00961     {
00962         mbedtls_free( slot->data.raw.data );
00963     }
00964     else
00965 #if defined(MBEDTLS_RSA_C)
00966     if( PSA_KEY_TYPE_IS_RSA( slot->attr.type ) )
00967     {
00968         mbedtls_rsa_free( slot->data.rsa );
00969         mbedtls_free( slot->data.rsa );
00970     }
00971     else
00972 #endif /* defined(MBEDTLS_RSA_C) */
00973 #if defined(MBEDTLS_ECP_C)
00974     if( PSA_KEY_TYPE_IS_ECC( slot->attr.type ) )
00975     {
00976         mbedtls_ecp_keypair_free( slot->data.ecp );
00977         mbedtls_free( slot->data.ecp );
00978     }
00979     else
00980 #endif /* defined(MBEDTLS_ECP_C) */
00981     {
00982         /* Shouldn't happen: the key type is not any type that we
00983          * put in. */
00984         return( PSA_ERROR_CORRUPTION_DETECTED );
00985     }
00986 
00987     return( PSA_SUCCESS );
00988 }
00989 
00990 /** Completely wipe a slot in memory, including its policy.
00991  * Persistent storage is not affected. */
00992 psa_status_t psa_wipe_key_slot( psa_key_slot_t *slot )
00993 {
00994     psa_status_t status = psa_remove_key_data_from_memory( slot );
00995     /* Multipart operations may still be using the key. This is safe
00996      * because all multipart operation objects are independent from
00997      * the key slot: if they need to access the key after the setup
00998      * phase, they have a copy of the key. Note that this means that
00999      * key material can linger until all operations are completed. */
01000     /* At this point, key material and other type-specific content has
01001      * been wiped. Clear remaining metadata. We can call memset and not
01002      * zeroize because the metadata is not particularly sensitive. */
01003     memset( slot, 0, sizeof( *slot ) );
01004     return( status );
01005 }
01006 
01007 psa_status_t psa_destroy_key( psa_key_handle_t handle )
01008 {
01009     psa_key_slot_t *slot;
01010     psa_status_t status; /* status of the last operation */
01011     psa_status_t overall_status = PSA_SUCCESS;
01012 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
01013     psa_se_drv_table_entry_t *driver;
01014 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
01015 
01016     if( handle == 0 )
01017         return( PSA_SUCCESS );
01018 
01019     status = psa_get_key_slot( handle, &slot );
01020     if( status != PSA_SUCCESS )
01021         return( status );
01022 
01023 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
01024     driver = psa_get_se_driver_entry( slot->attr.lifetime );
01025     if( driver != NULL )
01026     {
01027         /* For a key in a secure element, we need to do three things:
01028          * remove the key file in internal storage, destroy the
01029          * key inside the secure element, and update the driver's
01030          * persistent data. Start a transaction that will encompass these
01031          * three actions. */
01032         psa_crypto_prepare_transaction( PSA_CRYPTO_TRANSACTION_DESTROY_KEY );
01033         psa_crypto_transaction.key.lifetime = slot->attr.lifetime;
01034         psa_crypto_transaction.key.slot = slot->data.se.slot_number;
01035         psa_crypto_transaction.key.id = slot->attr.id;
01036         status = psa_crypto_save_transaction( );
01037         if( status != PSA_SUCCESS )
01038         {
01039             (void) psa_crypto_stop_transaction( );
01040             /* We should still try to destroy the key in the secure
01041              * element and the key metadata in storage. This is especially
01042              * important if the error is that the storage is full.
01043              * But how to do it exactly without risking an inconsistent
01044              * state after a reset?
01045              * https://github.com/ARMmbed/mbed-crypto/issues/215
01046              */
01047             overall_status = status;
01048             goto exit;
01049         }
01050 
01051         status = psa_destroy_se_key( driver, slot->data.se.slot_number );
01052         if( overall_status == PSA_SUCCESS )
01053             overall_status = status;
01054     }
01055 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
01056 
01057 #if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C)
01058     if( slot->attr.lifetime != PSA_KEY_LIFETIME_VOLATILE )
01059     {
01060         status = psa_destroy_persistent_key( slot->attr.id );
01061         if( overall_status == PSA_SUCCESS )
01062             overall_status = status;
01063 
01064         /* TODO: other slots may have a copy of the same key. We should
01065          * invalidate them.
01066          * https://github.com/ARMmbed/mbed-crypto/issues/214
01067          */
01068     }
01069 #endif /* defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) */
01070 
01071 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
01072     if( driver != NULL )
01073     {
01074         status = psa_save_se_persistent_data( driver );
01075         if( overall_status == PSA_SUCCESS )
01076             overall_status = status;
01077         status = psa_crypto_stop_transaction( );
01078         if( overall_status == PSA_SUCCESS )
01079             overall_status = status;
01080     }
01081 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
01082 
01083 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
01084 exit:
01085 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
01086     status = psa_wipe_key_slot( slot );
01087     /* Prioritize CORRUPTION_DETECTED from wiping over a storage error */
01088     if( overall_status == PSA_SUCCESS )
01089         overall_status = status;
01090     return( overall_status );
01091 }
01092 
01093 void psa_reset_key_attributes( psa_key_attributes_t *attributes )
01094 {
01095     mbedtls_free( attributes->domain_parameters );
01096     memset( attributes, 0, sizeof( *attributes ) );
01097 }
01098 
01099 psa_status_t psa_set_key_domain_parameters( psa_key_attributes_t *attributes,
01100                                             psa_key_type_t type,
01101                                             const uint8_t *data,
01102                                             size_t data_length )
01103 {
01104     uint8_t *copy = NULL;
01105 
01106     if( data_length != 0 )
01107     {
01108         copy = mbedtls_calloc( 1, data_length );
01109         if( copy == NULL )
01110             return( PSA_ERROR_INSUFFICIENT_MEMORY );
01111         memcpy( copy, data, data_length );
01112     }
01113     /* After this point, this function is guaranteed to succeed, so it
01114      * can start modifying `*attributes`. */
01115 
01116     if( attributes->domain_parameters != NULL )
01117     {
01118         mbedtls_free( attributes->domain_parameters );
01119         attributes->domain_parameters = NULL;
01120         attributes->domain_parameters_size = 0;
01121     }
01122 
01123     attributes->domain_parameters = copy;
01124     attributes->domain_parameters_size = data_length;
01125     attributes->core.type = type;
01126     return( PSA_SUCCESS );
01127 }
01128 
01129 psa_status_t psa_get_key_domain_parameters(
01130     const psa_key_attributes_t *attributes,
01131     uint8_t *data, size_t data_size, size_t *data_length )
01132 {
01133     if( attributes->domain_parameters_size > data_size )
01134         return( PSA_ERROR_BUFFER_TOO_SMALL );
01135     *data_length = attributes->domain_parameters_size;
01136     if( attributes->domain_parameters_size != 0 )
01137         memcpy( data, attributes->domain_parameters,
01138                 attributes->domain_parameters_size );
01139     return( PSA_SUCCESS );
01140 }
01141 
01142 #if defined(MBEDTLS_RSA_C)
01143 static psa_status_t psa_get_rsa_public_exponent(
01144     const mbedtls_rsa_context *rsa,
01145     psa_key_attributes_t *attributes )
01146 {
01147     mbedtls_mpi mpi;
01148     int ret;
01149     uint8_t *buffer = NULL;
01150     size_t buflen;
01151     mbedtls_mpi_init( &mpi );
01152 
01153     ret = mbedtls_rsa_export( rsa, NULL, NULL, NULL, NULL, &mpi );
01154     if( ret != 0 )
01155         goto exit;
01156     if( mbedtls_mpi_cmp_int( &mpi, 65537 ) == 0 )
01157     {
01158         /* It's the default value, which is reported as an empty string,
01159          * so there's nothing to do. */
01160         goto exit;
01161     }
01162 
01163     buflen = mbedtls_mpi_size( &mpi );
01164     buffer = mbedtls_calloc( 1, buflen );
01165     if( buffer == NULL )
01166     {
01167         ret = MBEDTLS_ERR_MPI_ALLOC_FAILED;
01168         goto exit;
01169     }
01170     ret = mbedtls_mpi_write_binary( &mpi, buffer, buflen );
01171     if( ret != 0 )
01172         goto exit;
01173     attributes->domain_parameters = buffer;
01174     attributes->domain_parameters_size = buflen;
01175 
01176 exit:
01177     mbedtls_mpi_free( &mpi );
01178     if( ret != 0 )
01179         mbedtls_free( buffer );
01180     return( mbedtls_to_psa_error( ret ) );
01181 }
01182 #endif /* MBEDTLS_RSA_C */
01183 
01184 /** Retrieve all the publicly-accessible attributes of a key.
01185  */
01186 psa_status_t psa_get_key_attributes( psa_key_handle_t handle,
01187                                      psa_key_attributes_t *attributes )
01188 {
01189     psa_key_slot_t *slot;
01190     psa_status_t status;
01191 
01192     psa_reset_key_attributes( attributes );
01193 
01194     status = psa_get_key_from_slot( handle, &slot, 0, 0 );
01195     if( status != PSA_SUCCESS )
01196         return( status );
01197 
01198     attributes->core = slot->attr;
01199     attributes->core.flags &= ( MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY |
01200                                 MBEDTLS_PSA_KA_MASK_DUAL_USE );
01201 
01202 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
01203     if( psa_key_slot_is_external( slot ) )
01204         psa_set_key_slot_number( attributes, slot->data.se.slot_number );
01205 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
01206 
01207     switch( slot->attr.type )
01208     {
01209 #if defined(MBEDTLS_RSA_C)
01210         case PSA_KEY_TYPE_RSA_KEY_PAIR:
01211         case PSA_KEY_TYPE_RSA_PUBLIC_KEY:
01212 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
01213             /* TODO: reporting the public exponent for opaque keys
01214              * is not yet implemented.
01215              * https://github.com/ARMmbed/mbed-crypto/issues/216
01216              */
01217             if( psa_key_slot_is_external( slot ) )
01218                 break;
01219 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
01220             status = psa_get_rsa_public_exponent( slot->data.rsa, attributes );
01221             break;
01222 #endif /* MBEDTLS_RSA_C */
01223         default:
01224             /* Nothing else to do. */
01225             break;
01226     }
01227 
01228     if( status != PSA_SUCCESS )
01229         psa_reset_key_attributes( attributes );
01230     return( status );
01231 }
01232 
01233 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
01234 psa_status_t psa_get_key_slot_number(
01235     const psa_key_attributes_t *attributes,
01236     psa_key_slot_number_t *slot_number )
01237 {
01238     if( attributes->core.flags & MBEDTLS_PSA_KA_FLAG_HAS_SLOT_NUMBER )
01239     {
01240         *slot_number = attributes->slot_number;
01241         return( PSA_SUCCESS );
01242     }
01243     else
01244         return( PSA_ERROR_INVALID_ARGUMENT );
01245 }
01246 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
01247 
01248 #if defined(MBEDTLS_RSA_C) || defined(MBEDTLS_ECP_C)
01249 static int pk_write_pubkey_simple( mbedtls_pk_context *key,
01250                                    unsigned char *buf, size_t size )
01251 {
01252     int ret;
01253     unsigned char *c;
01254     size_t len = 0;
01255 
01256     c = buf + size;
01257 
01258     MBEDTLS_ASN1_CHK_ADD( len, mbedtls_pk_write_pubkey( &c, buf, key ) );
01259 
01260     return( (int) len );
01261 }
01262 #endif /* defined(MBEDTLS_RSA_C) || defined(MBEDTLS_ECP_C) */
01263 
01264 static psa_status_t psa_internal_export_key( const psa_key_slot_t *slot,
01265                                              uint8_t *data,
01266                                              size_t data_size,
01267                                              size_t *data_length,
01268                                              int export_public_key )
01269 {
01270 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
01271     const psa_drv_se_t *drv;
01272     psa_drv_se_context_t *drv_context;
01273 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
01274 
01275     *data_length = 0;
01276 
01277     if( export_public_key && ! PSA_KEY_TYPE_IS_ASYMMETRIC( slot->attr.type ) )
01278         return( PSA_ERROR_INVALID_ARGUMENT );
01279 
01280     /* Reject a zero-length output buffer now, since this can never be a
01281      * valid key representation. This way we know that data must be a valid
01282      * pointer and we can do things like memset(data, ..., data_size). */
01283     if( data_size == 0 )
01284         return( PSA_ERROR_BUFFER_TOO_SMALL );
01285 
01286 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
01287     if( psa_get_se_driver( slot->attr.lifetime, &drv, &drv_context ) )
01288     {
01289         psa_drv_se_export_key_t method;
01290         if( drv->key_management == NULL )
01291             return( PSA_ERROR_NOT_SUPPORTED );
01292         method = ( export_public_key ?
01293                    drv->key_management->p_export_public :
01294                    drv->key_management->p_export );
01295         if( method == NULL )
01296             return( PSA_ERROR_NOT_SUPPORTED );
01297         return( method( drv_context,
01298                         slot->data.se.slot_number,
01299                         data, data_size, data_length ) );
01300     }
01301 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
01302 
01303     if( key_type_is_raw_bytes( slot->attr.type ) )
01304     {
01305         if( slot->data.raw.bytes > data_size )
01306             return( PSA_ERROR_BUFFER_TOO_SMALL );
01307         memcpy( data, slot->data.raw.data, slot->data.raw.bytes );
01308         memset( data + slot->data.raw.bytes, 0,
01309                 data_size - slot->data.raw.bytes );
01310         *data_length = slot->data.raw.bytes;
01311         return( PSA_SUCCESS );
01312     }
01313 #if defined(MBEDTLS_ECP_C)
01314     if( PSA_KEY_TYPE_IS_ECC_KEY_PAIR( slot->attr.type ) && !export_public_key )
01315     {
01316         psa_status_t status;
01317 
01318         size_t bytes = PSA_BITS_TO_BYTES( slot->attr.bits );
01319         if( bytes > data_size )
01320             return( PSA_ERROR_BUFFER_TOO_SMALL );
01321         status = mbedtls_to_psa_error(
01322             mbedtls_mpi_write_binary( &slot->data.ecp->d, data, bytes ) );
01323         if( status != PSA_SUCCESS )
01324             return( status );
01325         memset( data + bytes, 0, data_size - bytes );
01326         *data_length = bytes;
01327         return( PSA_SUCCESS );
01328     }
01329 #endif
01330     else
01331     {
01332 #if defined(MBEDTLS_PK_WRITE_C)
01333         if( PSA_KEY_TYPE_IS_RSA( slot->attr.type ) ||
01334             PSA_KEY_TYPE_IS_ECC( slot->attr.type ) )
01335         {
01336             mbedtls_pk_context pk;
01337             int ret;
01338             if( PSA_KEY_TYPE_IS_RSA( slot->attr.type ) )
01339             {
01340 #if defined(MBEDTLS_RSA_C)
01341                 mbedtls_pk_init( &pk );
01342                 pk.pk_info = &mbedtls_rsa_info;
01343                 pk.pk_ctx = slot->data.rsa;
01344 #else
01345                 return( PSA_ERROR_NOT_SUPPORTED );
01346 #endif
01347             }
01348             else
01349             {
01350 #if defined(MBEDTLS_ECP_C)
01351                 mbedtls_pk_init( &pk );
01352                 pk.pk_info = &mbedtls_eckey_info;
01353                 pk.pk_ctx = slot->data.ecp;
01354 #else
01355                 return( PSA_ERROR_NOT_SUPPORTED );
01356 #endif
01357             }
01358             if( export_public_key || PSA_KEY_TYPE_IS_PUBLIC_KEY( slot->attr.type ) )
01359             {
01360                 ret = pk_write_pubkey_simple( &pk, data, data_size );
01361             }
01362             else
01363             {
01364                 ret = mbedtls_pk_write_key_der( &pk, data, data_size );
01365             }
01366             if( ret < 0 )
01367             {
01368                 memset( data, 0, data_size );
01369                 return( mbedtls_to_psa_error( ret ) );
01370             }
01371             /* The mbedtls_pk_xxx functions write to the end of the buffer.
01372              * Move the data to the beginning and erase remaining data
01373              * at the original location. */
01374             if( 2 * (size_t) ret <= data_size )
01375             {
01376                 memcpy( data, data + data_size - ret, ret );
01377                 memset( data + data_size - ret, 0, ret );
01378             }
01379             else if( (size_t) ret < data_size )
01380             {
01381                 memmove( data, data + data_size - ret, ret );
01382                 memset( data + ret, 0, data_size - ret );
01383             }
01384             *data_length = ret;
01385             return( PSA_SUCCESS );
01386         }
01387         else
01388 #endif /* defined(MBEDTLS_PK_WRITE_C) */
01389         {
01390             /* This shouldn't happen in the reference implementation, but
01391                it is valid for a special-purpose implementation to omit
01392                support for exporting certain key types. */
01393             return( PSA_ERROR_NOT_SUPPORTED );
01394         }
01395     }
01396 }
01397 
01398 psa_status_t psa_export_key( psa_key_handle_t handle,
01399                              uint8_t *data,
01400                              size_t data_size,
01401                              size_t *data_length )
01402 {
01403     psa_key_slot_t *slot;
01404     psa_status_t status;
01405 
01406     /* Set the key to empty now, so that even when there are errors, we always
01407      * set data_length to a value between 0 and data_size. On error, setting
01408      * the key to empty is a good choice because an empty key representation is
01409      * unlikely to be accepted anywhere. */
01410     *data_length = 0;
01411 
01412     /* Export requires the EXPORT flag. There is an exception for public keys,
01413      * which don't require any flag, but psa_get_key_from_slot takes
01414      * care of this. */
01415     status = psa_get_key_from_slot( handle, &slot, PSA_KEY_USAGE_EXPORT, 0 );
01416     if( status != PSA_SUCCESS )
01417         return( status );
01418     return( psa_internal_export_key( slot, data, data_size,
01419                                      data_length, 0 ) );
01420 }
01421 
01422 psa_status_t psa_export_public_key( psa_key_handle_t handle,
01423                                     uint8_t *data,
01424                                     size_t data_size,
01425                                     size_t *data_length )
01426 {
01427     psa_key_slot_t *slot;
01428     psa_status_t status;
01429 
01430     /* Set the key to empty now, so that even when there are errors, we always
01431      * set data_length to a value between 0 and data_size. On error, setting
01432      * the key to empty is a good choice because an empty key representation is
01433      * unlikely to be accepted anywhere. */
01434     *data_length = 0;
01435 
01436     /* Exporting a public key doesn't require a usage flag. */
01437     status = psa_get_key_from_slot( handle, &slot, 0, 0 );
01438     if( status != PSA_SUCCESS )
01439         return( status );
01440     return( psa_internal_export_key( slot, data, data_size,
01441                                      data_length, 1 ) );
01442 }
01443 
01444 #if defined(static_assert)
01445 static_assert( ( MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY & MBEDTLS_PSA_KA_MASK_DUAL_USE ) == 0,
01446                "One or more key attribute flag is listed as both external-only and dual-use" );
01447 static_assert( ( PSA_KA_MASK_INTERNAL_ONLY & MBEDTLS_PSA_KA_MASK_DUAL_USE ) == 0,
01448                "One or more key attribute flag is listed as both internal-only and dual-use" );
01449 static_assert( ( PSA_KA_MASK_INTERNAL_ONLY & MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY ) == 0,
01450                "One or more key attribute flag is listed as both internal-only and external-only" );
01451 #endif
01452 
01453 /** Validate that a key policy is internally well-formed.
01454  *
01455  * This function only rejects invalid policies. It does not validate the
01456  * consistency of the policy with respect to other attributes of the key
01457  * such as the key type.
01458  */
01459 static psa_status_t psa_validate_key_policy( const psa_key_policy_t *policy )
01460 {
01461     if( ( policy->usage & ~( PSA_KEY_USAGE_EXPORT |
01462                              PSA_KEY_USAGE_COPY |
01463                              PSA_KEY_USAGE_ENCRYPT |
01464                              PSA_KEY_USAGE_DECRYPT |
01465                              PSA_KEY_USAGE_SIGN |
01466                              PSA_KEY_USAGE_VERIFY |
01467                              PSA_KEY_USAGE_DERIVE ) ) != 0 )
01468         return( PSA_ERROR_INVALID_ARGUMENT );
01469 
01470     return( PSA_SUCCESS );
01471 }
01472 
01473 /** Validate the internal consistency of key attributes.
01474  *
01475  * This function only rejects invalid attribute values. If does not
01476  * validate the consistency of the attributes with any key data that may
01477  * be involved in the creation of the key.
01478  *
01479  * Call this function early in the key creation process.
01480  *
01481  * \param[in] attributes    Key attributes for the new key.
01482  * \param[out] p_drv        On any return, the driver for the key, if any.
01483  *                          NULL for a transparent key.
01484  *
01485  */
01486 static psa_status_t psa_validate_key_attributes(
01487     const psa_key_attributes_t *attributes,
01488     psa_se_drv_table_entry_t **p_drv )
01489 {
01490     psa_status_t status;
01491 
01492     if( attributes->core.lifetime != PSA_KEY_LIFETIME_VOLATILE )
01493     {
01494         status = psa_validate_persistent_key_parameters(
01495             attributes->core.lifetime, attributes->core.id,
01496             p_drv, 1 );
01497         if( status != PSA_SUCCESS )
01498             return( status );
01499     }
01500 
01501     status = psa_validate_key_policy( &attributes->core.policy );
01502     if( status != PSA_SUCCESS )
01503         return( status );
01504 
01505     /* Refuse to create overly large keys.
01506      * Note that this doesn't trigger on import if the attributes don't
01507      * explicitly specify a size (so psa_get_key_bits returns 0), so
01508      * psa_import_key() needs its own checks. */
01509     if( psa_get_key_bits( attributes ) > PSA_MAX_KEY_BITS )
01510         return( PSA_ERROR_NOT_SUPPORTED );
01511 
01512     /* Reject invalid flags. These should not be reachable through the API. */
01513     if( attributes->core.flags & ~ ( MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY |
01514                                      MBEDTLS_PSA_KA_MASK_DUAL_USE ) )
01515         return( PSA_ERROR_INVALID_ARGUMENT );
01516 
01517     return( PSA_SUCCESS );
01518 }
01519 
01520 /** Prepare a key slot to receive key material.
01521  *
01522  * This function allocates a key slot and sets its metadata.
01523  *
01524  * If this function fails, call psa_fail_key_creation().
01525  *
01526  * This function is intended to be used as follows:
01527  * -# Call psa_start_key_creation() to allocate a key slot, prepare
01528  *    it with the specified attributes, and assign it a handle.
01529  * -# Populate the slot with the key material.
01530  * -# Call psa_finish_key_creation() to finalize the creation of the slot.
01531  * In case of failure at any step, stop the sequence and call
01532  * psa_fail_key_creation().
01533  *
01534  * \param method            An identification of the calling function.
01535  * \param[in] attributes    Key attributes for the new key.
01536  * \param[out] handle       On success, a handle for the allocated slot.
01537  * \param[out] p_slot       On success, a pointer to the prepared slot.
01538  * \param[out] p_drv        On any return, the driver for the key, if any.
01539  *                          NULL for a transparent key.
01540  *
01541  * \retval #PSA_SUCCESS
01542  *         The key slot is ready to receive key material.
01543  * \return If this function fails, the key slot is an invalid state.
01544  *         You must call psa_fail_key_creation() to wipe and free the slot.
01545  */
01546 static psa_status_t psa_start_key_creation(
01547     psa_key_creation_method_t method,
01548     const psa_key_attributes_t *attributes,
01549     psa_key_handle_t *handle,
01550     psa_key_slot_t **p_slot,
01551     psa_se_drv_table_entry_t **p_drv )
01552 {
01553     psa_status_t status;
01554     psa_key_slot_t *slot;
01555 
01556     (void) method;
01557     *p_drv = NULL;
01558 
01559     status = psa_validate_key_attributes( attributes, p_drv );
01560     if( status != PSA_SUCCESS )
01561         return( status );
01562 
01563     status = psa_get_empty_key_slot( handle, p_slot );
01564     if( status != PSA_SUCCESS )
01565         return( status );
01566     slot = *p_slot;
01567 
01568     /* We're storing the declared bit-size of the key. It's up to each
01569      * creation mechanism to verify that this information is correct.
01570      * It's automatically correct for mechanisms that use the bit-size as
01571      * an input (generate, device) but not for those where the bit-size
01572      * is optional (import, copy). */
01573 
01574     slot->attr = attributes->core;
01575 
01576     /* Erase external-only flags from the internal copy. To access
01577      * external-only flags, query `attributes`. Thanks to the check
01578      * in psa_validate_key_attributes(), this leaves the dual-use
01579      * flags and any internal flag that psa_get_empty_key_slot()
01580      * may have set. */
01581     slot->attr.flags &= ~MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY;
01582 
01583 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
01584     /* For a key in a secure element, we need to do three things
01585      * when creating or registering a key:
01586      * create the key file in internal storage, create the
01587      * key inside the secure element, and update the driver's
01588      * persistent data. Start a transaction that will encompass these
01589      * three actions. */
01590     /* The first thing to do is to find a slot number for the new key.
01591      * We save the slot number in persistent storage as part of the
01592      * transaction data. It will be needed to recover if the power
01593      * fails during the key creation process, to clean up on the secure
01594      * element side after restarting. Obtaining a slot number from the
01595      * secure element driver updates its persistent state, but we do not yet
01596      * save the driver's persistent state, so that if the power fails,
01597      * we can roll back to a state where the key doesn't exist. */
01598     if( *p_drv != NULL )
01599     {
01600         status = psa_find_se_slot_for_key( attributes, method, *p_drv,
01601                                            &slot->data.se.slot_number );
01602         if( status != PSA_SUCCESS )
01603             return( status );
01604         psa_crypto_prepare_transaction( PSA_CRYPTO_TRANSACTION_CREATE_KEY );
01605         psa_crypto_transaction.key.lifetime = slot->attr.lifetime;
01606         psa_crypto_transaction.key.slot = slot->data.se.slot_number;
01607         psa_crypto_transaction.key.id = slot->attr.id;
01608         status = psa_crypto_save_transaction( );
01609         if( status != PSA_SUCCESS )
01610         {
01611             (void) psa_crypto_stop_transaction( );
01612             return( status );
01613         }
01614     }
01615 
01616     if( *p_drv == NULL && method == PSA_KEY_CREATION_REGISTER )
01617     {
01618         /* Key registration only makes sense with a secure element. */
01619         return( PSA_ERROR_INVALID_ARGUMENT );
01620     }
01621 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
01622 
01623     return( status );
01624 }
01625 
01626 /** Finalize the creation of a key once its key material has been set.
01627  *
01628  * This entails writing the key to persistent storage.
01629  *
01630  * If this function fails, call psa_fail_key_creation().
01631  * See the documentation of psa_start_key_creation() for the intended use
01632  * of this function.
01633  *
01634  * \param[in,out] slot  Pointer to the slot with key material.
01635  * \param[in] driver    The secure element driver for the key,
01636  *                      or NULL for a transparent key.
01637  *
01638  * \retval #PSA_SUCCESS
01639  *         The key was successfully created. The handle is now valid.
01640  * \return If this function fails, the key slot is an invalid state.
01641  *         You must call psa_fail_key_creation() to wipe and free the slot.
01642  */
01643 static psa_status_t psa_finish_key_creation(
01644     psa_key_slot_t *slot,
01645     psa_se_drv_table_entry_t *driver )
01646 {
01647     psa_status_t status = PSA_SUCCESS;
01648     (void) slot;
01649     (void) driver;
01650 
01651 #if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C)
01652     if( slot->attr.lifetime != PSA_KEY_LIFETIME_VOLATILE )
01653     {
01654 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
01655         if( driver != NULL )
01656         {
01657             psa_se_key_data_storage_t data;
01658 #if defined(static_assert)
01659             static_assert( sizeof( slot->data.se.slot_number ) ==
01660                            sizeof( data.slot_number ),
01661                            "Slot number size does not match psa_se_key_data_storage_t" );
01662             static_assert( sizeof( slot->attr.bits ) == sizeof( data.bits ),
01663                            "Bit-size size does not match psa_se_key_data_storage_t" );
01664 #endif
01665             memcpy( &data.slot_number, &slot->data.se.slot_number,
01666                     sizeof( slot->data.se.slot_number ) );
01667             memcpy( &data.bits, &slot->attr.bits,
01668                     sizeof( slot->attr.bits ) );
01669             status = psa_save_persistent_key( &slot->attr,
01670                                               (uint8_t*) &data,
01671                                               sizeof( data ) );
01672         }
01673         else
01674 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
01675         {
01676             size_t buffer_size =
01677                 PSA_KEY_EXPORT_MAX_SIZE( slot->attr.type,
01678                                          slot->attr.bits );
01679             uint8_t *buffer = mbedtls_calloc( 1, buffer_size );
01680             size_t length = 0;
01681             if( buffer == NULL )
01682                 return( PSA_ERROR_INSUFFICIENT_MEMORY );
01683             status = psa_internal_export_key( slot,
01684                                               buffer, buffer_size, &length,
01685                                               0 );
01686             if( status == PSA_SUCCESS )
01687                 status = psa_save_persistent_key( &slot->attr,
01688                                                   buffer, length );
01689 
01690             mbedtls_platform_zeroize( buffer, buffer_size );
01691             mbedtls_free( buffer );
01692         }
01693     }
01694 #endif /* defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) */
01695 
01696 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
01697     /* Finish the transaction for a key creation. This does not
01698      * happen when registering an existing key. Detect this case
01699      * by checking whether a transaction is in progress (actual
01700      * creation of a key in a secure element requires a transaction,
01701      * but registration doesn't use one). */
01702     if( driver != NULL &&
01703         psa_crypto_transaction.unknown.type == PSA_CRYPTO_TRANSACTION_CREATE_KEY )
01704     {
01705         status = psa_save_se_persistent_data( driver );
01706         if( status != PSA_SUCCESS )
01707         {
01708             psa_destroy_persistent_key( slot->attr.id );
01709             return( status );
01710         }
01711         status = psa_crypto_stop_transaction( );
01712         if( status != PSA_SUCCESS )
01713             return( status );
01714     }
01715 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
01716 
01717     return( status );
01718 }
01719 
01720 /** Abort the creation of a key.
01721  *
01722  * You may call this function after calling psa_start_key_creation(),
01723  * or after psa_finish_key_creation() fails. In other circumstances, this
01724  * function may not clean up persistent storage.
01725  * See the documentation of psa_start_key_creation() for the intended use
01726  * of this function.
01727  *
01728  * \param[in,out] slot  Pointer to the slot with key material.
01729  * \param[in] driver    The secure element driver for the key,
01730  *                      or NULL for a transparent key.
01731  */
01732 static void psa_fail_key_creation( psa_key_slot_t *slot,
01733                                    psa_se_drv_table_entry_t *driver )
01734 {
01735     (void) driver;
01736 
01737     if( slot == NULL )
01738         return;
01739 
01740 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
01741     /* TODO: If the key has already been created in the secure
01742      * element, and the failure happened later (when saving metadata
01743      * to internal storage), we need to destroy the key in the secure
01744      * element.
01745      * https://github.com/ARMmbed/mbed-crypto/issues/217
01746      */
01747 
01748     /* Abort the ongoing transaction if any (there may not be one if
01749      * the creation process failed before starting one, or if the
01750      * key creation is a registration of a key in a secure element).
01751      * Earlier functions must already have done what it takes to undo any
01752      * partial creation. All that's left is to update the transaction data
01753      * itself. */
01754     (void) psa_crypto_stop_transaction( );
01755 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
01756 
01757     psa_wipe_key_slot( slot );
01758 }
01759 
01760 /** Validate optional attributes during key creation.
01761  *
01762  * Some key attributes are optional during key creation. If they are
01763  * specified in the attributes structure, check that they are consistent
01764  * with the data in the slot.
01765  *
01766  * This function should be called near the end of key creation, after
01767  * the slot in memory is fully populated but before saving persistent data.
01768  */
01769 static psa_status_t psa_validate_optional_attributes(
01770     const psa_key_slot_t *slot,
01771     const psa_key_attributes_t *attributes )
01772 {
01773     if( attributes->core.type != 0 )
01774     {
01775         if( attributes->core.type != slot->attr.type )
01776             return( PSA_ERROR_INVALID_ARGUMENT );
01777     }
01778 
01779     if( attributes->domain_parameters_size != 0 )
01780     {
01781 #if defined(MBEDTLS_RSA_C)
01782         if( PSA_KEY_TYPE_IS_RSA( slot->attr.type ) )
01783         {
01784             mbedtls_mpi actual, required;
01785             int ret;
01786             mbedtls_mpi_init( &actual );
01787             mbedtls_mpi_init( &required );
01788             ret = mbedtls_rsa_export( slot->data.rsa,
01789                                       NULL, NULL, NULL, NULL, &actual );
01790             if( ret != 0 )
01791                 goto rsa_exit;
01792             ret = mbedtls_mpi_read_binary( &required,
01793                                            attributes->domain_parameters,
01794                                            attributes->domain_parameters_size );
01795             if( ret != 0 )
01796                 goto rsa_exit;
01797             if( mbedtls_mpi_cmp_mpi( &actual, &required ) != 0 )
01798                 ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
01799         rsa_exit:
01800             mbedtls_mpi_free( &actual );
01801             mbedtls_mpi_free( &required );
01802             if( ret != 0)
01803                 return( mbedtls_to_psa_error( ret ) );
01804         }
01805         else
01806 #endif
01807         {
01808             return( PSA_ERROR_INVALID_ARGUMENT );
01809         }
01810     }
01811 
01812     if( attributes->core.bits != 0 )
01813     {
01814         if( attributes->core.bits != slot->attr.bits )
01815             return( PSA_ERROR_INVALID_ARGUMENT );
01816     }
01817 
01818     return( PSA_SUCCESS );
01819 }
01820 
01821 psa_status_t psa_import_key( const psa_key_attributes_t *attributes,
01822                              const uint8_t *data,
01823                              size_t data_length,
01824                              psa_key_handle_t *handle )
01825 {
01826     psa_status_t status;
01827     psa_key_slot_t *slot = NULL;
01828     psa_se_drv_table_entry_t *driver = NULL;
01829 
01830     /* Reject zero-length symmetric keys (including raw data key objects).
01831      * This also rejects any key which might be encoded as an empty string,
01832      * which is never valid. */
01833     if( data_length == 0 )
01834         return( PSA_ERROR_INVALID_ARGUMENT );
01835 
01836     status = psa_start_key_creation( PSA_KEY_CREATION_IMPORT, attributes,
01837                                      handle, &slot, &driver );
01838     if( status != PSA_SUCCESS )
01839         goto exit;
01840 
01841 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
01842     if( driver != NULL )
01843     {
01844         const psa_drv_se_t *drv = psa_get_se_driver_methods( driver );
01845         /* The driver should set the number of key bits, however in
01846          * case it doesn't, we initialize bits to an invalid value. */
01847         size_t bits = PSA_MAX_KEY_BITS + 1;
01848         if( drv->key_management == NULL ||
01849             drv->key_management->p_import == NULL )
01850         {
01851             status = PSA_ERROR_NOT_SUPPORTED;
01852             goto exit;
01853         }
01854         status = drv->key_management->p_import(
01855             psa_get_se_driver_context( driver ),
01856             slot->data.se.slot_number, attributes, data, data_length,
01857             &bits );
01858         if( status != PSA_SUCCESS )
01859             goto exit;
01860         if( bits > PSA_MAX_KEY_BITS )
01861         {
01862             status = PSA_ERROR_NOT_SUPPORTED;
01863             goto exit;
01864         }
01865         slot->attr.bits = (psa_key_bits_t) bits;
01866     }
01867     else
01868 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
01869     {
01870         status = psa_import_key_into_slot( slot, data, data_length );
01871         if( status != PSA_SUCCESS )
01872             goto exit;
01873     }
01874     status = psa_validate_optional_attributes( slot, attributes );
01875     if( status != PSA_SUCCESS )
01876         goto exit;
01877 
01878     status = psa_finish_key_creation( slot, driver );
01879 exit:
01880     if( status != PSA_SUCCESS )
01881     {
01882         psa_fail_key_creation( slot, driver );
01883         *handle = 0;
01884     }
01885     return( status );
01886 }
01887 
01888 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
01889 psa_status_t mbedtls_psa_register_se_key(
01890     const psa_key_attributes_t *attributes )
01891 {
01892     psa_status_t status;
01893     psa_key_slot_t *slot = NULL;
01894     psa_se_drv_table_entry_t *driver = NULL;
01895     psa_key_handle_t handle = 0;
01896 
01897     /* Leaving attributes unspecified is not currently supported.
01898      * It could make sense to query the key type and size from the
01899      * secure element, but not all secure elements support this
01900      * and the driver HAL doesn't currently support it. */
01901     if( psa_get_key_type( attributes ) == PSA_KEY_TYPE_NONE )
01902         return( PSA_ERROR_NOT_SUPPORTED );
01903     if( psa_get_key_bits( attributes ) == 0 )
01904         return( PSA_ERROR_NOT_SUPPORTED );
01905 
01906     status = psa_start_key_creation( PSA_KEY_CREATION_REGISTER, attributes,
01907                                      &handle, &slot, &driver );
01908     if( status != PSA_SUCCESS )
01909         goto exit;
01910 
01911     status = psa_finish_key_creation( slot, driver );
01912 
01913 exit:
01914     if( status != PSA_SUCCESS )
01915     {
01916         psa_fail_key_creation( slot, driver );
01917     }
01918     /* Registration doesn't keep the key in RAM. */
01919     psa_close_key( handle );
01920     return( status );
01921 }
01922 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
01923 
01924 static psa_status_t psa_copy_key_material( const psa_key_slot_t *source,
01925                                            psa_key_slot_t *target )
01926 {
01927     psa_status_t status;
01928     uint8_t *buffer = NULL;
01929     size_t buffer_size = 0;
01930     size_t length;
01931 
01932     buffer_size = PSA_KEY_EXPORT_MAX_SIZE( source->attr.type,
01933                                            psa_get_key_slot_bits( source ) );
01934     buffer = mbedtls_calloc( 1, buffer_size );
01935     if( buffer == NULL )
01936         return( PSA_ERROR_INSUFFICIENT_MEMORY );
01937     status = psa_internal_export_key( source, buffer, buffer_size, &length, 0 );
01938     if( status != PSA_SUCCESS )
01939         goto exit;
01940     target->attr.type = source->attr.type;
01941     status = psa_import_key_into_slot( target, buffer, length );
01942 
01943 exit:
01944     mbedtls_platform_zeroize( buffer, buffer_size );
01945     mbedtls_free( buffer );
01946     return( status );
01947 }
01948 
01949 psa_status_t psa_copy_key( psa_key_handle_t source_handle,
01950                            const psa_key_attributes_t *specified_attributes,
01951                            psa_key_handle_t *target_handle )
01952 {
01953     psa_status_t status;
01954     psa_key_slot_t *source_slot = NULL;
01955     psa_key_slot_t *target_slot = NULL;
01956     psa_key_attributes_t actual_attributes = *specified_attributes;
01957     psa_se_drv_table_entry_t *driver = NULL;
01958 
01959     status = psa_get_transparent_key( source_handle, &source_slot,
01960                                       PSA_KEY_USAGE_COPY, 0 );
01961     if( status != PSA_SUCCESS )
01962         goto exit;
01963 
01964     status = psa_validate_optional_attributes( source_slot,
01965                                                specified_attributes );
01966     if( status != PSA_SUCCESS )
01967         goto exit;
01968 
01969     status = psa_restrict_key_policy( &actual_attributes.core.policy,
01970                                       &source_slot->attr.policy );
01971     if( status != PSA_SUCCESS )
01972         goto exit;
01973 
01974     status = psa_start_key_creation( PSA_KEY_CREATION_COPY,
01975                                      &actual_attributes,
01976                                      target_handle, &target_slot, &driver );
01977     if( status != PSA_SUCCESS )
01978         goto exit;
01979 
01980 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
01981     if( driver != NULL )
01982     {
01983         /* Copying to a secure element is not implemented yet. */
01984         status = PSA_ERROR_NOT_SUPPORTED;
01985         goto exit;
01986     }
01987 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
01988 
01989     status = psa_copy_key_material( source_slot, target_slot );
01990     if( status != PSA_SUCCESS )
01991         goto exit;
01992 
01993     status = psa_finish_key_creation( target_slot, driver );
01994 exit:
01995     if( status != PSA_SUCCESS )
01996     {
01997         psa_fail_key_creation( target_slot, driver );
01998         *target_handle = 0;
01999     }
02000     return( status );
02001 }
02002 
02003 
02004 
02005 /****************************************************************/
02006 /* Message digests */
02007 /****************************************************************/
02008 
02009 static const mbedtls_md_info_t *mbedtls_md_info_from_psa( psa_algorithm_t alg )
02010 {
02011     switch( alg )
02012     {
02013 #if defined(MBEDTLS_MD2_C)
02014         case PSA_ALG_MD2:
02015             return( &mbedtls_md2_info );
02016 #endif
02017 #if defined(MBEDTLS_MD4_C)
02018         case PSA_ALG_MD4:
02019             return( &mbedtls_md4_info );
02020 #endif
02021 #if defined(MBEDTLS_MD5_C)
02022         case PSA_ALG_MD5:
02023             return( &mbedtls_md5_info );
02024 #endif
02025 #if defined(MBEDTLS_RIPEMD160_C)
02026         case PSA_ALG_RIPEMD160:
02027             return( &mbedtls_ripemd160_info );
02028 #endif
02029 #if defined(MBEDTLS_SHA1_C)
02030         case PSA_ALG_SHA_1:
02031             return( &mbedtls_sha1_info );
02032 #endif
02033 #if defined(MBEDTLS_SHA256_C)
02034         case PSA_ALG_SHA_224:
02035             return( &mbedtls_sha224_info );
02036         case PSA_ALG_SHA_256:
02037             return( &mbedtls_sha256_info );
02038 #endif
02039 #if defined(MBEDTLS_SHA512_C)
02040         case PSA_ALG_SHA_384:
02041             return( &mbedtls_sha384_info );
02042         case PSA_ALG_SHA_512:
02043             return( &mbedtls_sha512_info );
02044 #endif
02045         default:
02046             return( NULL );
02047     }
02048 }
02049 
02050 psa_status_t psa_hash_abort( psa_hash_operation_t *operation )
02051 {
02052     switch( operation->alg )
02053     {
02054         case 0:
02055             /* The object has (apparently) been initialized but it is not
02056              * in use. It's ok to call abort on such an object, and there's
02057              * nothing to do. */
02058             break;
02059 #if defined(MBEDTLS_MD2_C)
02060         case PSA_ALG_MD2:
02061             mbedtls_md2_free( &operation->ctx.md2 );
02062             break;
02063 #endif
02064 #if defined(MBEDTLS_MD4_C)
02065         case PSA_ALG_MD4:
02066             mbedtls_md4_free( &operation->ctx.md4 );
02067             break;
02068 #endif
02069 #if defined(MBEDTLS_MD5_C)
02070         case PSA_ALG_MD5:
02071             mbedtls_md5_free( &operation->ctx.md5 );
02072             break;
02073 #endif
02074 #if defined(MBEDTLS_RIPEMD160_C)
02075         case PSA_ALG_RIPEMD160:
02076             mbedtls_ripemd160_free( &operation->ctx.ripemd160 );
02077             break;
02078 #endif
02079 #if defined(MBEDTLS_SHA1_C)
02080         case PSA_ALG_SHA_1:
02081             mbedtls_sha1_free( &operation->ctx.sha1 );
02082             break;
02083 #endif
02084 #if defined(MBEDTLS_SHA256_C)
02085         case PSA_ALG_SHA_224:
02086         case PSA_ALG_SHA_256:
02087             mbedtls_sha256_free( &operation->ctx.sha256 );
02088             break;
02089 #endif
02090 #if defined(MBEDTLS_SHA512_C)
02091         case PSA_ALG_SHA_384:
02092         case PSA_ALG_SHA_512:
02093             mbedtls_sha512_free( &operation->ctx.sha512 );
02094             break;
02095 #endif
02096         default:
02097             return( PSA_ERROR_BAD_STATE );
02098     }
02099     operation->alg = 0;
02100     return( PSA_SUCCESS );
02101 }
02102 
02103 psa_status_t psa_hash_setup( psa_hash_operation_t *operation,
02104                              psa_algorithm_t alg )
02105 {
02106     int ret;
02107 
02108     /* A context must be freshly initialized before it can be set up. */
02109     if( operation->alg != 0 )
02110     {
02111         return( PSA_ERROR_BAD_STATE );
02112     }
02113 
02114     switch( alg )
02115     {
02116 #if defined(MBEDTLS_MD2_C)
02117         case PSA_ALG_MD2:
02118             mbedtls_md2_init( &operation->ctx.md2 );
02119             ret = mbedtls_md2_starts_ret( &operation->ctx.md2 );
02120             break;
02121 #endif
02122 #if defined(MBEDTLS_MD4_C)
02123         case PSA_ALG_MD4:
02124             mbedtls_md4_init( &operation->ctx.md4 );
02125             ret = mbedtls_md4_starts_ret( &operation->ctx.md4 );
02126             break;
02127 #endif
02128 #if defined(MBEDTLS_MD5_C)
02129         case PSA_ALG_MD5:
02130             mbedtls_md5_init( &operation->ctx.md5 );
02131             ret = mbedtls_md5_starts_ret( &operation->ctx.md5 );
02132             break;
02133 #endif
02134 #if defined(MBEDTLS_RIPEMD160_C)
02135         case PSA_ALG_RIPEMD160:
02136             mbedtls_ripemd160_init( &operation->ctx.ripemd160 );
02137             ret = mbedtls_ripemd160_starts_ret( &operation->ctx.ripemd160 );
02138             break;
02139 #endif
02140 #if defined(MBEDTLS_SHA1_C)
02141         case PSA_ALG_SHA_1:
02142             mbedtls_sha1_init( &operation->ctx.sha1 );
02143             ret = mbedtls_sha1_starts_ret( &operation->ctx.sha1 );
02144             break;
02145 #endif
02146 #if defined(MBEDTLS_SHA256_C)
02147         case PSA_ALG_SHA_224:
02148             mbedtls_sha256_init( &operation->ctx.sha256 );
02149             ret = mbedtls_sha256_starts_ret( &operation->ctx.sha256, 1 );
02150             break;
02151         case PSA_ALG_SHA_256:
02152             mbedtls_sha256_init( &operation->ctx.sha256 );
02153             ret = mbedtls_sha256_starts_ret( &operation->ctx.sha256, 0 );
02154             break;
02155 #endif
02156 #if defined(MBEDTLS_SHA512_C)
02157         case PSA_ALG_SHA_384:
02158             mbedtls_sha512_init( &operation->ctx.sha512 );
02159             ret = mbedtls_sha512_starts_ret( &operation->ctx.sha512, 1 );
02160             break;
02161         case PSA_ALG_SHA_512:
02162             mbedtls_sha512_init( &operation->ctx.sha512 );
02163             ret = mbedtls_sha512_starts_ret( &operation->ctx.sha512, 0 );
02164             break;
02165 #endif
02166         default:
02167             return( PSA_ALG_IS_HASH( alg ) ?
02168                     PSA_ERROR_NOT_SUPPORTED :
02169                     PSA_ERROR_INVALID_ARGUMENT );
02170     }
02171     if( ret == 0 )
02172         operation->alg = alg;
02173     else
02174         psa_hash_abort( operation );
02175     return( mbedtls_to_psa_error( ret ) );
02176 }
02177 
02178 psa_status_t psa_hash_update( psa_hash_operation_t *operation,
02179                               const uint8_t *input,
02180                               size_t input_length )
02181 {
02182     int ret;
02183 
02184     /* Don't require hash implementations to behave correctly on a
02185      * zero-length input, which may have an invalid pointer. */
02186     if( input_length == 0 )
02187         return( PSA_SUCCESS );
02188 
02189     switch( operation->alg )
02190     {
02191 #if defined(MBEDTLS_MD2_C)
02192         case PSA_ALG_MD2:
02193             ret = mbedtls_md2_update_ret( &operation->ctx.md2,
02194                                           input, input_length );
02195             break;
02196 #endif
02197 #if defined(MBEDTLS_MD4_C)
02198         case PSA_ALG_MD4:
02199             ret = mbedtls_md4_update_ret( &operation->ctx.md4,
02200                                           input, input_length );
02201             break;
02202 #endif
02203 #if defined(MBEDTLS_MD5_C)
02204         case PSA_ALG_MD5:
02205             ret = mbedtls_md5_update_ret( &operation->ctx.md5,
02206                                           input, input_length );
02207             break;
02208 #endif
02209 #if defined(MBEDTLS_RIPEMD160_C)
02210         case PSA_ALG_RIPEMD160:
02211             ret = mbedtls_ripemd160_update_ret( &operation->ctx.ripemd160,
02212                                                 input, input_length );
02213             break;
02214 #endif
02215 #if defined(MBEDTLS_SHA1_C)
02216         case PSA_ALG_SHA_1:
02217             ret = mbedtls_sha1_update_ret( &operation->ctx.sha1,
02218                                            input, input_length );
02219             break;
02220 #endif
02221 #if defined(MBEDTLS_SHA256_C)
02222         case PSA_ALG_SHA_224:
02223         case PSA_ALG_SHA_256:
02224             ret = mbedtls_sha256_update_ret( &operation->ctx.sha256,
02225                                              input, input_length );
02226             break;
02227 #endif
02228 #if defined(MBEDTLS_SHA512_C)
02229         case PSA_ALG_SHA_384:
02230         case PSA_ALG_SHA_512:
02231             ret = mbedtls_sha512_update_ret( &operation->ctx.sha512,
02232                                              input, input_length );
02233             break;
02234 #endif
02235         default:
02236             return( PSA_ERROR_BAD_STATE );
02237     }
02238 
02239     if( ret != 0 )
02240         psa_hash_abort( operation );
02241     return( mbedtls_to_psa_error( ret ) );
02242 }
02243 
02244 psa_status_t psa_hash_finish( psa_hash_operation_t *operation,
02245                               uint8_t *hash,
02246                               size_t hash_size,
02247                               size_t *hash_length )
02248 {
02249     psa_status_t status;
02250     int ret;
02251     size_t actual_hash_length = PSA_HASH_SIZE( operation->alg );
02252 
02253     /* Fill the output buffer with something that isn't a valid hash
02254      * (barring an attack on the hash and deliberately-crafted input),
02255      * in case the caller doesn't check the return status properly. */
02256     *hash_length = hash_size;
02257     /* If hash_size is 0 then hash may be NULL and then the
02258      * call to memset would have undefined behavior. */
02259     if( hash_size != 0 )
02260         memset( hash, '!', hash_size );
02261 
02262     if( hash_size < actual_hash_length )
02263     {
02264         status = PSA_ERROR_BUFFER_TOO_SMALL;
02265         goto exit;
02266     }
02267 
02268     switch( operation->alg )
02269     {
02270 #if defined(MBEDTLS_MD2_C)
02271         case PSA_ALG_MD2:
02272             ret = mbedtls_md2_finish_ret( &operation->ctx.md2, hash );
02273             break;
02274 #endif
02275 #if defined(MBEDTLS_MD4_C)
02276         case PSA_ALG_MD4:
02277             ret = mbedtls_md4_finish_ret( &operation->ctx.md4, hash );
02278             break;
02279 #endif
02280 #if defined(MBEDTLS_MD5_C)
02281         case PSA_ALG_MD5:
02282             ret = mbedtls_md5_finish_ret( &operation->ctx.md5, hash );
02283             break;
02284 #endif
02285 #if defined(MBEDTLS_RIPEMD160_C)
02286         case PSA_ALG_RIPEMD160:
02287             ret = mbedtls_ripemd160_finish_ret( &operation->ctx.ripemd160, hash );
02288             break;
02289 #endif
02290 #if defined(MBEDTLS_SHA1_C)
02291         case PSA_ALG_SHA_1:
02292             ret = mbedtls_sha1_finish_ret( &operation->ctx.sha1, hash );
02293             break;
02294 #endif
02295 #if defined(MBEDTLS_SHA256_C)
02296         case PSA_ALG_SHA_224:
02297         case PSA_ALG_SHA_256:
02298             ret = mbedtls_sha256_finish_ret( &operation->ctx.sha256, hash );
02299             break;
02300 #endif
02301 #if defined(MBEDTLS_SHA512_C)
02302         case PSA_ALG_SHA_384:
02303         case PSA_ALG_SHA_512:
02304             ret = mbedtls_sha512_finish_ret( &operation->ctx.sha512, hash );
02305             break;
02306 #endif
02307         default:
02308             return( PSA_ERROR_BAD_STATE );
02309     }
02310     status = mbedtls_to_psa_error( ret );
02311 
02312 exit:
02313     if( status == PSA_SUCCESS )
02314     {
02315         *hash_length = actual_hash_length;
02316         return( psa_hash_abort( operation ) );
02317     }
02318     else
02319     {
02320         psa_hash_abort( operation );
02321         return( status );
02322     }
02323 }
02324 
02325 psa_status_t psa_hash_verify( psa_hash_operation_t *operation,
02326                               const uint8_t *hash,
02327                               size_t hash_length )
02328 {
02329     uint8_t actual_hash[MBEDTLS_MD_MAX_SIZE];
02330     size_t actual_hash_length;
02331     psa_status_t status = psa_hash_finish( operation,
02332                                            actual_hash, sizeof( actual_hash ),
02333                                            &actual_hash_length );
02334     if( status != PSA_SUCCESS )
02335         return( status );
02336     if( actual_hash_length != hash_length )
02337         return( PSA_ERROR_INVALID_SIGNATURE );
02338     if( safer_memcmp( hash, actual_hash, actual_hash_length ) != 0 )
02339         return( PSA_ERROR_INVALID_SIGNATURE );
02340     return( PSA_SUCCESS );
02341 }
02342 
02343 psa_status_t psa_hash_clone( const psa_hash_operation_t *source_operation,
02344                              psa_hash_operation_t *target_operation )
02345 {
02346     if( target_operation->alg != 0 )
02347         return( PSA_ERROR_BAD_STATE );
02348 
02349     switch( source_operation->alg )
02350     {
02351         case 0:
02352             return( PSA_ERROR_BAD_STATE );
02353 #if defined(MBEDTLS_MD2_C)
02354         case PSA_ALG_MD2:
02355             mbedtls_md2_clone( &target_operation->ctx.md2,
02356                                &source_operation->ctx.md2 );
02357             break;
02358 #endif
02359 #if defined(MBEDTLS_MD4_C)
02360         case PSA_ALG_MD4:
02361             mbedtls_md4_clone( &target_operation->ctx.md4,
02362                                &source_operation->ctx.md4 );
02363             break;
02364 #endif
02365 #if defined(MBEDTLS_MD5_C)
02366         case PSA_ALG_MD5:
02367             mbedtls_md5_clone( &target_operation->ctx.md5,
02368                                &source_operation->ctx.md5 );
02369             break;
02370 #endif
02371 #if defined(MBEDTLS_RIPEMD160_C)
02372         case PSA_ALG_RIPEMD160:
02373             mbedtls_ripemd160_clone( &target_operation->ctx.ripemd160,
02374                                      &source_operation->ctx.ripemd160 );
02375             break;
02376 #endif
02377 #if defined(MBEDTLS_SHA1_C)
02378         case PSA_ALG_SHA_1:
02379             mbedtls_sha1_clone( &target_operation->ctx.sha1,
02380                                 &source_operation->ctx.sha1 );
02381             break;
02382 #endif
02383 #if defined(MBEDTLS_SHA256_C)
02384         case PSA_ALG_SHA_224:
02385         case PSA_ALG_SHA_256:
02386             mbedtls_sha256_clone( &target_operation->ctx.sha256,
02387                                   &source_operation->ctx.sha256 );
02388             break;
02389 #endif
02390 #if defined(MBEDTLS_SHA512_C)
02391         case PSA_ALG_SHA_384:
02392         case PSA_ALG_SHA_512:
02393             mbedtls_sha512_clone( &target_operation->ctx.sha512,
02394                                   &source_operation->ctx.sha512 );
02395             break;
02396 #endif
02397         default:
02398             return( PSA_ERROR_NOT_SUPPORTED );
02399     }
02400 
02401     target_operation->alg = source_operation->alg;
02402     return( PSA_SUCCESS );
02403 }
02404 
02405 
02406 /****************************************************************/
02407 /* MAC */
02408 /****************************************************************/
02409 
02410 static const mbedtls_cipher_info_t *mbedtls_cipher_info_from_psa(
02411     psa_algorithm_t alg,
02412     psa_key_type_t key_type,
02413     size_t key_bits,
02414     mbedtls_cipher_id_t* cipher_id )
02415 {
02416     mbedtls_cipher_mode_t mode;
02417     mbedtls_cipher_id_t cipher_id_tmp;
02418 
02419     if( PSA_ALG_IS_AEAD( alg ) )
02420         alg = PSA_ALG_AEAD_WITH_TAG_LENGTH( alg, 0 );
02421 
02422     if( PSA_ALG_IS_CIPHER( alg ) || PSA_ALG_IS_AEAD( alg ) )
02423     {
02424         switch( alg )
02425         {
02426             case PSA_ALG_ARC4:
02427             case PSA_ALG_CHACHA20:
02428                 mode = MBEDTLS_MODE_STREAM;
02429                 break;
02430             case PSA_ALG_CTR:
02431                 mode = MBEDTLS_MODE_CTR;
02432                 break;
02433             case PSA_ALG_CFB:
02434                 mode = MBEDTLS_MODE_CFB;
02435                 break;
02436             case PSA_ALG_OFB:
02437                 mode = MBEDTLS_MODE_OFB;
02438                 break;
02439             case PSA_ALG_CBC_NO_PADDING:
02440                 mode = MBEDTLS_MODE_CBC;
02441                 break;
02442             case PSA_ALG_CBC_PKCS7:
02443                 mode = MBEDTLS_MODE_CBC;
02444                 break;
02445             case PSA_ALG_AEAD_WITH_TAG_LENGTH( PSA_ALG_CCM, 0 ):
02446                 mode = MBEDTLS_MODE_CCM;
02447                 break;
02448             case PSA_ALG_AEAD_WITH_TAG_LENGTH( PSA_ALG_GCM, 0 ):
02449                 mode = MBEDTLS_MODE_GCM;
02450                 break;
02451             case PSA_ALG_AEAD_WITH_TAG_LENGTH( PSA_ALG_CHACHA20_POLY1305, 0 ):
02452                 mode = MBEDTLS_MODE_CHACHAPOLY;
02453                 break;
02454             default:
02455                 return( NULL );
02456         }
02457     }
02458     else if( alg == PSA_ALG_CMAC )
02459         mode = MBEDTLS_MODE_ECB;
02460     else
02461         return( NULL );
02462 
02463     switch( key_type )
02464     {
02465         case PSA_KEY_TYPE_AES:
02466             cipher_id_tmp = MBEDTLS_CIPHER_ID_AES;
02467             break;
02468         case PSA_KEY_TYPE_DES:
02469             /* key_bits is 64 for Single-DES, 128 for two-key Triple-DES,
02470              * and 192 for three-key Triple-DES. */
02471             if( key_bits == 64 )
02472                 cipher_id_tmp = MBEDTLS_CIPHER_ID_DES;
02473             else
02474                 cipher_id_tmp = MBEDTLS_CIPHER_ID_3DES;
02475             /* mbedtls doesn't recognize two-key Triple-DES as an algorithm,
02476              * but two-key Triple-DES is functionally three-key Triple-DES
02477              * with K1=K3, so that's how we present it to mbedtls. */
02478             if( key_bits == 128 )
02479                 key_bits = 192;
02480             break;
02481         case PSA_KEY_TYPE_CAMELLIA:
02482             cipher_id_tmp = MBEDTLS_CIPHER_ID_CAMELLIA;
02483             break;
02484         case PSA_KEY_TYPE_ARC4:
02485             cipher_id_tmp = MBEDTLS_CIPHER_ID_ARC4;
02486             break;
02487         case PSA_KEY_TYPE_CHACHA20:
02488             cipher_id_tmp = MBEDTLS_CIPHER_ID_CHACHA20;
02489             break;
02490         default:
02491             return( NULL );
02492     }
02493     if( cipher_id != NULL )
02494         *cipher_id = cipher_id_tmp;
02495 
02496     return( mbedtls_cipher_info_from_values( cipher_id_tmp,
02497                                              (int) key_bits, mode ) );
02498 }
02499 
02500 #if defined(MBEDTLS_MD_C)
02501 static size_t psa_get_hash_block_size( psa_algorithm_t alg )
02502 {
02503     switch( alg )
02504     {
02505         case PSA_ALG_MD2:
02506             return( 16 );
02507         case PSA_ALG_MD4:
02508             return( 64 );
02509         case PSA_ALG_MD5:
02510             return( 64 );
02511         case PSA_ALG_RIPEMD160:
02512             return( 64 );
02513         case PSA_ALG_SHA_1:
02514             return( 64 );
02515         case PSA_ALG_SHA_224:
02516             return( 64 );
02517         case PSA_ALG_SHA_256:
02518             return( 64 );
02519         case PSA_ALG_SHA_384:
02520             return( 128 );
02521         case PSA_ALG_SHA_512:
02522             return( 128 );
02523         default:
02524             return( 0 );
02525     }
02526 }
02527 #endif /* MBEDTLS_MD_C */
02528 
02529 /* Initialize the MAC operation structure. Once this function has been
02530  * called, psa_mac_abort can run and will do the right thing. */
02531 static psa_status_t psa_mac_init( psa_mac_operation_t *operation,
02532                                   psa_algorithm_t alg )
02533 {
02534     psa_status_t status = PSA_ERROR_NOT_SUPPORTED;
02535 
02536     operation->alg = alg;
02537     operation->key_set = 0;
02538     operation->iv_set = 0;
02539     operation->iv_required = 0;
02540     operation->has_input = 0;
02541     operation->is_sign = 0;
02542 
02543 #if defined(MBEDTLS_CMAC_C)
02544     if( alg == PSA_ALG_CMAC )
02545     {
02546         operation->iv_required = 0;
02547         mbedtls_cipher_init( &operation->ctx.cmac );
02548         status = PSA_SUCCESS;
02549     }
02550     else
02551 #endif /* MBEDTLS_CMAC_C */
02552 #if defined(MBEDTLS_MD_C)
02553     if( PSA_ALG_IS_HMAC( operation->alg ) )
02554     {
02555         /* We'll set up the hash operation later in psa_hmac_setup_internal. */
02556         operation->ctx.hmac.hash_ctx.alg = 0;
02557         status = PSA_SUCCESS;
02558     }
02559     else
02560 #endif /* MBEDTLS_MD_C */
02561     {
02562         if( ! PSA_ALG_IS_MAC( alg ) )
02563             status = PSA_ERROR_INVALID_ARGUMENT;
02564     }
02565 
02566     if( status != PSA_SUCCESS )
02567         memset( operation, 0, sizeof( *operation ) );
02568     return( status );
02569 }
02570 
02571 #if defined(MBEDTLS_MD_C)
02572 static psa_status_t psa_hmac_abort_internal( psa_hmac_internal_data *hmac )
02573 {
02574     mbedtls_platform_zeroize( hmac->opad, sizeof( hmac->opad ) );
02575     return( psa_hash_abort( &hmac->hash_ctx ) );
02576 }
02577 #endif /* MBEDTLS_MD_C */
02578 
02579 psa_status_t psa_mac_abort( psa_mac_operation_t *operation )
02580 {
02581     if( operation->alg == 0 )
02582     {
02583         /* The object has (apparently) been initialized but it is not
02584          * in use. It's ok to call abort on such an object, and there's
02585          * nothing to do. */
02586         return( PSA_SUCCESS );
02587     }
02588     else
02589 #if defined(MBEDTLS_CMAC_C)
02590     if( operation->alg == PSA_ALG_CMAC )
02591     {
02592         mbedtls_cipher_free( &operation->ctx.cmac );
02593     }
02594     else
02595 #endif /* MBEDTLS_CMAC_C */
02596 #if defined(MBEDTLS_MD_C)
02597     if( PSA_ALG_IS_HMAC( operation->alg ) )
02598     {
02599         psa_hmac_abort_internal( &operation->ctx.hmac );
02600     }
02601     else
02602 #endif /* MBEDTLS_MD_C */
02603     {
02604         /* Sanity check (shouldn't happen: operation->alg should
02605          * always have been initialized to a valid value). */
02606         goto bad_state;
02607     }
02608 
02609     operation->alg = 0;
02610     operation->key_set = 0;
02611     operation->iv_set = 0;
02612     operation->iv_required = 0;
02613     operation->has_input = 0;
02614     operation->is_sign = 0;
02615 
02616     return( PSA_SUCCESS );
02617 
02618 bad_state:
02619     /* If abort is called on an uninitialized object, we can't trust
02620      * anything. Wipe the object in case it contains confidential data.
02621      * This may result in a memory leak if a pointer gets overwritten,
02622      * but it's too late to do anything about this. */
02623     memset( operation, 0, sizeof( *operation ) );
02624     return( PSA_ERROR_BAD_STATE );
02625 }
02626 
02627 #if defined(MBEDTLS_CMAC_C)
02628 static int psa_cmac_setup( psa_mac_operation_t *operation,
02629                            size_t key_bits,
02630                            psa_key_slot_t *slot,
02631                            const mbedtls_cipher_info_t *cipher_info )
02632 {
02633     int ret;
02634 
02635     operation->mac_size = cipher_info->block_size;
02636 
02637     ret = mbedtls_cipher_setup( &operation->ctx.cmac, cipher_info );
02638     if( ret != 0 )
02639         return( ret );
02640 
02641     ret = mbedtls_cipher_cmac_starts( &operation->ctx.cmac,
02642                                       slot->data.raw.data,
02643                                       key_bits );
02644     return( ret );
02645 }
02646 #endif /* MBEDTLS_CMAC_C */
02647 
02648 #if defined(MBEDTLS_MD_C)
02649 static psa_status_t psa_hmac_setup_internal( psa_hmac_internal_data *hmac,
02650                                              const uint8_t *key,
02651                                              size_t key_length,
02652                                              psa_algorithm_t hash_alg )
02653 {
02654     uint8_t ipad[PSA_HMAC_MAX_HASH_BLOCK_SIZE];
02655     size_t i;
02656     size_t hash_size = PSA_HASH_SIZE( hash_alg );
02657     size_t block_size = psa_get_hash_block_size( hash_alg );
02658     psa_status_t status;
02659 
02660     /* Sanity checks on block_size, to guarantee that there won't be a buffer
02661      * overflow below. This should never trigger if the hash algorithm
02662      * is implemented correctly. */
02663     /* The size checks against the ipad and opad buffers cannot be written
02664      * `block_size > sizeof( ipad ) || block_size > sizeof( hmac->opad )`
02665      * because that triggers -Wlogical-op on GCC 7.3. */
02666     if( block_size > sizeof( ipad ) )
02667         return( PSA_ERROR_NOT_SUPPORTED );
02668     if( block_size > sizeof( hmac->opad ) )
02669         return( PSA_ERROR_NOT_SUPPORTED );
02670     if( block_size < hash_size )
02671         return( PSA_ERROR_NOT_SUPPORTED );
02672 
02673     if( key_length > block_size )
02674     {
02675         status = psa_hash_setup( &hmac->hash_ctx, hash_alg );
02676         if( status != PSA_SUCCESS )
02677             goto cleanup;
02678         status = psa_hash_update( &hmac->hash_ctx, key, key_length );
02679         if( status != PSA_SUCCESS )
02680             goto cleanup;
02681         status = psa_hash_finish( &hmac->hash_ctx,
02682                                   ipad, sizeof( ipad ), &key_length );
02683         if( status != PSA_SUCCESS )
02684             goto cleanup;
02685     }
02686     /* A 0-length key is not commonly used in HMAC when used as a MAC,
02687      * but it is permitted. It is common when HMAC is used in HKDF, for
02688      * example. Don't call `memcpy` in the 0-length because `key` could be
02689      * an invalid pointer which would make the behavior undefined. */
02690     else if( key_length != 0 )
02691         memcpy( ipad, key, key_length );
02692 
02693     /* ipad contains the key followed by garbage. Xor and fill with 0x36
02694      * to create the ipad value. */
02695     for( i = 0; i < key_length; i++ )
02696         ipad[i] ^= 0x36;
02697     memset( ipad + key_length, 0x36, block_size - key_length );
02698 
02699     /* Copy the key material from ipad to opad, flipping the requisite bits,
02700      * and filling the rest of opad with the requisite constant. */
02701     for( i = 0; i < key_length; i++ )
02702         hmac->opad[i] = ipad[i] ^ 0x36 ^ 0x5C;
02703     memset( hmac->opad + key_length, 0x5C, block_size - key_length );
02704 
02705     status = psa_hash_setup( &hmac->hash_ctx, hash_alg );
02706     if( status != PSA_SUCCESS )
02707         goto cleanup;
02708 
02709     status = psa_hash_update( &hmac->hash_ctx, ipad, block_size );
02710 
02711 cleanup:
02712     mbedtls_platform_zeroize( ipad, sizeof(ipad) );
02713 
02714     return( status );
02715 }
02716 #endif /* MBEDTLS_MD_C */
02717 
02718 static psa_status_t psa_mac_setup( psa_mac_operation_t *operation,
02719                                    psa_key_handle_t handle,
02720                                    psa_algorithm_t alg,
02721                                    int is_sign )
02722 {
02723     psa_status_t status;
02724     psa_key_slot_t *slot;
02725     size_t key_bits;
02726     psa_key_usage_t usage =
02727         is_sign ? PSA_KEY_USAGE_SIGN : PSA_KEY_USAGE_VERIFY;
02728     uint8_t truncated = PSA_MAC_TRUNCATED_LENGTH( alg );
02729     psa_algorithm_t full_length_alg = PSA_ALG_FULL_LENGTH_MAC( alg );
02730 
02731     /* A context must be freshly initialized before it can be set up. */
02732     if( operation->alg != 0 )
02733     {
02734         return( PSA_ERROR_BAD_STATE );
02735     }
02736 
02737     status = psa_mac_init( operation, full_length_alg );
02738     if( status != PSA_SUCCESS )
02739         return( status );
02740     if( is_sign )
02741         operation->is_sign = 1;
02742 
02743     status = psa_get_transparent_key( handle, &slot, usage, alg );
02744     if( status != PSA_SUCCESS )
02745         goto exit;
02746     key_bits = psa_get_key_slot_bits( slot );
02747 
02748 #if defined(MBEDTLS_CMAC_C)
02749     if( full_length_alg == PSA_ALG_CMAC )
02750     {
02751         const mbedtls_cipher_info_t *cipher_info =
02752             mbedtls_cipher_info_from_psa( full_length_alg,
02753                                           slot->attr.type, key_bits, NULL );
02754         int ret;
02755         if( cipher_info == NULL )
02756         {
02757             status = PSA_ERROR_NOT_SUPPORTED;
02758             goto exit;
02759         }
02760         operation->mac_size = cipher_info->block_size;
02761         ret = psa_cmac_setup( operation, key_bits, slot, cipher_info );
02762         status = mbedtls_to_psa_error( ret );
02763     }
02764     else
02765 #endif /* MBEDTLS_CMAC_C */
02766 #if defined(MBEDTLS_MD_C)
02767     if( PSA_ALG_IS_HMAC( full_length_alg ) )
02768     {
02769         psa_algorithm_t hash_alg = PSA_ALG_HMAC_GET_HASH( alg );
02770         if( hash_alg == 0 )
02771         {
02772             status = PSA_ERROR_NOT_SUPPORTED;
02773             goto exit;
02774         }
02775 
02776         operation->mac_size = PSA_HASH_SIZE( hash_alg );
02777         /* Sanity check. This shouldn't fail on a valid configuration. */
02778         if( operation->mac_size == 0 ||
02779             operation->mac_size > sizeof( operation->ctx.hmac.opad ) )
02780         {
02781             status = PSA_ERROR_NOT_SUPPORTED;
02782             goto exit;
02783         }
02784 
02785         if( slot->attr.type != PSA_KEY_TYPE_HMAC )
02786         {
02787             status = PSA_ERROR_INVALID_ARGUMENT;
02788             goto exit;
02789         }
02790 
02791         status = psa_hmac_setup_internal( &operation->ctx.hmac,
02792                                           slot->data.raw.data,
02793                                           slot->data.raw.bytes,
02794                                           hash_alg );
02795     }
02796     else
02797 #endif /* MBEDTLS_MD_C */
02798     {
02799         (void) key_bits;
02800         status = PSA_ERROR_NOT_SUPPORTED;
02801     }
02802 
02803     if( truncated == 0 )
02804     {
02805         /* The "normal" case: untruncated algorithm. Nothing to do. */
02806     }
02807     else if( truncated < 4 )
02808     {
02809         /* A very short MAC is too short for security since it can be
02810          * brute-forced. Ancient protocols with 32-bit MACs do exist,
02811          * so we make this our minimum, even though 32 bits is still
02812          * too small for security. */
02813         status = PSA_ERROR_NOT_SUPPORTED;
02814     }
02815     else if( truncated > operation->mac_size )
02816     {
02817         /* It's impossible to "truncate" to a larger length. */
02818         status = PSA_ERROR_INVALID_ARGUMENT;
02819     }
02820     else
02821         operation->mac_size = truncated;
02822 
02823 exit:
02824     if( status != PSA_SUCCESS )
02825     {
02826         psa_mac_abort( operation );
02827     }
02828     else
02829     {
02830         operation->key_set = 1;
02831     }
02832     return( status );
02833 }
02834 
02835 psa_status_t psa_mac_sign_setup( psa_mac_operation_t *operation,
02836                                  psa_key_handle_t handle,
02837                                  psa_algorithm_t alg )
02838 {
02839     return( psa_mac_setup( operation, handle, alg, 1 ) );
02840 }
02841 
02842 psa_status_t psa_mac_verify_setup( psa_mac_operation_t *operation,
02843                                    psa_key_handle_t handle,
02844                                    psa_algorithm_t alg )
02845 {
02846     return( psa_mac_setup( operation, handle, alg, 0 ) );
02847 }
02848 
02849 psa_status_t psa_mac_update( psa_mac_operation_t *operation,
02850                              const uint8_t *input,
02851                              size_t input_length )
02852 {
02853     psa_status_t status = PSA_ERROR_BAD_STATE;
02854     if( ! operation->key_set )
02855         return( PSA_ERROR_BAD_STATE );
02856     if( operation->iv_required && ! operation->iv_set )
02857         return( PSA_ERROR_BAD_STATE );
02858     operation->has_input = 1;
02859 
02860 #if defined(MBEDTLS_CMAC_C)
02861     if( operation->alg == PSA_ALG_CMAC )
02862     {
02863         int ret = mbedtls_cipher_cmac_update( &operation->ctx.cmac,
02864                                               input, input_length );
02865         status = mbedtls_to_psa_error( ret );
02866     }
02867     else
02868 #endif /* MBEDTLS_CMAC_C */
02869 #if defined(MBEDTLS_MD_C)
02870     if( PSA_ALG_IS_HMAC( operation->alg ) )
02871     {
02872         status = psa_hash_update( &operation->ctx.hmac.hash_ctx, input,
02873                                   input_length );
02874     }
02875     else
02876 #endif /* MBEDTLS_MD_C */
02877     {
02878         /* This shouldn't happen if `operation` was initialized by
02879          * a setup function. */
02880         return( PSA_ERROR_BAD_STATE );
02881     }
02882 
02883     if( status != PSA_SUCCESS )
02884         psa_mac_abort( operation );
02885     return( status );
02886 }
02887 
02888 #if defined(MBEDTLS_MD_C)
02889 static psa_status_t psa_hmac_finish_internal( psa_hmac_internal_data *hmac,
02890                                               uint8_t *mac,
02891                                               size_t mac_size )
02892 {
02893     uint8_t tmp[MBEDTLS_MD_MAX_SIZE];
02894     psa_algorithm_t hash_alg = hmac->hash_ctx.alg;
02895     size_t hash_size = 0;
02896     size_t block_size = psa_get_hash_block_size( hash_alg );
02897     psa_status_t status;
02898 
02899     status = psa_hash_finish( &hmac->hash_ctx, tmp, sizeof( tmp ), &hash_size );
02900     if( status != PSA_SUCCESS )
02901         return( status );
02902     /* From here on, tmp needs to be wiped. */
02903 
02904     status = psa_hash_setup( &hmac->hash_ctx, hash_alg );
02905     if( status != PSA_SUCCESS )
02906         goto exit;
02907 
02908     status = psa_hash_update( &hmac->hash_ctx, hmac->opad, block_size );
02909     if( status != PSA_SUCCESS )
02910         goto exit;
02911 
02912     status = psa_hash_update( &hmac->hash_ctx, tmp, hash_size );
02913     if( status != PSA_SUCCESS )
02914         goto exit;
02915 
02916     status = psa_hash_finish( &hmac->hash_ctx, tmp, sizeof( tmp ), &hash_size );
02917     if( status != PSA_SUCCESS )
02918         goto exit;
02919 
02920     memcpy( mac, tmp, mac_size );
02921 
02922 exit:
02923     mbedtls_platform_zeroize( tmp, hash_size );
02924     return( status );
02925 }
02926 #endif /* MBEDTLS_MD_C */
02927 
02928 static psa_status_t psa_mac_finish_internal( psa_mac_operation_t *operation,
02929                                              uint8_t *mac,
02930                                              size_t mac_size )
02931 {
02932     if( ! operation->key_set )
02933         return( PSA_ERROR_BAD_STATE );
02934     if( operation->iv_required && ! operation->iv_set )
02935         return( PSA_ERROR_BAD_STATE );
02936 
02937     if( mac_size < operation->mac_size )
02938         return( PSA_ERROR_BUFFER_TOO_SMALL );
02939 
02940 #if defined(MBEDTLS_CMAC_C)
02941     if( operation->alg == PSA_ALG_CMAC )
02942     {
02943         uint8_t tmp[PSA_MAX_BLOCK_CIPHER_BLOCK_SIZE];
02944         int ret = mbedtls_cipher_cmac_finish( &operation->ctx.cmac, tmp );
02945         if( ret == 0 )
02946             memcpy( mac, tmp, operation->mac_size );
02947         mbedtls_platform_zeroize( tmp, sizeof( tmp ) );
02948         return( mbedtls_to_psa_error( ret ) );
02949     }
02950     else
02951 #endif /* MBEDTLS_CMAC_C */
02952 #if defined(MBEDTLS_MD_C)
02953     if( PSA_ALG_IS_HMAC( operation->alg ) )
02954     {
02955         return( psa_hmac_finish_internal( &operation->ctx.hmac,
02956                                           mac, operation->mac_size ) );
02957     }
02958     else
02959 #endif /* MBEDTLS_MD_C */
02960     {
02961         /* This shouldn't happen if `operation` was initialized by
02962          * a setup function. */
02963         return( PSA_ERROR_BAD_STATE );
02964     }
02965 }
02966 
02967 psa_status_t psa_mac_sign_finish( psa_mac_operation_t *operation,
02968                                   uint8_t *mac,
02969                                   size_t mac_size,
02970                                   size_t *mac_length )
02971 {
02972     psa_status_t status;
02973 
02974     if( operation->alg == 0 )
02975     {
02976         return( PSA_ERROR_BAD_STATE );
02977     }
02978 
02979     /* Fill the output buffer with something that isn't a valid mac
02980      * (barring an attack on the mac and deliberately-crafted input),
02981      * in case the caller doesn't check the return status properly. */
02982     *mac_length = mac_size;
02983     /* If mac_size is 0 then mac may be NULL and then the
02984      * call to memset would have undefined behavior. */
02985     if( mac_size != 0 )
02986         memset( mac, '!', mac_size );
02987 
02988     if( ! operation->is_sign )
02989     {
02990         return( PSA_ERROR_BAD_STATE );
02991     }
02992 
02993     status = psa_mac_finish_internal( operation, mac, mac_size );
02994 
02995     if( status == PSA_SUCCESS )
02996     {
02997         status = psa_mac_abort( operation );
02998         if( status == PSA_SUCCESS )
02999             *mac_length = operation->mac_size;
03000         else
03001             memset( mac, '!', mac_size );
03002     }
03003     else
03004         psa_mac_abort( operation );
03005     return( status );
03006 }
03007 
03008 psa_status_t psa_mac_verify_finish( psa_mac_operation_t *operation,
03009                                     const uint8_t *mac,
03010                                     size_t mac_length )
03011 {
03012     uint8_t actual_mac[PSA_MAC_MAX_SIZE];
03013     psa_status_t status;
03014 
03015     if( operation->alg == 0 )
03016     {
03017         return( PSA_ERROR_BAD_STATE );
03018     }
03019 
03020     if( operation->is_sign )
03021     {
03022         return( PSA_ERROR_BAD_STATE );
03023     }
03024     if( operation->mac_size != mac_length )
03025     {
03026         status = PSA_ERROR_INVALID_SIGNATURE;
03027         goto cleanup;
03028     }
03029 
03030     status = psa_mac_finish_internal( operation,
03031                                       actual_mac, sizeof( actual_mac ) );
03032 
03033     if( safer_memcmp( mac, actual_mac, mac_length ) != 0 )
03034         status = PSA_ERROR_INVALID_SIGNATURE;
03035 
03036 cleanup:
03037     if( status == PSA_SUCCESS )
03038         status = psa_mac_abort( operation );
03039     else
03040         psa_mac_abort( operation );
03041 
03042     mbedtls_platform_zeroize( actual_mac, sizeof( actual_mac ) );
03043 
03044     return( status );
03045 }
03046 
03047 
03048 
03049 /****************************************************************/
03050 /* Asymmetric cryptography */
03051 /****************************************************************/
03052 
03053 #if defined(MBEDTLS_RSA_C)
03054 /* Decode the hash algorithm from alg and store the mbedtls encoding in
03055  * md_alg. Verify that the hash length is acceptable. */
03056 static psa_status_t psa_rsa_decode_md_type( psa_algorithm_t alg,
03057                                             size_t hash_length,
03058                                             mbedtls_md_type_t *md_alg )
03059 {
03060     psa_algorithm_t hash_alg = PSA_ALG_SIGN_GET_HASH( alg );
03061     const mbedtls_md_info_t *md_info = mbedtls_md_info_from_psa( hash_alg );
03062     *md_alg = mbedtls_md_get_type( md_info );
03063 
03064     /* The Mbed TLS RSA module uses an unsigned int for hash length
03065      * parameters. Validate that it fits so that we don't risk an
03066      * overflow later. */
03067 #if SIZE_MAX > UINT_MAX
03068     if( hash_length > UINT_MAX )
03069         return( PSA_ERROR_INVALID_ARGUMENT );
03070 #endif
03071 
03072 #if defined(MBEDTLS_PKCS1_V15)
03073     /* For PKCS#1 v1.5 signature, if using a hash, the hash length
03074      * must be correct. */
03075     if( PSA_ALG_IS_RSA_PKCS1V15_SIGN( alg ) &&
03076         alg != PSA_ALG_RSA_PKCS1V15_SIGN_RAW )
03077     {
03078         if( md_info == NULL )
03079             return( PSA_ERROR_NOT_SUPPORTED );
03080         if( mbedtls_md_get_size( md_info ) != hash_length )
03081             return( PSA_ERROR_INVALID_ARGUMENT );
03082     }
03083 #endif /* MBEDTLS_PKCS1_V15 */
03084 
03085 #if defined(MBEDTLS_PKCS1_V21)
03086     /* PSS requires a hash internally. */
03087     if( PSA_ALG_IS_RSA_PSS( alg ) )
03088     {
03089         if( md_info == NULL )
03090             return( PSA_ERROR_NOT_SUPPORTED );
03091     }
03092 #endif /* MBEDTLS_PKCS1_V21 */
03093 
03094     return( PSA_SUCCESS );
03095 }
03096 
03097 static psa_status_t psa_rsa_sign( mbedtls_rsa_context *rsa,
03098                                   psa_algorithm_t alg,
03099                                   const uint8_t *hash,
03100                                   size_t hash_length,
03101                                   uint8_t *signature,
03102                                   size_t signature_size,
03103                                   size_t *signature_length )
03104 {
03105     psa_status_t status;
03106     int ret;
03107     mbedtls_md_type_t md_alg;
03108 
03109     status = psa_rsa_decode_md_type( alg, hash_length, &md_alg );
03110     if( status != PSA_SUCCESS )
03111         return( status );
03112 
03113     if( signature_size < mbedtls_rsa_get_len( rsa ) )
03114         return( PSA_ERROR_BUFFER_TOO_SMALL );
03115 
03116 #if defined(MBEDTLS_PKCS1_V15)
03117     if( PSA_ALG_IS_RSA_PKCS1V15_SIGN( alg ) )
03118     {
03119         mbedtls_rsa_set_padding( rsa, MBEDTLS_RSA_PKCS_V15,
03120                                  MBEDTLS_MD_NONE );
03121         ret = mbedtls_rsa_pkcs1_sign( rsa,
03122                                       mbedtls_ctr_drbg_random,
03123                                       &global_data.ctr_drbg,
03124                                       MBEDTLS_RSA_PRIVATE,
03125                                       md_alg,
03126                                       (unsigned int) hash_length,
03127                                       hash,
03128                                       signature );
03129     }
03130     else
03131 #endif /* MBEDTLS_PKCS1_V15 */
03132 #if defined(MBEDTLS_PKCS1_V21)
03133     if( PSA_ALG_IS_RSA_PSS( alg ) )
03134     {
03135         mbedtls_rsa_set_padding( rsa, MBEDTLS_RSA_PKCS_V21, md_alg );
03136         ret = mbedtls_rsa_rsassa_pss_sign( rsa,
03137                                            mbedtls_ctr_drbg_random,
03138                                            &global_data.ctr_drbg,
03139                                            MBEDTLS_RSA_PRIVATE,
03140                                            MBEDTLS_MD_NONE,
03141                                            (unsigned int) hash_length,
03142                                            hash,
03143                                            signature );
03144     }
03145     else
03146 #endif /* MBEDTLS_PKCS1_V21 */
03147     {
03148         return( PSA_ERROR_INVALID_ARGUMENT );
03149     }
03150 
03151     if( ret == 0 )
03152         *signature_length = mbedtls_rsa_get_len( rsa );
03153     return( mbedtls_to_psa_error( ret ) );
03154 }
03155 
03156 static psa_status_t psa_rsa_verify( mbedtls_rsa_context *rsa,
03157                                     psa_algorithm_t alg,
03158                                     const uint8_t *hash,
03159                                     size_t hash_length,
03160                                     const uint8_t *signature,
03161                                     size_t signature_length )
03162 {
03163     psa_status_t status;
03164     int ret;
03165     mbedtls_md_type_t md_alg;
03166 
03167     status = psa_rsa_decode_md_type( alg, hash_length, &md_alg );
03168     if( status != PSA_SUCCESS )
03169         return( status );
03170 
03171     if( signature_length != mbedtls_rsa_get_len( rsa ) )
03172         return( PSA_ERROR_INVALID_SIGNATURE );
03173 
03174 #if defined(MBEDTLS_PKCS1_V15)
03175     if( PSA_ALG_IS_RSA_PKCS1V15_SIGN( alg ) )
03176     {
03177         mbedtls_rsa_set_padding( rsa, MBEDTLS_RSA_PKCS_V15,
03178                                  MBEDTLS_MD_NONE );
03179         ret = mbedtls_rsa_pkcs1_verify( rsa,
03180                                         mbedtls_ctr_drbg_random,
03181                                         &global_data.ctr_drbg,
03182                                         MBEDTLS_RSA_PUBLIC,
03183                                         md_alg,
03184                                         (unsigned int) hash_length,
03185                                         hash,
03186                                         signature );
03187     }
03188     else
03189 #endif /* MBEDTLS_PKCS1_V15 */
03190 #if defined(MBEDTLS_PKCS1_V21)
03191     if( PSA_ALG_IS_RSA_PSS( alg ) )
03192     {
03193         mbedtls_rsa_set_padding( rsa, MBEDTLS_RSA_PKCS_V21, md_alg );
03194         ret = mbedtls_rsa_rsassa_pss_verify( rsa,
03195                                              mbedtls_ctr_drbg_random,
03196                                              &global_data.ctr_drbg,
03197                                              MBEDTLS_RSA_PUBLIC,
03198                                              MBEDTLS_MD_NONE,
03199                                              (unsigned int) hash_length,
03200                                              hash,
03201                                              signature );
03202     }
03203     else
03204 #endif /* MBEDTLS_PKCS1_V21 */
03205     {
03206         return( PSA_ERROR_INVALID_ARGUMENT );
03207     }
03208 
03209     /* Mbed TLS distinguishes "invalid padding" from "valid padding but
03210      * the rest of the signature is invalid". This has little use in
03211      * practice and PSA doesn't report this distinction. */
03212     if( ret == MBEDTLS_ERR_RSA_INVALID_PADDING )
03213         return( PSA_ERROR_INVALID_SIGNATURE );
03214     return( mbedtls_to_psa_error( ret ) );
03215 }
03216 #endif /* MBEDTLS_RSA_C */
03217 
03218 #if defined(MBEDTLS_ECDSA_C)
03219 /* `ecp` cannot be const because `ecp->grp` needs to be non-const
03220  * for mbedtls_ecdsa_sign() and mbedtls_ecdsa_sign_det()
03221  * (even though these functions don't modify it). */
03222 static psa_status_t psa_ecdsa_sign( mbedtls_ecp_keypair *ecp,
03223                                     psa_algorithm_t alg,
03224                                     const uint8_t *hash,
03225                                     size_t hash_length,
03226                                     uint8_t *signature,
03227                                     size_t signature_size,
03228                                     size_t *signature_length )
03229 {
03230     int ret;
03231     mbedtls_mpi r, s;
03232     size_t curve_bytes = PSA_BITS_TO_BYTES( ecp->grp .pbits  );
03233     mbedtls_mpi_init( &r );
03234     mbedtls_mpi_init( &s );
03235 
03236     if( signature_size < 2 * curve_bytes )
03237     {
03238         ret = MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL;
03239         goto cleanup;
03240     }
03241 
03242 #if defined(MBEDTLS_ECDSA_DETERMINISTIC)
03243     if( PSA_ALG_DSA_IS_DETERMINISTIC( alg ) )
03244     {
03245         psa_algorithm_t hash_alg = PSA_ALG_SIGN_GET_HASH( alg );
03246         const mbedtls_md_info_t *md_info = mbedtls_md_info_from_psa( hash_alg );
03247         mbedtls_md_type_t md_alg = mbedtls_md_get_type( md_info );
03248         MBEDTLS_MPI_CHK( mbedtls_ecdsa_sign_det_ext( &ecp->grp , &r, &s,
03249                                                      &ecp->d , hash,
03250                                                      hash_length, md_alg,
03251                                                      mbedtls_ctr_drbg_random,
03252                                                      &global_data.ctr_drbg ) );
03253     }
03254     else
03255 #endif /* MBEDTLS_ECDSA_DETERMINISTIC */
03256     {
03257         (void) alg;
03258         MBEDTLS_MPI_CHK( mbedtls_ecdsa_sign( &ecp->grp , &r, &s, &ecp->d ,
03259                                              hash, hash_length,
03260                                              mbedtls_ctr_drbg_random,
03261                                              &global_data.ctr_drbg ) );
03262     }
03263 
03264     MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &r,
03265                                                signature,
03266                                                curve_bytes ) );
03267     MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &s,
03268                                                signature + curve_bytes,
03269                                                curve_bytes ) );
03270 
03271 cleanup:
03272     mbedtls_mpi_free( &r );
03273     mbedtls_mpi_free( &s );
03274     if( ret == 0 )
03275         *signature_length = 2 * curve_bytes;
03276     return( mbedtls_to_psa_error( ret ) );
03277 }
03278 
03279 static psa_status_t psa_ecdsa_verify( mbedtls_ecp_keypair *ecp,
03280                                       const uint8_t *hash,
03281                                       size_t hash_length,
03282                                       const uint8_t *signature,
03283                                       size_t signature_length )
03284 {
03285     int ret;
03286     mbedtls_mpi r, s;
03287     size_t curve_bytes = PSA_BITS_TO_BYTES( ecp->grp .pbits  );
03288     mbedtls_mpi_init( &r );
03289     mbedtls_mpi_init( &s );
03290 
03291     if( signature_length != 2 * curve_bytes )
03292         return( PSA_ERROR_INVALID_SIGNATURE );
03293 
03294     MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &r,
03295                                               signature,
03296                                               curve_bytes ) );
03297     MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &s,
03298                                               signature + curve_bytes,
03299                                               curve_bytes ) );
03300 
03301     ret = mbedtls_ecdsa_verify( &ecp->grp , hash, hash_length,
03302                                 &ecp->Q , &r, &s );
03303 
03304 cleanup:
03305     mbedtls_mpi_free( &r );
03306     mbedtls_mpi_free( &s );
03307     return( mbedtls_to_psa_error( ret ) );
03308 }
03309 #endif /* MBEDTLS_ECDSA_C */
03310 
03311 psa_status_t psa_asymmetric_sign( psa_key_handle_t handle,
03312                                   psa_algorithm_t alg,
03313                                   const uint8_t *hash,
03314                                   size_t hash_length,
03315                                   uint8_t *signature,
03316                                   size_t signature_size,
03317                                   size_t *signature_length )
03318 {
03319     psa_key_slot_t *slot;
03320     psa_status_t status;
03321 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
03322     const psa_drv_se_t *drv;
03323     psa_drv_se_context_t *drv_context;
03324 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
03325 
03326     *signature_length = signature_size;
03327     /* Immediately reject a zero-length signature buffer. This guarantees
03328      * that signature must be a valid pointer. (On the other hand, the hash
03329      * buffer can in principle be empty since it doesn't actually have
03330      * to be a hash.) */
03331     if( signature_size == 0 )
03332         return( PSA_ERROR_BUFFER_TOO_SMALL );
03333 
03334     status = psa_get_key_from_slot( handle, &slot, PSA_KEY_USAGE_SIGN, alg );
03335     if( status != PSA_SUCCESS )
03336         goto exit;
03337     if( ! PSA_KEY_TYPE_IS_KEY_PAIR( slot->attr.type ) )
03338     {
03339         status = PSA_ERROR_INVALID_ARGUMENT;
03340         goto exit;
03341     }
03342 
03343 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
03344     if( psa_get_se_driver( slot->attr.lifetime, &drv, &drv_context ) )
03345     {
03346         if( drv->asymmetric == NULL ||
03347             drv->asymmetric->p_sign == NULL )
03348         {
03349             status = PSA_ERROR_NOT_SUPPORTED;
03350             goto exit;
03351         }
03352         status = drv->asymmetric->p_sign( drv_context,
03353                                           slot->data.se.slot_number,
03354                                           alg,
03355                                           hash, hash_length,
03356                                           signature, signature_size,
03357                                           signature_length );
03358     }
03359     else
03360 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
03361 #if defined(MBEDTLS_RSA_C)
03362     if( slot->attr.type == PSA_KEY_TYPE_RSA_KEY_PAIR )
03363     {
03364         status = psa_rsa_sign( slot->data.rsa,
03365                                alg,
03366                                hash, hash_length,
03367                                signature, signature_size,
03368                                signature_length );
03369     }
03370     else
03371 #endif /* defined(MBEDTLS_RSA_C) */
03372 #if defined(MBEDTLS_ECP_C)
03373     if( PSA_KEY_TYPE_IS_ECC( slot->attr.type ) )
03374     {
03375 #if defined(MBEDTLS_ECDSA_C)
03376         if(
03377 #if defined(MBEDTLS_ECDSA_DETERMINISTIC)
03378             PSA_ALG_IS_ECDSA( alg )
03379 #else
03380             PSA_ALG_IS_RANDOMIZED_ECDSA( alg )
03381 #endif
03382             )
03383             status = psa_ecdsa_sign( slot->data.ecp,
03384                                      alg,
03385                                      hash, hash_length,
03386                                      signature, signature_size,
03387                                      signature_length );
03388         else
03389 #endif /* defined(MBEDTLS_ECDSA_C) */
03390         {
03391             status = PSA_ERROR_INVALID_ARGUMENT;
03392         }
03393     }
03394     else
03395 #endif /* defined(MBEDTLS_ECP_C) */
03396     {
03397         status = PSA_ERROR_NOT_SUPPORTED;
03398     }
03399 
03400 exit:
03401     /* Fill the unused part of the output buffer (the whole buffer on error,
03402      * the trailing part on success) with something that isn't a valid mac
03403      * (barring an attack on the mac and deliberately-crafted input),
03404      * in case the caller doesn't check the return status properly. */
03405     if( status == PSA_SUCCESS )
03406         memset( signature + *signature_length, '!',
03407                 signature_size - *signature_length );
03408     else
03409         memset( signature, '!', signature_size );
03410     /* If signature_size is 0 then we have nothing to do. We must not call
03411      * memset because signature may be NULL in this case. */
03412     return( status );
03413 }
03414 
03415 psa_status_t psa_asymmetric_verify( psa_key_handle_t handle,
03416                                     psa_algorithm_t alg,
03417                                     const uint8_t *hash,
03418                                     size_t hash_length,
03419                                     const uint8_t *signature,
03420                                     size_t signature_length )
03421 {
03422     psa_key_slot_t *slot;
03423     psa_status_t status;
03424 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
03425     const psa_drv_se_t *drv;
03426     psa_drv_se_context_t *drv_context;
03427 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
03428 
03429     status = psa_get_key_from_slot( handle, &slot, PSA_KEY_USAGE_VERIFY, alg );
03430     if( status != PSA_SUCCESS )
03431         return( status );
03432 
03433 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
03434     if( psa_get_se_driver( slot->attr.lifetime, &drv, &drv_context ) )
03435     {
03436         if( drv->asymmetric == NULL ||
03437             drv->asymmetric->p_verify == NULL )
03438             return( PSA_ERROR_NOT_SUPPORTED );
03439         return( drv->asymmetric->p_verify( drv_context,
03440                                            slot->data.se.slot_number,
03441                                            alg,
03442                                            hash, hash_length,
03443                                            signature, signature_length ) );
03444     }
03445     else
03446 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
03447 #if defined(MBEDTLS_RSA_C)
03448     if( PSA_KEY_TYPE_IS_RSA( slot->attr.type ) )
03449     {
03450         return( psa_rsa_verify( slot->data.rsa,
03451                                 alg,
03452                                 hash, hash_length,
03453                                 signature, signature_length ) );
03454     }
03455     else
03456 #endif /* defined(MBEDTLS_RSA_C) */
03457 #if defined(MBEDTLS_ECP_C)
03458     if( PSA_KEY_TYPE_IS_ECC( slot->attr.type ) )
03459     {
03460 #if defined(MBEDTLS_ECDSA_C)
03461         if( PSA_ALG_IS_ECDSA( alg ) )
03462             return( psa_ecdsa_verify( slot->data.ecp,
03463                                       hash, hash_length,
03464                                       signature, signature_length ) );
03465         else
03466 #endif /* defined(MBEDTLS_ECDSA_C) */
03467         {
03468             return( PSA_ERROR_INVALID_ARGUMENT );
03469         }
03470     }
03471     else
03472 #endif /* defined(MBEDTLS_ECP_C) */
03473     {
03474         return( PSA_ERROR_NOT_SUPPORTED );
03475     }
03476 }
03477 
03478 #if defined(MBEDTLS_RSA_C) && defined(MBEDTLS_PKCS1_V21)
03479 static void psa_rsa_oaep_set_padding_mode( psa_algorithm_t alg,
03480                                            mbedtls_rsa_context *rsa )
03481 {
03482     psa_algorithm_t hash_alg = PSA_ALG_RSA_OAEP_GET_HASH( alg );
03483     const mbedtls_md_info_t *md_info = mbedtls_md_info_from_psa( hash_alg );
03484     mbedtls_md_type_t md_alg = mbedtls_md_get_type( md_info );
03485     mbedtls_rsa_set_padding( rsa, MBEDTLS_RSA_PKCS_V21, md_alg );
03486 }
03487 #endif /* defined(MBEDTLS_RSA_C) && defined(MBEDTLS_PKCS1_V21) */
03488 
03489 psa_status_t psa_asymmetric_encrypt( psa_key_handle_t handle,
03490                                      psa_algorithm_t alg,
03491                                      const uint8_t *input,
03492                                      size_t input_length,
03493                                      const uint8_t *salt,
03494                                      size_t salt_length,
03495                                      uint8_t *output,
03496                                      size_t output_size,
03497                                      size_t *output_length )
03498 {
03499     psa_key_slot_t *slot;
03500     psa_status_t status;
03501 
03502     (void) input;
03503     (void) input_length;
03504     (void) salt;
03505     (void) output;
03506     (void) output_size;
03507 
03508     *output_length = 0;
03509 
03510     if( ! PSA_ALG_IS_RSA_OAEP( alg ) && salt_length != 0 )
03511         return( PSA_ERROR_INVALID_ARGUMENT );
03512 
03513     status = psa_get_transparent_key( handle, &slot, PSA_KEY_USAGE_ENCRYPT, alg );
03514     if( status != PSA_SUCCESS )
03515         return( status );
03516     if( ! ( PSA_KEY_TYPE_IS_PUBLIC_KEY( slot->attr.type ) ||
03517             PSA_KEY_TYPE_IS_KEY_PAIR( slot->attr.type ) ) )
03518         return( PSA_ERROR_INVALID_ARGUMENT );
03519 
03520 #if defined(MBEDTLS_RSA_C)
03521     if( PSA_KEY_TYPE_IS_RSA( slot->attr.type ) )
03522     {
03523         mbedtls_rsa_context *rsa = slot->data.rsa;
03524         int ret;
03525         if( output_size < mbedtls_rsa_get_len( rsa ) )
03526             return( PSA_ERROR_BUFFER_TOO_SMALL );
03527 #if defined(MBEDTLS_PKCS1_V15)
03528         if( alg == PSA_ALG_RSA_PKCS1V15_CRYPT )
03529         {
03530             ret = mbedtls_rsa_pkcs1_encrypt( rsa,
03531                                              mbedtls_ctr_drbg_random,
03532                                              &global_data.ctr_drbg,
03533                                              MBEDTLS_RSA_PUBLIC,
03534                                              input_length,
03535                                              input,
03536                                              output );
03537         }
03538         else
03539 #endif /* MBEDTLS_PKCS1_V15 */
03540 #if defined(MBEDTLS_PKCS1_V21)
03541         if( PSA_ALG_IS_RSA_OAEP( alg ) )
03542         {
03543             psa_rsa_oaep_set_padding_mode( alg, rsa );
03544             ret = mbedtls_rsa_rsaes_oaep_encrypt( rsa,
03545                                                   mbedtls_ctr_drbg_random,
03546                                                   &global_data.ctr_drbg,
03547                                                   MBEDTLS_RSA_PUBLIC,
03548                                                   salt, salt_length,
03549                                                   input_length,
03550                                                   input,
03551                                                   output );
03552         }
03553         else
03554 #endif /* MBEDTLS_PKCS1_V21 */
03555         {
03556             return( PSA_ERROR_INVALID_ARGUMENT );
03557         }
03558         if( ret == 0 )
03559             *output_length = mbedtls_rsa_get_len( rsa );
03560         return( mbedtls_to_psa_error( ret ) );
03561     }
03562     else
03563 #endif /* defined(MBEDTLS_RSA_C) */
03564     {
03565         return( PSA_ERROR_NOT_SUPPORTED );
03566     }
03567 }
03568 
03569 psa_status_t psa_asymmetric_decrypt( psa_key_handle_t handle,
03570                                      psa_algorithm_t alg,
03571                                      const uint8_t *input,
03572                                      size_t input_length,
03573                                      const uint8_t *salt,
03574                                      size_t salt_length,
03575                                      uint8_t *output,
03576                                      size_t output_size,
03577                                      size_t *output_length )
03578 {
03579     psa_key_slot_t *slot;
03580     psa_status_t status;
03581 
03582     (void) input;
03583     (void) input_length;
03584     (void) salt;
03585     (void) output;
03586     (void) output_size;
03587 
03588     *output_length = 0;
03589 
03590     if( ! PSA_ALG_IS_RSA_OAEP( alg ) && salt_length != 0 )
03591         return( PSA_ERROR_INVALID_ARGUMENT );
03592 
03593     status = psa_get_transparent_key( handle, &slot, PSA_KEY_USAGE_DECRYPT, alg );
03594     if( status != PSA_SUCCESS )
03595         return( status );
03596     if( ! PSA_KEY_TYPE_IS_KEY_PAIR( slot->attr.type ) )
03597         return( PSA_ERROR_INVALID_ARGUMENT );
03598 
03599 #if defined(MBEDTLS_RSA_C)
03600     if( slot->attr.type == PSA_KEY_TYPE_RSA_KEY_PAIR )
03601     {
03602         mbedtls_rsa_context *rsa = slot->data.rsa;
03603         int ret;
03604 
03605         if( input_length != mbedtls_rsa_get_len( rsa ) )
03606             return( PSA_ERROR_INVALID_ARGUMENT );
03607 
03608 #if defined(MBEDTLS_PKCS1_V15)
03609         if( alg == PSA_ALG_RSA_PKCS1V15_CRYPT )
03610         {
03611             ret = mbedtls_rsa_pkcs1_decrypt( rsa,
03612                                              mbedtls_ctr_drbg_random,
03613                                              &global_data.ctr_drbg,
03614                                              MBEDTLS_RSA_PRIVATE,
03615                                              output_length,
03616                                              input,
03617                                              output,
03618                                              output_size );
03619         }
03620         else
03621 #endif /* MBEDTLS_PKCS1_V15 */
03622 #if defined(MBEDTLS_PKCS1_V21)
03623         if( PSA_ALG_IS_RSA_OAEP( alg ) )
03624         {
03625             psa_rsa_oaep_set_padding_mode( alg, rsa );
03626             ret = mbedtls_rsa_rsaes_oaep_decrypt( rsa,
03627                                                   mbedtls_ctr_drbg_random,
03628                                                   &global_data.ctr_drbg,
03629                                                   MBEDTLS_RSA_PRIVATE,
03630                                                   salt, salt_length,
03631                                                   output_length,
03632                                                   input,
03633                                                   output,
03634                                                   output_size );
03635         }
03636         else
03637 #endif /* MBEDTLS_PKCS1_V21 */
03638         {
03639             return( PSA_ERROR_INVALID_ARGUMENT );
03640         }
03641 
03642         return( mbedtls_to_psa_error( ret ) );
03643     }
03644     else
03645 #endif /* defined(MBEDTLS_RSA_C) */
03646     {
03647         return( PSA_ERROR_NOT_SUPPORTED );
03648     }
03649 }
03650 
03651 
03652 
03653 /****************************************************************/
03654 /* Symmetric cryptography */
03655 /****************************************************************/
03656 
03657 /* Initialize the cipher operation structure. Once this function has been
03658  * called, psa_cipher_abort can run and will do the right thing. */
03659 static psa_status_t psa_cipher_init( psa_cipher_operation_t *operation,
03660                                      psa_algorithm_t alg )
03661 {
03662     if( ! PSA_ALG_IS_CIPHER( alg ) )
03663     {
03664         memset( operation, 0, sizeof( *operation ) );
03665         return( PSA_ERROR_INVALID_ARGUMENT );
03666     }
03667 
03668     operation->alg = alg;
03669     operation->key_set = 0;
03670     operation->iv_set = 0;
03671     operation->iv_required = 1;
03672     operation->iv_size = 0;
03673     operation->block_size = 0;
03674     mbedtls_cipher_init( &operation->ctx.cipher );
03675     return( PSA_SUCCESS );
03676 }
03677 
03678 static psa_status_t psa_cipher_setup( psa_cipher_operation_t *operation,
03679                                       psa_key_handle_t handle,
03680                                       psa_algorithm_t alg,
03681                                       mbedtls_operation_t cipher_operation )
03682 {
03683     int ret = 0;
03684     psa_status_t status = PSA_ERROR_GENERIC_ERROR;
03685     psa_key_slot_t *slot;
03686     size_t key_bits;
03687     const mbedtls_cipher_info_t *cipher_info = NULL;
03688     psa_key_usage_t usage = ( cipher_operation == MBEDTLS_ENCRYPT ?
03689                               PSA_KEY_USAGE_ENCRYPT :
03690                               PSA_KEY_USAGE_DECRYPT );
03691 
03692     /* A context must be freshly initialized before it can be set up. */
03693     if( operation->alg != 0 )
03694     {
03695         return( PSA_ERROR_BAD_STATE );
03696     }
03697 
03698     status = psa_cipher_init( operation, alg );
03699     if( status != PSA_SUCCESS )
03700         return( status );
03701 
03702     status = psa_get_transparent_key( handle, &slot, usage, alg);
03703     if( status != PSA_SUCCESS )
03704         goto exit;
03705     key_bits = psa_get_key_slot_bits( slot );
03706 
03707     cipher_info = mbedtls_cipher_info_from_psa( alg, slot->attr.type, key_bits, NULL );
03708     if( cipher_info == NULL )
03709     {
03710         status = PSA_ERROR_NOT_SUPPORTED;
03711         goto exit;
03712     }
03713 
03714     ret = mbedtls_cipher_setup( &operation->ctx.cipher, cipher_info );
03715     if( ret != 0 )
03716         goto exit;
03717 
03718 #if defined(MBEDTLS_DES_C)
03719     if( slot->attr.type == PSA_KEY_TYPE_DES && key_bits == 128 )
03720     {
03721         /* Two-key Triple-DES is 3-key Triple-DES with K1=K3 */
03722         uint8_t keys[24];
03723         memcpy( keys, slot->data.raw.data, 16 );
03724         memcpy( keys + 16, slot->data.raw.data, 8 );
03725         ret = mbedtls_cipher_setkey( &operation->ctx.cipher,
03726                                      keys,
03727                                      192, cipher_operation );
03728     }
03729     else
03730 #endif
03731     {
03732         ret = mbedtls_cipher_setkey( &operation->ctx.cipher,
03733                                      slot->data.raw.data,
03734                                      (int) key_bits, cipher_operation );
03735     }
03736     if( ret != 0 )
03737         goto exit;
03738 
03739 #if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING)
03740     switch( alg )
03741     {
03742         case PSA_ALG_CBC_NO_PADDING:
03743             ret = mbedtls_cipher_set_padding_mode( &operation->ctx.cipher,
03744                                                    MBEDTLS_PADDING_NONE );
03745             break;
03746         case PSA_ALG_CBC_PKCS7:
03747             ret = mbedtls_cipher_set_padding_mode( &operation->ctx.cipher,
03748                                                    MBEDTLS_PADDING_PKCS7 );
03749             break;
03750         default:
03751             /* The algorithm doesn't involve padding. */
03752             ret = 0;
03753             break;
03754     }
03755     if( ret != 0 )
03756         goto exit;
03757 #endif //MBEDTLS_CIPHER_MODE_WITH_PADDING
03758 
03759     operation->key_set = 1;
03760     operation->block_size = ( PSA_ALG_IS_STREAM_CIPHER( alg ) ? 1 :
03761                               PSA_BLOCK_CIPHER_BLOCK_SIZE( slot->attr.type ) );
03762     if( alg & PSA_ALG_CIPHER_FROM_BLOCK_FLAG )
03763     {
03764         operation->iv_size = PSA_BLOCK_CIPHER_BLOCK_SIZE( slot->attr.type );
03765     }
03766 #if defined(MBEDTLS_CHACHA20_C)
03767     else
03768     if( alg == PSA_ALG_CHACHA20 )
03769         operation->iv_size = 12;
03770 #endif
03771 
03772 exit:
03773     if( status == 0 )
03774         status = mbedtls_to_psa_error( ret );
03775     if( status != 0 )
03776         psa_cipher_abort( operation );
03777     return( status );
03778 }
03779 
03780 psa_status_t psa_cipher_encrypt_setup( psa_cipher_operation_t *operation,
03781                                        psa_key_handle_t handle,
03782                                        psa_algorithm_t alg )
03783 {
03784     return( psa_cipher_setup( operation, handle, alg, MBEDTLS_ENCRYPT ) );
03785 }
03786 
03787 psa_status_t psa_cipher_decrypt_setup( psa_cipher_operation_t *operation,
03788                                        psa_key_handle_t handle,
03789                                        psa_algorithm_t alg )
03790 {
03791     return( psa_cipher_setup( operation, handle, alg, MBEDTLS_DECRYPT ) );
03792 }
03793 
03794 psa_status_t psa_cipher_generate_iv( psa_cipher_operation_t *operation,
03795                                      uint8_t *iv,
03796                                      size_t iv_size,
03797                                      size_t *iv_length )
03798 {
03799     psa_status_t status;
03800     int ret;
03801     if( operation->iv_set || ! operation->iv_required )
03802     {
03803         return( PSA_ERROR_BAD_STATE );
03804     }
03805     if( iv_size < operation->iv_size )
03806     {
03807         status = PSA_ERROR_BUFFER_TOO_SMALL;
03808         goto exit;
03809     }
03810     ret = mbedtls_ctr_drbg_random( &global_data.ctr_drbg,
03811                                    iv, operation->iv_size );
03812     if( ret != 0 )
03813     {
03814         status = mbedtls_to_psa_error( ret );
03815         goto exit;
03816     }
03817 
03818     *iv_length = operation->iv_size;
03819     status = psa_cipher_set_iv( operation, iv, *iv_length );
03820 
03821 exit:
03822     if( status != PSA_SUCCESS )
03823         psa_cipher_abort( operation );
03824     return( status );
03825 }
03826 
03827 psa_status_t psa_cipher_set_iv( psa_cipher_operation_t *operation,
03828                                 const uint8_t *iv,
03829                                 size_t iv_length )
03830 {
03831     psa_status_t status;
03832     int ret;
03833     if( operation->iv_set || ! operation->iv_required )
03834     {
03835         return( PSA_ERROR_BAD_STATE );
03836     }
03837     if( iv_length != operation->iv_size )
03838     {
03839         status = PSA_ERROR_INVALID_ARGUMENT;
03840         goto exit;
03841     }
03842     ret = mbedtls_cipher_set_iv( &operation->ctx.cipher, iv, iv_length );
03843     status = mbedtls_to_psa_error( ret );
03844 exit:
03845     if( status == PSA_SUCCESS )
03846         operation->iv_set = 1;
03847     else
03848         psa_cipher_abort( operation );
03849     return( status );
03850 }
03851 
03852 psa_status_t psa_cipher_update( psa_cipher_operation_t *operation,
03853                                 const uint8_t *input,
03854                                 size_t input_length,
03855                                 uint8_t *output,
03856                                 size_t output_size,
03857                                 size_t *output_length )
03858 {
03859     psa_status_t status;
03860     int ret;
03861     size_t expected_output_size;
03862 
03863     if( operation->alg == 0 )
03864     {
03865         return( PSA_ERROR_BAD_STATE );
03866     }
03867 
03868     if( ! PSA_ALG_IS_STREAM_CIPHER( operation->alg ) )
03869     {
03870         /* Take the unprocessed partial block left over from previous
03871          * update calls, if any, plus the input to this call. Remove
03872          * the last partial block, if any. You get the data that will be
03873          * output in this call. */
03874         expected_output_size =
03875             ( operation->ctx.cipher.unprocessed_len + input_length )
03876             / operation->block_size * operation->block_size;
03877     }
03878     else
03879     {
03880         expected_output_size = input_length;
03881     }
03882 
03883     if( output_size < expected_output_size )
03884     {
03885         status = PSA_ERROR_BUFFER_TOO_SMALL;
03886         goto exit;
03887     }
03888 
03889     ret = mbedtls_cipher_update( &operation->ctx.cipher, input,
03890                                  input_length, output, output_length );
03891     status = mbedtls_to_psa_error( ret );
03892 exit:
03893     if( status != PSA_SUCCESS )
03894         psa_cipher_abort( operation );
03895     return( status );
03896 }
03897 
03898 psa_status_t psa_cipher_finish( psa_cipher_operation_t *operation,
03899                                 uint8_t *output,
03900                                 size_t output_size,
03901                                 size_t *output_length )
03902 {
03903     psa_status_t status = PSA_ERROR_GENERIC_ERROR;
03904     int cipher_ret = MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE;
03905     uint8_t temp_output_buffer[MBEDTLS_MAX_BLOCK_LENGTH];
03906 
03907     if( ! operation->key_set )
03908     {
03909         return( PSA_ERROR_BAD_STATE );
03910     }
03911     if( operation->iv_required && ! operation->iv_set )
03912     {
03913         return( PSA_ERROR_BAD_STATE );
03914     }
03915 
03916     if( operation->ctx.cipher.operation == MBEDTLS_ENCRYPT &&
03917         operation->alg == PSA_ALG_CBC_NO_PADDING &&
03918         operation->ctx.cipher.unprocessed_len != 0 )
03919     {
03920             status = PSA_ERROR_INVALID_ARGUMENT;
03921             goto error;
03922     }
03923 
03924     cipher_ret = mbedtls_cipher_finish( &operation->ctx.cipher,
03925                                         temp_output_buffer,
03926                                         output_length );
03927     if( cipher_ret != 0 )
03928     {
03929         status = mbedtls_to_psa_error( cipher_ret );
03930         goto error;
03931     }
03932 
03933     if( *output_length == 0 )
03934         ; /* Nothing to copy. Note that output may be NULL in this case. */
03935     else if( output_size >= *output_length )
03936         memcpy( output, temp_output_buffer, *output_length );
03937     else
03938     {
03939         status = PSA_ERROR_BUFFER_TOO_SMALL;
03940         goto error;
03941     }
03942 
03943     mbedtls_platform_zeroize( temp_output_buffer, sizeof( temp_output_buffer ) );
03944     status = psa_cipher_abort( operation );
03945 
03946     return( status );
03947 
03948 error:
03949 
03950     *output_length = 0;
03951 
03952     mbedtls_platform_zeroize( temp_output_buffer, sizeof( temp_output_buffer ) );
03953     (void) psa_cipher_abort( operation );
03954 
03955     return( status );
03956 }
03957 
03958 psa_status_t psa_cipher_abort( psa_cipher_operation_t *operation )
03959 {
03960     if( operation->alg == 0 )
03961     {
03962         /* The object has (apparently) been initialized but it is not
03963          * in use. It's ok to call abort on such an object, and there's
03964          * nothing to do. */
03965         return( PSA_SUCCESS );
03966     }
03967 
03968     /* Sanity check (shouldn't happen: operation->alg should
03969      * always have been initialized to a valid value). */
03970     if( ! PSA_ALG_IS_CIPHER( operation->alg ) )
03971         return( PSA_ERROR_BAD_STATE );
03972 
03973     mbedtls_cipher_free( &operation->ctx.cipher );
03974 
03975     operation->alg = 0;
03976     operation->key_set = 0;
03977     operation->iv_set = 0;
03978     operation->iv_size = 0;
03979     operation->block_size = 0;
03980     operation->iv_required = 0;
03981 
03982     return( PSA_SUCCESS );
03983 }
03984 
03985 
03986 
03987 
03988 /****************************************************************/
03989 /* AEAD */
03990 /****************************************************************/
03991 
03992 typedef struct
03993 {
03994     psa_key_slot_t *slot;
03995     const mbedtls_cipher_info_t *cipher_info;
03996     union
03997     {
03998 #if defined(MBEDTLS_CCM_C)
03999         mbedtls_ccm_context ccm;
04000 #endif /* MBEDTLS_CCM_C */
04001 #if defined(MBEDTLS_GCM_C)
04002         mbedtls_gcm_context gcm;
04003 #endif /* MBEDTLS_GCM_C */
04004 #if defined(MBEDTLS_CHACHAPOLY_C)
04005         mbedtls_chachapoly_context chachapoly;
04006 #endif /* MBEDTLS_CHACHAPOLY_C */
04007     } ctx;
04008     psa_algorithm_t core_alg;
04009     uint8_t full_tag_length;
04010     uint8_t tag_length;
04011 } aead_operation_t;
04012 
04013 static void psa_aead_abort_internal( aead_operation_t *operation )
04014 {
04015     switch( operation->core_alg )
04016     {
04017 #if defined(MBEDTLS_CCM_C)
04018         case PSA_ALG_CCM:
04019             mbedtls_ccm_free( &operation->ctx.ccm );
04020             break;
04021 #endif /* MBEDTLS_CCM_C */
04022 #if defined(MBEDTLS_GCM_C)
04023         case PSA_ALG_GCM:
04024             mbedtls_gcm_free( &operation->ctx.gcm );
04025             break;
04026 #endif /* MBEDTLS_GCM_C */
04027     }
04028 }
04029 
04030 static psa_status_t psa_aead_setup( aead_operation_t *operation,
04031                                     psa_key_handle_t handle,
04032                                     psa_key_usage_t usage,
04033                                     psa_algorithm_t alg )
04034 {
04035     psa_status_t status;
04036     size_t key_bits;
04037     mbedtls_cipher_id_t cipher_id;
04038 
04039     status = psa_get_transparent_key( handle, &operation->slot, usage, alg );
04040     if( status != PSA_SUCCESS )
04041         return( status );
04042 
04043     key_bits = psa_get_key_slot_bits( operation->slot );
04044 
04045     operation->cipher_info =
04046         mbedtls_cipher_info_from_psa( alg, operation->slot->attr.type, key_bits,
04047                                       &cipher_id );
04048     if( operation->cipher_info == NULL )
04049         return( PSA_ERROR_NOT_SUPPORTED );
04050 
04051     switch( PSA_ALG_AEAD_WITH_TAG_LENGTH( alg, 0 ) )
04052     {
04053 #if defined(MBEDTLS_CCM_C)
04054         case PSA_ALG_AEAD_WITH_TAG_LENGTH( PSA_ALG_CCM, 0 ):
04055             operation->core_alg = PSA_ALG_CCM;
04056             operation->full_tag_length = 16;
04057             /* CCM allows the following tag lengths: 4, 6, 8, 10, 12, 14, 16.
04058              * The call to mbedtls_ccm_encrypt_and_tag or
04059              * mbedtls_ccm_auth_decrypt will validate the tag length. */
04060             if( PSA_BLOCK_CIPHER_BLOCK_SIZE( operation->slot->attr.type ) != 16 )
04061                 return( PSA_ERROR_INVALID_ARGUMENT );
04062             mbedtls_ccm_init( &operation->ctx.ccm );
04063             status = mbedtls_to_psa_error(
04064                 mbedtls_ccm_setkey( &operation->ctx.ccm, cipher_id,
04065                                     operation->slot->data.raw.data,
04066                                     (unsigned int) key_bits ) );
04067             if( status != 0 )
04068                 goto cleanup;
04069             break;
04070 #endif /* MBEDTLS_CCM_C */
04071 
04072 #if defined(MBEDTLS_GCM_C)
04073         case PSA_ALG_AEAD_WITH_TAG_LENGTH( PSA_ALG_GCM, 0 ):
04074             operation->core_alg = PSA_ALG_GCM;
04075             operation->full_tag_length = 16;
04076             /* GCM allows the following tag lengths: 4, 8, 12, 13, 14, 15, 16.
04077              * The call to mbedtls_gcm_crypt_and_tag or
04078              * mbedtls_gcm_auth_decrypt will validate the tag length. */
04079             if( PSA_BLOCK_CIPHER_BLOCK_SIZE( operation->slot->attr.type ) != 16 )
04080                 return( PSA_ERROR_INVALID_ARGUMENT );
04081             mbedtls_gcm_init( &operation->ctx.gcm );
04082             status = mbedtls_to_psa_error(
04083                 mbedtls_gcm_setkey( &operation->ctx.gcm, cipher_id,
04084                                     operation->slot->data.raw.data,
04085                                     (unsigned int) key_bits ) );
04086             if( status != 0 )
04087                 goto cleanup;
04088             break;
04089 #endif /* MBEDTLS_GCM_C */
04090 
04091 #if defined(MBEDTLS_CHACHAPOLY_C)
04092         case PSA_ALG_AEAD_WITH_TAG_LENGTH( PSA_ALG_CHACHA20_POLY1305, 0 ):
04093             operation->core_alg = PSA_ALG_CHACHA20_POLY1305;
04094             operation->full_tag_length = 16;
04095             /* We only support the default tag length. */
04096             if( alg != PSA_ALG_CHACHA20_POLY1305 )
04097                 return( PSA_ERROR_NOT_SUPPORTED );
04098             mbedtls_chachapoly_init( &operation->ctx.chachapoly );
04099             status = mbedtls_to_psa_error(
04100                 mbedtls_chachapoly_setkey( &operation->ctx.chachapoly,
04101                                            operation->slot->data.raw.data ) );
04102             if( status != 0 )
04103                 goto cleanup;
04104             break;
04105 #endif /* MBEDTLS_CHACHAPOLY_C */
04106 
04107         default:
04108             return( PSA_ERROR_NOT_SUPPORTED );
04109     }
04110 
04111     if( PSA_AEAD_TAG_LENGTH( alg ) > operation->full_tag_length )
04112     {
04113         status = PSA_ERROR_INVALID_ARGUMENT;
04114         goto cleanup;
04115     }
04116     operation->tag_length = PSA_AEAD_TAG_LENGTH( alg );
04117 
04118     return( PSA_SUCCESS );
04119 
04120 cleanup:
04121     psa_aead_abort_internal( operation );
04122     return( status );
04123 }
04124 
04125 psa_status_t psa_aead_encrypt( psa_key_handle_t handle,
04126                                psa_algorithm_t alg,
04127                                const uint8_t *nonce,
04128                                size_t nonce_length,
04129                                const uint8_t *additional_data,
04130                                size_t additional_data_length,
04131                                const uint8_t *plaintext,
04132                                size_t plaintext_length,
04133                                uint8_t *ciphertext,
04134                                size_t ciphertext_size,
04135                                size_t *ciphertext_length )
04136 {
04137     psa_status_t status;
04138     aead_operation_t operation;
04139     uint8_t *tag;
04140 
04141     *ciphertext_length = 0;
04142 
04143     status = psa_aead_setup( &operation, handle, PSA_KEY_USAGE_ENCRYPT, alg );
04144     if( status != PSA_SUCCESS )
04145         return( status );
04146 
04147     /* For all currently supported modes, the tag is at the end of the
04148      * ciphertext. */
04149     if( ciphertext_size < ( plaintext_length + operation.tag_length ) )
04150     {
04151         status = PSA_ERROR_BUFFER_TOO_SMALL;
04152         goto exit;
04153     }
04154     tag = ciphertext + plaintext_length;
04155 
04156 #if defined(MBEDTLS_GCM_C)
04157     if( operation.core_alg == PSA_ALG_GCM )
04158     {
04159         status = mbedtls_to_psa_error(
04160             mbedtls_gcm_crypt_and_tag( &operation.ctx.gcm,
04161                                        MBEDTLS_GCM_ENCRYPT,
04162                                        plaintext_length,
04163                                        nonce, nonce_length,
04164                                        additional_data, additional_data_length,
04165                                        plaintext, ciphertext,
04166                                        operation.tag_length, tag ) );
04167     }
04168     else
04169 #endif /* MBEDTLS_GCM_C */
04170 #if defined(MBEDTLS_CCM_C)
04171     if( operation.core_alg == PSA_ALG_CCM )
04172     {
04173         status = mbedtls_to_psa_error(
04174             mbedtls_ccm_encrypt_and_tag( &operation.ctx.ccm,
04175                                          plaintext_length,
04176                                          nonce, nonce_length,
04177                                          additional_data,
04178                                          additional_data_length,
04179                                          plaintext, ciphertext,
04180                                          tag, operation.tag_length ) );
04181     }
04182     else
04183 #endif /* MBEDTLS_CCM_C */
04184 #if defined(MBEDTLS_CHACHAPOLY_C)
04185     if( operation.core_alg == PSA_ALG_CHACHA20_POLY1305 )
04186     {
04187         if( nonce_length != 12 || operation.tag_length != 16 )
04188         {
04189             status = PSA_ERROR_NOT_SUPPORTED;
04190             goto exit;
04191         }
04192         status = mbedtls_to_psa_error(
04193             mbedtls_chachapoly_encrypt_and_tag( &operation.ctx.chachapoly,
04194                                                 plaintext_length,
04195                                                 nonce,
04196                                                 additional_data,
04197                                                 additional_data_length,
04198                                                 plaintext,
04199                                                 ciphertext,
04200                                                 tag ) );
04201     }
04202     else
04203 #endif /* MBEDTLS_CHACHAPOLY_C */
04204     {
04205         return( PSA_ERROR_NOT_SUPPORTED );
04206     }
04207 
04208     if( status != PSA_SUCCESS && ciphertext_size != 0 )
04209         memset( ciphertext, 0, ciphertext_size );
04210 
04211 exit:
04212     psa_aead_abort_internal( &operation );
04213     if( status == PSA_SUCCESS )
04214         *ciphertext_length = plaintext_length + operation.tag_length;
04215     return( status );
04216 }
04217 
04218 /* Locate the tag in a ciphertext buffer containing the encrypted data
04219  * followed by the tag. Return the length of the part preceding the tag in
04220  * *plaintext_length. This is the size of the plaintext in modes where
04221  * the encrypted data has the same size as the plaintext, such as
04222  * CCM and GCM. */
04223 static psa_status_t psa_aead_unpadded_locate_tag( size_t tag_length,
04224                                                   const uint8_t *ciphertext,
04225                                                   size_t ciphertext_length,
04226                                                   size_t plaintext_size,
04227                                                   const uint8_t **p_tag )
04228 {
04229     size_t payload_length;
04230     if( tag_length > ciphertext_length )
04231         return( PSA_ERROR_INVALID_ARGUMENT );
04232     payload_length = ciphertext_length - tag_length;
04233     if( payload_length > plaintext_size )
04234         return( PSA_ERROR_BUFFER_TOO_SMALL );
04235     *p_tag = ciphertext + payload_length;
04236     return( PSA_SUCCESS );
04237 }
04238 
04239 psa_status_t psa_aead_decrypt( psa_key_handle_t handle,
04240                                psa_algorithm_t alg,
04241                                const uint8_t *nonce,
04242                                size_t nonce_length,
04243                                const uint8_t *additional_data,
04244                                size_t additional_data_length,
04245                                const uint8_t *ciphertext,
04246                                size_t ciphertext_length,
04247                                uint8_t *plaintext,
04248                                size_t plaintext_size,
04249                                size_t *plaintext_length )
04250 {
04251     psa_status_t status;
04252     aead_operation_t operation;
04253     const uint8_t *tag = NULL;
04254 
04255     *plaintext_length = 0;
04256 
04257     status = psa_aead_setup( &operation, handle, PSA_KEY_USAGE_DECRYPT, alg );
04258     if( status != PSA_SUCCESS )
04259         return( status );
04260 
04261     status = psa_aead_unpadded_locate_tag( operation.tag_length,
04262                                            ciphertext, ciphertext_length,
04263                                            plaintext_size, &tag );
04264     if( status != PSA_SUCCESS )
04265         goto exit;
04266 
04267 #if defined(MBEDTLS_GCM_C)
04268     if( operation.core_alg == PSA_ALG_GCM )
04269     {
04270         status = mbedtls_to_psa_error(
04271             mbedtls_gcm_auth_decrypt( &operation.ctx.gcm,
04272                                       ciphertext_length - operation.tag_length,
04273                                       nonce, nonce_length,
04274                                       additional_data,
04275                                       additional_data_length,
04276                                       tag, operation.tag_length,
04277                                       ciphertext, plaintext ) );
04278     }
04279     else
04280 #endif /* MBEDTLS_GCM_C */
04281 #if defined(MBEDTLS_CCM_C)
04282     if( operation.core_alg == PSA_ALG_CCM )
04283     {
04284         status = mbedtls_to_psa_error(
04285             mbedtls_ccm_auth_decrypt( &operation.ctx.ccm,
04286                                       ciphertext_length - operation.tag_length,
04287                                       nonce, nonce_length,
04288                                       additional_data,
04289                                       additional_data_length,
04290                                       ciphertext, plaintext,
04291                                       tag, operation.tag_length ) );
04292     }
04293     else
04294 #endif /* MBEDTLS_CCM_C */
04295 #if defined(MBEDTLS_CHACHAPOLY_C)
04296     if( operation.core_alg == PSA_ALG_CHACHA20_POLY1305 )
04297     {
04298         if( nonce_length != 12 || operation.tag_length != 16 )
04299         {
04300             status = PSA_ERROR_NOT_SUPPORTED;
04301             goto exit;
04302         }
04303         status = mbedtls_to_psa_error(
04304             mbedtls_chachapoly_auth_decrypt( &operation.ctx.chachapoly,
04305                                              ciphertext_length - operation.tag_length,
04306                                              nonce,
04307                                              additional_data,
04308                                              additional_data_length,
04309                                              tag,
04310                                              ciphertext,
04311                                              plaintext ) );
04312     }
04313     else
04314 #endif /* MBEDTLS_CHACHAPOLY_C */
04315     {
04316         return( PSA_ERROR_NOT_SUPPORTED );
04317     }
04318 
04319     if( status != PSA_SUCCESS && plaintext_size != 0 )
04320         memset( plaintext, 0, plaintext_size );
04321 
04322 exit:
04323     psa_aead_abort_internal( &operation );
04324     if( status == PSA_SUCCESS )
04325         *plaintext_length = ciphertext_length - operation.tag_length;
04326     return( status );
04327 }
04328 
04329 
04330 
04331 /****************************************************************/
04332 /* Generators */
04333 /****************************************************************/
04334 
04335 #define HKDF_STATE_INIT 0 /* no input yet */
04336 #define HKDF_STATE_STARTED 1 /* got salt */
04337 #define HKDF_STATE_KEYED 2 /* got key */
04338 #define HKDF_STATE_OUTPUT 3 /* output started */
04339 
04340 static psa_algorithm_t psa_key_derivation_get_kdf_alg(
04341     const psa_key_derivation_operation_t *operation )
04342 {
04343     if ( PSA_ALG_IS_KEY_AGREEMENT( operation->alg ) )
04344         return( PSA_ALG_KEY_AGREEMENT_GET_KDF( operation->alg ) );
04345     else
04346         return( operation->alg );
04347 }
04348 
04349 
04350 psa_status_t psa_key_derivation_abort( psa_key_derivation_operation_t *operation )
04351 {
04352     psa_status_t status = PSA_SUCCESS;
04353     psa_algorithm_t kdf_alg = psa_key_derivation_get_kdf_alg( operation );
04354     if( kdf_alg == 0 )
04355     {
04356         /* The object has (apparently) been initialized but it is not
04357          * in use. It's ok to call abort on such an object, and there's
04358          * nothing to do. */
04359     }
04360     else
04361 #if defined(MBEDTLS_MD_C)
04362     if( PSA_ALG_IS_HKDF( kdf_alg ) )
04363     {
04364         mbedtls_free( operation->ctx.hkdf.info );
04365         status = psa_hmac_abort_internal( &operation->ctx.hkdf.hmac );
04366     }
04367     else if( PSA_ALG_IS_TLS12_PRF( kdf_alg ) ||
04368              /* TLS-1.2 PSK-to-MS KDF uses the same core as TLS-1.2 PRF */
04369              PSA_ALG_IS_TLS12_PSK_TO_MS( kdf_alg ) )
04370     {
04371         if( operation->ctx.tls12_prf.seed != NULL )
04372         {
04373             mbedtls_platform_zeroize( operation->ctx.tls12_prf.seed,
04374                                       operation->ctx.tls12_prf.seed_length );
04375             mbedtls_free( operation->ctx.tls12_prf.seed );
04376         }
04377 
04378         if( operation->ctx.tls12_prf.label != NULL )
04379         {
04380             mbedtls_platform_zeroize( operation->ctx.tls12_prf.label,
04381                                       operation->ctx.tls12_prf.label_length );
04382             mbedtls_free( operation->ctx.tls12_prf.label );
04383         }
04384 
04385         status = psa_hmac_abort_internal( &operation->ctx.tls12_prf.hmac );
04386 
04387         /* We leave the fields Ai and output_block to be erased safely by the
04388          * mbedtls_platform_zeroize() in the end of this function. */
04389     }
04390     else
04391 #endif /* MBEDTLS_MD_C */
04392     {
04393         status = PSA_ERROR_BAD_STATE;
04394     }
04395     mbedtls_platform_zeroize( operation, sizeof( *operation ) );
04396     return( status );
04397 }
04398 
04399 psa_status_t psa_key_derivation_get_capacity(const psa_key_derivation_operation_t *operation,
04400                                         size_t *capacity)
04401 {
04402     if( operation->alg == 0 )
04403     {
04404         /* This is a blank key derivation operation. */
04405         return PSA_ERROR_BAD_STATE;
04406     }
04407 
04408     *capacity = operation->capacity;
04409     return( PSA_SUCCESS );
04410 }
04411 
04412 psa_status_t psa_key_derivation_set_capacity( psa_key_derivation_operation_t *operation,
04413                                          size_t capacity )
04414 {
04415     if( operation->alg == 0 )
04416         return( PSA_ERROR_BAD_STATE );
04417     if( capacity > operation->capacity )
04418         return( PSA_ERROR_INVALID_ARGUMENT );
04419     operation->capacity = capacity;
04420     return( PSA_SUCCESS );
04421 }
04422 
04423 #if defined(MBEDTLS_MD_C)
04424 /* Read some bytes from an HKDF-based operation. This performs a chunk
04425  * of the expand phase of the HKDF algorithm. */
04426 static psa_status_t psa_key_derivation_hkdf_read( psa_hkdf_key_derivation_t *hkdf,
04427                                              psa_algorithm_t hash_alg,
04428                                              uint8_t *output,
04429                                              size_t output_length )
04430 {
04431     uint8_t hash_length = PSA_HASH_SIZE( hash_alg );
04432     psa_status_t status;
04433 
04434     if( hkdf->state < HKDF_STATE_KEYED || ! hkdf->info_set )
04435         return( PSA_ERROR_BAD_STATE );
04436     hkdf->state = HKDF_STATE_OUTPUT;
04437 
04438     while( output_length != 0 )
04439     {
04440         /* Copy what remains of the current block */
04441         uint8_t n = hash_length - hkdf->offset_in_block;
04442         if( n > output_length )
04443             n = (uint8_t) output_length;
04444         memcpy( output, hkdf->output_block + hkdf->offset_in_block, n );
04445         output += n;
04446         output_length -= n;
04447         hkdf->offset_in_block += n;
04448         if( output_length == 0 )
04449             break;
04450         /* We can't be wanting more output after block 0xff, otherwise
04451          * the capacity check in psa_key_derivation_output_bytes() would have
04452          * prevented this call. It could happen only if the operation
04453          * object was corrupted or if this function is called directly
04454          * inside the library. */
04455         if( hkdf->block_number == 0xff )
04456             return( PSA_ERROR_BAD_STATE );
04457 
04458         /* We need a new block */
04459         ++hkdf->block_number;
04460         hkdf->offset_in_block = 0;
04461         status = psa_hmac_setup_internal( &hkdf->hmac,
04462                                           hkdf->prk, hash_length,
04463                                           hash_alg );
04464         if( status != PSA_SUCCESS )
04465             return( status );
04466         if( hkdf->block_number != 1 )
04467         {
04468             status = psa_hash_update( &hkdf->hmac.hash_ctx,
04469                                       hkdf->output_block,
04470                                       hash_length );
04471             if( status != PSA_SUCCESS )
04472                 return( status );
04473         }
04474         status = psa_hash_update( &hkdf->hmac.hash_ctx,
04475                                   hkdf->info,
04476                                   hkdf->info_length );
04477         if( status != PSA_SUCCESS )
04478             return( status );
04479         status = psa_hash_update( &hkdf->hmac.hash_ctx,
04480                                   &hkdf->block_number, 1 );
04481         if( status != PSA_SUCCESS )
04482             return( status );
04483         status = psa_hmac_finish_internal( &hkdf->hmac,
04484                                            hkdf->output_block,
04485                                            sizeof( hkdf->output_block ) );
04486         if( status != PSA_SUCCESS )
04487             return( status );
04488     }
04489 
04490     return( PSA_SUCCESS );
04491 }
04492 
04493 static psa_status_t psa_key_derivation_tls12_prf_generate_next_block(
04494     psa_tls12_prf_key_derivation_t *tls12_prf,
04495     psa_algorithm_t alg )
04496 {
04497     psa_algorithm_t hash_alg = PSA_ALG_HKDF_GET_HASH( alg );
04498     uint8_t hash_length = PSA_HASH_SIZE( hash_alg );
04499     psa_hash_operation_t backup = PSA_HASH_OPERATION_INIT;
04500     psa_status_t status, cleanup_status;
04501 
04502     /* We can't be wanting more output after block 0xff, otherwise
04503      * the capacity check in psa_key_derivation_output_bytes() would have
04504      * prevented this call. It could happen only if the operation
04505      * object was corrupted or if this function is called directly
04506      * inside the library. */
04507     if( tls12_prf->block_number == 0xff )
04508         return( PSA_ERROR_CORRUPTION_DETECTED );
04509 
04510     /* We need a new block */
04511     ++tls12_prf->block_number;
04512     tls12_prf->left_in_block = hash_length;
04513 
04514     /* Recall the definition of the TLS-1.2-PRF from RFC 5246:
04515      *
04516      * PRF(secret, label, seed) = P_<hash>(secret, label + seed)
04517      *
04518      * P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
04519      *                        HMAC_hash(secret, A(2) + seed) +
04520      *                        HMAC_hash(secret, A(3) + seed) + ...
04521      *
04522      * A(0) = seed
04523      * A(i) = HMAC_hash(secret, A(i-1))
04524      *
04525      * The `psa_tls12_prf_key_derivation` structure saves the block
04526      * `HMAC_hash(secret, A(i) + seed)` from which the output
04527      * is currently extracted as `output_block` and where i is
04528      * `block_number`.
04529      */
04530 
04531     /* Save the hash context before using it, to preserve the hash state with
04532      * only the inner padding in it. We need this, because inner padding depends
04533      * on the key (secret in the RFC's terminology). */
04534     status = psa_hash_clone( &tls12_prf->hmac.hash_ctx, &backup );
04535     if( status != PSA_SUCCESS )
04536         goto cleanup;
04537 
04538     /* Calculate A(i) where i = tls12_prf->block_number. */
04539     if( tls12_prf->block_number == 1 )
04540     {
04541         /* A(1) = HMAC_hash(secret, A(0)), where A(0) = seed. (The RFC overloads
04542          * the variable seed and in this instance means it in the context of the
04543          * P_hash function, where seed = label + seed.) */
04544         status = psa_hash_update( &tls12_prf->hmac.hash_ctx,
04545                                   tls12_prf->label, tls12_prf->label_length );
04546         if( status != PSA_SUCCESS )
04547             goto cleanup;
04548         status = psa_hash_update( &tls12_prf->hmac.hash_ctx,
04549                                   tls12_prf->seed, tls12_prf->seed_length );
04550         if( status != PSA_SUCCESS )
04551             goto cleanup;
04552     }
04553     else
04554     {
04555         /* A(i) = HMAC_hash(secret, A(i-1)) */
04556         status = psa_hash_update( &tls12_prf->hmac.hash_ctx,
04557                                   tls12_prf->Ai, hash_length );
04558         if( status != PSA_SUCCESS )
04559             goto cleanup;
04560     }
04561 
04562     status = psa_hmac_finish_internal( &tls12_prf->hmac,
04563                                        tls12_prf->Ai, hash_length );
04564     if( status != PSA_SUCCESS )
04565         goto cleanup;
04566     status = psa_hash_clone( &backup, &tls12_prf->hmac.hash_ctx );
04567     if( status != PSA_SUCCESS )
04568         goto cleanup;
04569 
04570     /* Calculate HMAC_hash(secret, A(i) + label + seed). */
04571     status = psa_hash_update( &tls12_prf->hmac.hash_ctx,
04572                               tls12_prf->Ai, hash_length );
04573     if( status != PSA_SUCCESS )
04574         goto cleanup;
04575     status = psa_hash_update( &tls12_prf->hmac.hash_ctx,
04576                               tls12_prf->label, tls12_prf->label_length );
04577     if( status != PSA_SUCCESS )
04578         goto cleanup;
04579     status = psa_hash_update( &tls12_prf->hmac.hash_ctx,
04580                               tls12_prf->seed, tls12_prf->seed_length );
04581     if( status != PSA_SUCCESS )
04582         goto cleanup;
04583     status = psa_hmac_finish_internal( &tls12_prf->hmac,
04584                                        tls12_prf->output_block, hash_length );
04585     if( status != PSA_SUCCESS )
04586         goto cleanup;
04587     status = psa_hash_clone( &backup, &tls12_prf->hmac.hash_ctx );
04588     if( status != PSA_SUCCESS )
04589         goto cleanup;
04590 
04591 
04592 cleanup:
04593 
04594     cleanup_status = psa_hash_abort( &backup );
04595     if( status == PSA_SUCCESS && cleanup_status != PSA_SUCCESS )
04596         status = cleanup_status;
04597 
04598     return( status );
04599 }
04600 
04601 static psa_status_t psa_key_derivation_tls12_prf_read(
04602     psa_tls12_prf_key_derivation_t *tls12_prf,
04603     psa_algorithm_t alg,
04604     uint8_t *output,
04605     size_t output_length )
04606 {
04607     psa_algorithm_t hash_alg = PSA_ALG_TLS12_PRF_GET_HASH( alg );
04608     uint8_t hash_length = PSA_HASH_SIZE( hash_alg );
04609     psa_status_t status;
04610     uint8_t offset, length;
04611 
04612     while( output_length != 0 )
04613     {
04614         /* Check if we have fully processed the current block. */
04615         if( tls12_prf->left_in_block == 0 )
04616         {
04617             status = psa_key_derivation_tls12_prf_generate_next_block( tls12_prf,
04618                                                                        alg );
04619             if( status != PSA_SUCCESS )
04620                 return( status );
04621 
04622             continue;
04623         }
04624 
04625         if( tls12_prf->left_in_block > output_length )
04626             length = (uint8_t) output_length;
04627         else
04628             length = tls12_prf->left_in_block;
04629 
04630         offset = hash_length - tls12_prf->left_in_block;
04631         memcpy( output, tls12_prf->output_block + offset, length );
04632         output += length;
04633         output_length -= length;
04634         tls12_prf->left_in_block -= length;
04635     }
04636 
04637     return( PSA_SUCCESS );
04638 }
04639 #endif /* MBEDTLS_MD_C */
04640 
04641 psa_status_t psa_key_derivation_output_bytes(
04642     psa_key_derivation_operation_t *operation,
04643     uint8_t *output,
04644     size_t output_length )
04645 {
04646     psa_status_t status;
04647     psa_algorithm_t kdf_alg = psa_key_derivation_get_kdf_alg( operation );
04648 
04649     if( operation->alg == 0 )
04650     {
04651         /* This is a blank operation. */
04652         return PSA_ERROR_BAD_STATE;
04653     }
04654 
04655     if( output_length > operation->capacity )
04656     {
04657         operation->capacity = 0;
04658         /* Go through the error path to wipe all confidential data now
04659          * that the operation object is useless. */
04660         status = PSA_ERROR_INSUFFICIENT_DATA;
04661         goto exit;
04662     }
04663     if( output_length == 0 && operation->capacity == 0 )
04664     {
04665         /* Edge case: this is a finished operation, and 0 bytes
04666          * were requested. The right error in this case could
04667          * be either INSUFFICIENT_CAPACITY or BAD_STATE. Return
04668          * INSUFFICIENT_CAPACITY, which is right for a finished
04669          * operation, for consistency with the case when
04670          * output_length > 0. */
04671         return( PSA_ERROR_INSUFFICIENT_DATA );
04672     }
04673     operation->capacity -= output_length;
04674 
04675 #if defined(MBEDTLS_MD_C)
04676     if( PSA_ALG_IS_HKDF( kdf_alg ) )
04677     {
04678         psa_algorithm_t hash_alg = PSA_ALG_HKDF_GET_HASH( kdf_alg );
04679         status = psa_key_derivation_hkdf_read( &operation->ctx.hkdf, hash_alg,
04680                                           output, output_length );
04681     }
04682     else
04683     if( PSA_ALG_IS_TLS12_PRF( kdf_alg ) ||
04684              PSA_ALG_IS_TLS12_PSK_TO_MS( kdf_alg ) )
04685     {
04686         status = psa_key_derivation_tls12_prf_read( &operation->ctx.tls12_prf,
04687                                                kdf_alg, output,
04688                                                output_length );
04689     }
04690     else
04691 #endif /* MBEDTLS_MD_C */
04692     {
04693         return( PSA_ERROR_BAD_STATE );
04694     }
04695 
04696 exit:
04697     if( status != PSA_SUCCESS )
04698     {
04699         /* Preserve the algorithm upon errors, but clear all sensitive state.
04700          * This allows us to differentiate between exhausted operations and
04701          * blank operations, so we can return PSA_ERROR_BAD_STATE on blank
04702          * operations. */
04703         psa_algorithm_t alg = operation->alg;
04704         psa_key_derivation_abort( operation );
04705         operation->alg = alg;
04706         memset( output, '!', output_length );
04707     }
04708     return( status );
04709 }
04710 
04711 #if defined(MBEDTLS_DES_C)
04712 static void psa_des_set_key_parity( uint8_t *data, size_t data_size )
04713 {
04714     if( data_size >= 8 )
04715         mbedtls_des_key_set_parity( data );
04716     if( data_size >= 16 )
04717         mbedtls_des_key_set_parity( data + 8 );
04718     if( data_size >= 24 )
04719         mbedtls_des_key_set_parity( data + 16 );
04720 }
04721 #endif /* MBEDTLS_DES_C */
04722 
04723 static psa_status_t psa_generate_derived_key_internal(
04724     psa_key_slot_t *slot,
04725     size_t bits,
04726     psa_key_derivation_operation_t *operation )
04727 {
04728     uint8_t *data = NULL;
04729     size_t bytes = PSA_BITS_TO_BYTES( bits );
04730     psa_status_t status;
04731 
04732     if( ! key_type_is_raw_bytes( slot->attr.type ) )
04733         return( PSA_ERROR_INVALID_ARGUMENT );
04734     if( bits % 8 != 0 )
04735         return( PSA_ERROR_INVALID_ARGUMENT );
04736     data = mbedtls_calloc( 1, bytes );
04737     if( data == NULL )
04738         return( PSA_ERROR_INSUFFICIENT_MEMORY );
04739 
04740     status = psa_key_derivation_output_bytes( operation, data, bytes );
04741     if( status != PSA_SUCCESS )
04742         goto exit;
04743 #if defined(MBEDTLS_DES_C)
04744     if( slot->attr.type == PSA_KEY_TYPE_DES )
04745         psa_des_set_key_parity( data, bytes );
04746 #endif /* MBEDTLS_DES_C */
04747     status = psa_import_key_into_slot( slot, data, bytes );
04748 
04749 exit:
04750     mbedtls_free( data );
04751     return( status );
04752 }
04753 
04754 psa_status_t psa_key_derivation_output_key( const psa_key_attributes_t *attributes,
04755                                        psa_key_derivation_operation_t *operation,
04756                                        psa_key_handle_t *handle )
04757 {
04758     psa_status_t status;
04759     psa_key_slot_t *slot = NULL;
04760     psa_se_drv_table_entry_t *driver = NULL;
04761 
04762     /* Reject any attempt to create a zero-length key so that we don't
04763      * risk tripping up later, e.g. on a malloc(0) that returns NULL. */
04764     if( psa_get_key_bits( attributes ) == 0 )
04765         return( PSA_ERROR_INVALID_ARGUMENT );
04766 
04767     if( ! operation->can_output_key )
04768         return( PSA_ERROR_NOT_PERMITTED );
04769 
04770     status = psa_start_key_creation( PSA_KEY_CREATION_DERIVE,
04771                                      attributes, handle, &slot, &driver );
04772 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
04773     if( driver != NULL )
04774     {
04775         /* Deriving a key in a secure element is not implemented yet. */
04776         status = PSA_ERROR_NOT_SUPPORTED;
04777     }
04778 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
04779     if( status == PSA_SUCCESS )
04780     {
04781         status = psa_generate_derived_key_internal( slot,
04782                                                     attributes->core.bits,
04783                                                     operation );
04784     }
04785     if( status == PSA_SUCCESS )
04786         status = psa_finish_key_creation( slot, driver );
04787     if( status != PSA_SUCCESS )
04788     {
04789         psa_fail_key_creation( slot, driver );
04790         *handle = 0;
04791     }
04792     return( status );
04793 }
04794 
04795 
04796 
04797 /****************************************************************/
04798 /* Key derivation */
04799 /****************************************************************/
04800 
04801 static psa_status_t psa_key_derivation_setup_kdf(
04802     psa_key_derivation_operation_t *operation,
04803     psa_algorithm_t kdf_alg )
04804 {
04805     /* Make sure that operation->ctx is properly zero-initialised. (Macro
04806      * initialisers for this union leave some bytes unspecified.) */
04807     memset( &operation->ctx, 0, sizeof( operation->ctx ) );
04808 
04809     /* Make sure that kdf_alg is a supported key derivation algorithm. */
04810 #if defined(MBEDTLS_MD_C)
04811     if( PSA_ALG_IS_HKDF( kdf_alg ) ||
04812         PSA_ALG_IS_TLS12_PRF( kdf_alg ) ||
04813         PSA_ALG_IS_TLS12_PSK_TO_MS( kdf_alg ) )
04814     {
04815         psa_algorithm_t hash_alg = PSA_ALG_HKDF_GET_HASH( kdf_alg );
04816         size_t hash_size = PSA_HASH_SIZE( hash_alg );
04817         if( hash_size == 0 )
04818             return( PSA_ERROR_NOT_SUPPORTED );
04819         if( ( PSA_ALG_IS_TLS12_PRF( kdf_alg ) ||
04820               PSA_ALG_IS_TLS12_PSK_TO_MS( kdf_alg ) ) &&
04821             ! ( hash_alg == PSA_ALG_SHA_256 || hash_alg == PSA_ALG_SHA_384 ) )
04822         {
04823             return( PSA_ERROR_NOT_SUPPORTED );
04824         }
04825         operation->capacity = 255 * hash_size;
04826         return( PSA_SUCCESS );
04827     }
04828 #endif /* MBEDTLS_MD_C */
04829     else
04830         return( PSA_ERROR_NOT_SUPPORTED );
04831 }
04832 
04833 psa_status_t psa_key_derivation_setup( psa_key_derivation_operation_t *operation,
04834                                        psa_algorithm_t alg )
04835 {
04836     psa_status_t status;
04837 
04838     if( operation->alg != 0 )
04839         return( PSA_ERROR_BAD_STATE );
04840 
04841     if( PSA_ALG_IS_RAW_KEY_AGREEMENT( alg ) )
04842         return( PSA_ERROR_INVALID_ARGUMENT );
04843     else if( PSA_ALG_IS_KEY_AGREEMENT( alg ) )
04844     {
04845         psa_algorithm_t kdf_alg = PSA_ALG_KEY_AGREEMENT_GET_KDF( alg );
04846         status = psa_key_derivation_setup_kdf( operation, kdf_alg );
04847     }
04848     else if( PSA_ALG_IS_KEY_DERIVATION( alg ) )
04849     {
04850         status = psa_key_derivation_setup_kdf( operation, alg );
04851     }
04852     else
04853         return( PSA_ERROR_INVALID_ARGUMENT );
04854 
04855     if( status == PSA_SUCCESS )
04856         operation->alg = alg;
04857     return( status );
04858 }
04859 
04860 #if defined(MBEDTLS_MD_C)
04861 static psa_status_t psa_hkdf_input( psa_hkdf_key_derivation_t *hkdf,
04862                                     psa_algorithm_t hash_alg,
04863                                     psa_key_derivation_step_t step,
04864                                     const uint8_t *data,
04865                                     size_t data_length )
04866 {
04867     psa_status_t status;
04868     switch( step )
04869     {
04870         case PSA_KEY_DERIVATION_INPUT_SALT:
04871             if( hkdf->state != HKDF_STATE_INIT )
04872                 return( PSA_ERROR_BAD_STATE );
04873             status = psa_hmac_setup_internal( &hkdf->hmac,
04874                                               data, data_length,
04875                                               hash_alg );
04876             if( status != PSA_SUCCESS )
04877                 return( status );
04878             hkdf->state = HKDF_STATE_STARTED;
04879             return( PSA_SUCCESS );
04880         case PSA_KEY_DERIVATION_INPUT_SECRET:
04881             /* If no salt was provided, use an empty salt. */
04882             if( hkdf->state == HKDF_STATE_INIT )
04883             {
04884                 status = psa_hmac_setup_internal( &hkdf->hmac,
04885                                                   NULL, 0,
04886                                                   hash_alg );
04887                 if( status != PSA_SUCCESS )
04888                     return( status );
04889                 hkdf->state = HKDF_STATE_STARTED;
04890             }
04891             if( hkdf->state != HKDF_STATE_STARTED )
04892                 return( PSA_ERROR_BAD_STATE );
04893             status = psa_hash_update( &hkdf->hmac.hash_ctx,
04894                                       data, data_length );
04895             if( status != PSA_SUCCESS )
04896                 return( status );
04897             status = psa_hmac_finish_internal( &hkdf->hmac,
04898                                                hkdf->prk,
04899                                                sizeof( hkdf->prk ) );
04900             if( status != PSA_SUCCESS )
04901                 return( status );
04902             hkdf->offset_in_block = PSA_HASH_SIZE( hash_alg );
04903             hkdf->block_number = 0;
04904             hkdf->state = HKDF_STATE_KEYED;
04905             return( PSA_SUCCESS );
04906         case PSA_KEY_DERIVATION_INPUT_INFO:
04907             if( hkdf->state == HKDF_STATE_OUTPUT )
04908                 return( PSA_ERROR_BAD_STATE );
04909             if( hkdf->info_set )
04910                 return( PSA_ERROR_BAD_STATE );
04911             hkdf->info_length = data_length;
04912             if( data_length != 0 )
04913             {
04914                 hkdf->info = mbedtls_calloc( 1, data_length );
04915                 if( hkdf->info == NULL )
04916                     return( PSA_ERROR_INSUFFICIENT_MEMORY );
04917                 memcpy( hkdf->info, data, data_length );
04918             }
04919             hkdf->info_set = 1;
04920             return( PSA_SUCCESS );
04921         default:
04922             return( PSA_ERROR_INVALID_ARGUMENT );
04923     }
04924 }
04925 
04926 static psa_status_t psa_tls12_prf_set_seed( psa_tls12_prf_key_derivation_t *prf,
04927                                             const uint8_t *data,
04928                                             size_t data_length )
04929 {
04930     if( prf->state != TLS12_PRF_STATE_INIT )
04931         return( PSA_ERROR_BAD_STATE );
04932 
04933     if( data_length != 0 )
04934     {
04935         prf->seed = mbedtls_calloc( 1, data_length );
04936         if( prf->seed == NULL )
04937             return( PSA_ERROR_INSUFFICIENT_MEMORY );
04938 
04939         memcpy( prf->seed, data, data_length );
04940         prf->seed_length = data_length;
04941     }
04942 
04943     prf->state = TLS12_PRF_STATE_SEED_SET;
04944 
04945     return( PSA_SUCCESS );
04946 }
04947 
04948 static psa_status_t psa_tls12_prf_set_key( psa_tls12_prf_key_derivation_t *prf,
04949                                            psa_algorithm_t hash_alg,
04950                                            const uint8_t *data,
04951                                            size_t data_length )
04952 {
04953     psa_status_t status;
04954     if( prf->state != TLS12_PRF_STATE_SEED_SET )
04955         return( PSA_ERROR_BAD_STATE );
04956 
04957     status = psa_hmac_setup_internal( &prf->hmac, data, data_length, hash_alg );
04958     if( status != PSA_SUCCESS )
04959         return( status );
04960 
04961     prf->state = TLS12_PRF_STATE_KEY_SET;
04962 
04963     return( PSA_SUCCESS );
04964 }
04965 
04966 static psa_status_t psa_tls12_prf_psk_to_ms_set_key(
04967     psa_tls12_prf_key_derivation_t *prf,
04968     psa_algorithm_t hash_alg,
04969     const uint8_t *data,
04970     size_t data_length )
04971 {
04972     psa_status_t status;
04973     uint8_t pms[ 4 + 2 * PSA_ALG_TLS12_PSK_TO_MS_MAX_PSK_LEN ];
04974     uint8_t *cur = pms;
04975 
04976     if( data_length > PSA_ALG_TLS12_PSK_TO_MS_MAX_PSK_LEN )
04977         return( PSA_ERROR_INVALID_ARGUMENT );
04978 
04979     /* Quoting RFC 4279, Section 2:
04980      *
04981      * The premaster secret is formed as follows: if the PSK is N octets
04982      * long, concatenate a uint16 with the value N, N zero octets, a second
04983      * uint16 with the value N, and the PSK itself.
04984      */
04985 
04986     *cur++ = ( data_length >> 8 ) & 0xff;
04987     *cur++ = ( data_length >> 0 ) & 0xff;
04988     memset( cur, 0, data_length );
04989     cur += data_length;
04990     *cur++ = pms[0];
04991     *cur++ = pms[1];
04992     memcpy( cur, data, data_length );
04993     cur += data_length;
04994 
04995     status = psa_tls12_prf_set_key( prf, hash_alg, pms, cur - pms );
04996 
04997     mbedtls_platform_zeroize( pms, sizeof( pms ) );
04998     return( status );
04999 }
05000 
05001 static psa_status_t psa_tls12_prf_set_label( psa_tls12_prf_key_derivation_t *prf,
05002                                              const uint8_t *data,
05003                                              size_t data_length )
05004 {
05005     if( prf->state != TLS12_PRF_STATE_KEY_SET )
05006         return( PSA_ERROR_BAD_STATE );
05007 
05008     if( data_length != 0 )
05009     {
05010         prf->label = mbedtls_calloc( 1, data_length );
05011         if( prf->label == NULL )
05012             return( PSA_ERROR_INSUFFICIENT_MEMORY );
05013 
05014         memcpy( prf->label, data, data_length );
05015         prf->label_length = data_length;
05016     }
05017 
05018     prf->state = TLS12_PRF_STATE_LABEL_SET;
05019 
05020     return( PSA_SUCCESS );
05021 }
05022 
05023 static psa_status_t psa_tls12_prf_input( psa_tls12_prf_key_derivation_t *prf,
05024                                          psa_algorithm_t hash_alg,
05025                                          psa_key_derivation_step_t step,
05026                                          const uint8_t *data,
05027                                          size_t data_length )
05028 {
05029     switch( step )
05030     {
05031         case PSA_KEY_DERIVATION_INPUT_SEED:
05032             return( psa_tls12_prf_set_seed( prf, data, data_length ) );
05033         case PSA_KEY_DERIVATION_INPUT_SECRET:
05034             return( psa_tls12_prf_set_key( prf, hash_alg, data, data_length ) );
05035         case PSA_KEY_DERIVATION_INPUT_LABEL:
05036             return( psa_tls12_prf_set_label( prf, data, data_length ) );
05037         default:
05038             return( PSA_ERROR_INVALID_ARGUMENT );
05039     }
05040 }
05041 
05042 static psa_status_t psa_tls12_prf_psk_to_ms_input(
05043     psa_tls12_prf_key_derivation_t *prf,
05044     psa_algorithm_t hash_alg,
05045     psa_key_derivation_step_t step,
05046     const uint8_t *data,
05047     size_t data_length )
05048 {
05049     if( step == PSA_KEY_DERIVATION_INPUT_SECRET )
05050     {
05051         return( psa_tls12_prf_psk_to_ms_set_key( prf, hash_alg,
05052                                                  data, data_length ) );
05053     }
05054 
05055     return( psa_tls12_prf_input( prf, hash_alg, step, data, data_length ) );
05056 }
05057 #endif /* MBEDTLS_MD_C */
05058 
05059 /** Check whether the given key type is acceptable for the given
05060  * input step of a key derivation.
05061  *
05062  * Secret inputs must have the type #PSA_KEY_TYPE_DERIVE.
05063  * Non-secret inputs must have the type #PSA_KEY_TYPE_RAW_DATA.
05064  * Both secret and non-secret inputs can alternatively have the type
05065  * #PSA_KEY_TYPE_NONE, which is never the type of a key object, meaning
05066  * that the input was passed as a buffer rather than via a key object.
05067  */
05068 static int psa_key_derivation_check_input_type(
05069     psa_key_derivation_step_t step,
05070     psa_key_type_t key_type )
05071 {
05072     switch( step )
05073     {
05074         case PSA_KEY_DERIVATION_INPUT_SECRET:
05075             if( key_type == PSA_KEY_TYPE_DERIVE )
05076                 return( PSA_SUCCESS );
05077             if( key_type == PSA_KEY_TYPE_NONE )
05078                 return( PSA_SUCCESS );
05079             break;
05080         case PSA_KEY_DERIVATION_INPUT_LABEL:
05081         case PSA_KEY_DERIVATION_INPUT_SALT:
05082         case PSA_KEY_DERIVATION_INPUT_INFO:
05083         case PSA_KEY_DERIVATION_INPUT_SEED:
05084             if( key_type == PSA_KEY_TYPE_RAW_DATA )
05085                 return( PSA_SUCCESS );
05086             if( key_type == PSA_KEY_TYPE_NONE )
05087                 return( PSA_SUCCESS );
05088             break;
05089     }
05090     return( PSA_ERROR_INVALID_ARGUMENT );
05091 }
05092 
05093 static psa_status_t psa_key_derivation_input_internal(
05094     psa_key_derivation_operation_t *operation,
05095     psa_key_derivation_step_t step,
05096     psa_key_type_t key_type,
05097     const uint8_t *data,
05098     size_t data_length )
05099 {
05100     psa_status_t status;
05101     psa_algorithm_t kdf_alg = psa_key_derivation_get_kdf_alg( operation );
05102 
05103     status = psa_key_derivation_check_input_type( step, key_type );
05104     if( status != PSA_SUCCESS )
05105         goto exit;
05106 
05107 #if defined(MBEDTLS_MD_C)
05108     if( PSA_ALG_IS_HKDF( kdf_alg ) )
05109     {
05110         status = psa_hkdf_input( &operation->ctx.hkdf,
05111                                  PSA_ALG_HKDF_GET_HASH( kdf_alg ),
05112                                  step, data, data_length );
05113     }
05114     else if( PSA_ALG_IS_TLS12_PRF( kdf_alg ) )
05115     {
05116         status = psa_tls12_prf_input( &operation->ctx.tls12_prf,
05117                                       PSA_ALG_HKDF_GET_HASH( kdf_alg ),
05118                                       step, data, data_length );
05119     }
05120     else if( PSA_ALG_IS_TLS12_PSK_TO_MS( kdf_alg ) )
05121     {
05122         status = psa_tls12_prf_psk_to_ms_input( &operation->ctx.tls12_prf,
05123                                                 PSA_ALG_HKDF_GET_HASH( kdf_alg ),
05124                                                 step, data, data_length );
05125     }
05126     else
05127 #endif /* MBEDTLS_MD_C */
05128     {
05129         /* This can't happen unless the operation object was not initialized */
05130         return( PSA_ERROR_BAD_STATE );
05131     }
05132 
05133 exit:
05134     if( status != PSA_SUCCESS )
05135         psa_key_derivation_abort( operation );
05136     return( status );
05137 }
05138 
05139 psa_status_t psa_key_derivation_input_bytes(
05140     psa_key_derivation_operation_t *operation,
05141     psa_key_derivation_step_t step,
05142     const uint8_t *data,
05143     size_t data_length )
05144 {
05145     return( psa_key_derivation_input_internal( operation, step,
05146                                                PSA_KEY_TYPE_NONE,
05147                                                data, data_length ) );
05148 }
05149 
05150 psa_status_t psa_key_derivation_input_key(
05151     psa_key_derivation_operation_t *operation,
05152     psa_key_derivation_step_t step,
05153     psa_key_handle_t handle )
05154 {
05155     psa_key_slot_t *slot;
05156     psa_status_t status;
05157 
05158     status = psa_get_transparent_key( handle, &slot,
05159                                       PSA_KEY_USAGE_DERIVE,
05160                                       operation->alg );
05161     if( status != PSA_SUCCESS )
05162     {
05163         psa_key_derivation_abort( operation );
05164         return( status );
05165     }
05166 
05167     /* Passing a key object as a SECRET input unlocks the permission
05168      * to output to a key object. */
05169     if( step == PSA_KEY_DERIVATION_INPUT_SECRET )
05170         operation->can_output_key = 1;
05171 
05172     return( psa_key_derivation_input_internal( operation,
05173                                                step, slot->attr.type,
05174                                                slot->data.raw.data,
05175                                                slot->data.raw.bytes ) );
05176 }
05177 
05178 
05179 
05180 /****************************************************************/
05181 /* Key agreement */
05182 /****************************************************************/
05183 
05184 #if defined(MBEDTLS_ECDH_C)
05185 static psa_status_t psa_key_agreement_ecdh( const uint8_t *peer_key,
05186                                             size_t peer_key_length,
05187                                             const mbedtls_ecp_keypair *our_key,
05188                                             uint8_t *shared_secret,
05189                                             size_t shared_secret_size,
05190                                             size_t *shared_secret_length )
05191 {
05192     mbedtls_ecp_keypair *their_key = NULL;
05193     mbedtls_ecdh_context ecdh;
05194     psa_status_t status;
05195     mbedtls_ecdh_init( &ecdh );
05196 
05197     status = psa_import_ec_public_key(
05198         mbedtls_ecc_group_to_psa( our_key->grp .id  ),
05199         peer_key, peer_key_length,
05200         &their_key );
05201     if( status != PSA_SUCCESS )
05202         goto exit;
05203 
05204     status = mbedtls_to_psa_error(
05205         mbedtls_ecdh_get_params( &ecdh, their_key, MBEDTLS_ECDH_THEIRS ) );
05206     if( status != PSA_SUCCESS )
05207         goto exit;
05208     status = mbedtls_to_psa_error(
05209         mbedtls_ecdh_get_params( &ecdh, our_key, MBEDTLS_ECDH_OURS ) );
05210     if( status != PSA_SUCCESS )
05211         goto exit;
05212 
05213     status = mbedtls_to_psa_error(
05214         mbedtls_ecdh_calc_secret( &ecdh,
05215                                   shared_secret_length,
05216                                   shared_secret, shared_secret_size,
05217                                   mbedtls_ctr_drbg_random,
05218                                   &global_data.ctr_drbg ) );
05219 
05220 exit:
05221     mbedtls_ecdh_free( &ecdh );
05222     mbedtls_ecp_keypair_free( their_key );
05223     mbedtls_free( their_key );
05224     return( status );
05225 }
05226 #endif /* MBEDTLS_ECDH_C */
05227 
05228 #define PSA_KEY_AGREEMENT_MAX_SHARED_SECRET_SIZE MBEDTLS_ECP_MAX_BYTES
05229 
05230 static psa_status_t psa_key_agreement_raw_internal( psa_algorithm_t alg,
05231                                                     psa_key_slot_t *private_key,
05232                                                     const uint8_t *peer_key,
05233                                                     size_t peer_key_length,
05234                                                     uint8_t *shared_secret,
05235                                                     size_t shared_secret_size,
05236                                                     size_t *shared_secret_length )
05237 {
05238     switch( alg )
05239     {
05240 #if defined(MBEDTLS_ECDH_C)
05241         case PSA_ALG_ECDH:
05242             if( ! PSA_KEY_TYPE_IS_ECC_KEY_PAIR( private_key->attr.type ) )
05243                 return( PSA_ERROR_INVALID_ARGUMENT );
05244             return( psa_key_agreement_ecdh( peer_key, peer_key_length,
05245                                             private_key->data.ecp,
05246                                             shared_secret, shared_secret_size,
05247                                             shared_secret_length ) );
05248 #endif /* MBEDTLS_ECDH_C */
05249         default:
05250             (void) private_key;
05251             (void) peer_key;
05252             (void) peer_key_length;
05253             (void) shared_secret;
05254             (void) shared_secret_size;
05255             (void) shared_secret_length;
05256             return( PSA_ERROR_NOT_SUPPORTED );
05257     }
05258 }
05259 
05260 /* Note that if this function fails, you must call psa_key_derivation_abort()
05261  * to potentially free embedded data structures and wipe confidential data.
05262  */
05263 static psa_status_t psa_key_agreement_internal( psa_key_derivation_operation_t *operation,
05264                                                 psa_key_derivation_step_t step,
05265                                                 psa_key_slot_t *private_key,
05266                                                 const uint8_t *peer_key,
05267                                                 size_t peer_key_length )
05268 {
05269     psa_status_t status;
05270     uint8_t shared_secret[PSA_KEY_AGREEMENT_MAX_SHARED_SECRET_SIZE];
05271     size_t shared_secret_length = 0;
05272     psa_algorithm_t ka_alg = PSA_ALG_KEY_AGREEMENT_GET_BASE( operation->alg );
05273 
05274     /* Step 1: run the secret agreement algorithm to generate the shared
05275      * secret. */
05276     status = psa_key_agreement_raw_internal( ka_alg,
05277                                              private_key,
05278                                              peer_key, peer_key_length,
05279                                              shared_secret,
05280                                              sizeof( shared_secret ),
05281                                              &shared_secret_length );
05282     if( status != PSA_SUCCESS )
05283         goto exit;
05284 
05285     /* Step 2: set up the key derivation to generate key material from
05286      * the shared secret. A shared secret is permitted wherever a key
05287      * of type DERIVE is permitted. */
05288     status = psa_key_derivation_input_internal( operation, step,
05289                                                 PSA_KEY_TYPE_DERIVE,
05290                                                 shared_secret,
05291                                                 shared_secret_length );
05292 
05293 exit:
05294     mbedtls_platform_zeroize( shared_secret, shared_secret_length );
05295     return( status );
05296 }
05297 
05298 psa_status_t psa_key_derivation_key_agreement( psa_key_derivation_operation_t *operation,
05299                                                psa_key_derivation_step_t step,
05300                                                psa_key_handle_t private_key,
05301                                                const uint8_t *peer_key,
05302                                                size_t peer_key_length )
05303 {
05304     psa_key_slot_t *slot;
05305     psa_status_t status;
05306     if( ! PSA_ALG_IS_KEY_AGREEMENT( operation->alg ) )
05307         return( PSA_ERROR_INVALID_ARGUMENT );
05308     status = psa_get_transparent_key( private_key, &slot,
05309                                       PSA_KEY_USAGE_DERIVE, operation->alg );
05310     if( status != PSA_SUCCESS )
05311         return( status );
05312     status = psa_key_agreement_internal( operation, step,
05313                                          slot,
05314                                          peer_key, peer_key_length );
05315     if( status != PSA_SUCCESS )
05316         psa_key_derivation_abort( operation );
05317     return( status );
05318 }
05319 
05320 psa_status_t psa_raw_key_agreement( psa_algorithm_t alg,
05321                                     psa_key_handle_t private_key,
05322                                     const uint8_t *peer_key,
05323                                     size_t peer_key_length,
05324                                     uint8_t *output,
05325                                     size_t output_size,
05326                                     size_t *output_length )
05327 {
05328     psa_key_slot_t *slot;
05329     psa_status_t status;
05330 
05331     if( ! PSA_ALG_IS_KEY_AGREEMENT( alg ) )
05332     {
05333         status = PSA_ERROR_INVALID_ARGUMENT;
05334         goto exit;
05335     }
05336     status = psa_get_transparent_key( private_key, &slot,
05337                                       PSA_KEY_USAGE_DERIVE, alg );
05338     if( status != PSA_SUCCESS )
05339         goto exit;
05340 
05341     status = psa_key_agreement_raw_internal( alg, slot,
05342                                              peer_key, peer_key_length,
05343                                              output, output_size,
05344                                              output_length );
05345 
05346 exit:
05347     if( status != PSA_SUCCESS )
05348     {
05349         /* If an error happens and is not handled properly, the output
05350          * may be used as a key to protect sensitive data. Arrange for such
05351          * a key to be random, which is likely to result in decryption or
05352          * verification errors. This is better than filling the buffer with
05353          * some constant data such as zeros, which would result in the data
05354          * being protected with a reproducible, easily knowable key.
05355          */
05356         psa_generate_random( output, output_size );
05357         *output_length = output_size;
05358     }
05359     return( status );
05360 }
05361 
05362 
05363 /****************************************************************/
05364 /* Random generation */
05365 /****************************************************************/
05366 
05367 psa_status_t psa_generate_random( uint8_t *output,
05368                                   size_t output_size )
05369 {
05370     int ret;
05371     GUARD_MODULE_INITIALIZED;
05372 
05373     while( output_size > MBEDTLS_CTR_DRBG_MAX_REQUEST )
05374     {
05375         ret = mbedtls_ctr_drbg_random( &global_data.ctr_drbg,
05376                                        output,
05377                                        MBEDTLS_CTR_DRBG_MAX_REQUEST );
05378         if( ret != 0 )
05379             return( mbedtls_to_psa_error( ret ) );
05380         output += MBEDTLS_CTR_DRBG_MAX_REQUEST;
05381         output_size -= MBEDTLS_CTR_DRBG_MAX_REQUEST;
05382     }
05383 
05384     ret = mbedtls_ctr_drbg_random( &global_data.ctr_drbg, output, output_size );
05385     return( mbedtls_to_psa_error( ret ) );
05386 }
05387 
05388 #if defined(MBEDTLS_PSA_INJECT_ENTROPY)
05389 #include "mbedtls/entropy_poll.h"
05390 
05391 psa_status_t mbedtls_psa_inject_entropy( const uint8_t *seed,
05392                                          size_t seed_size )
05393 {
05394     if( global_data.initialized )
05395         return( PSA_ERROR_NOT_PERMITTED );
05396 
05397     if( ( ( seed_size < MBEDTLS_ENTROPY_MIN_PLATFORM ) ||
05398           ( seed_size < MBEDTLS_ENTROPY_BLOCK_SIZE ) ) ||
05399           ( seed_size > MBEDTLS_ENTROPY_MAX_SEED_SIZE ) )
05400             return( PSA_ERROR_INVALID_ARGUMENT );
05401 
05402     return( mbedtls_psa_storage_inject_entropy( seed, seed_size ) );
05403 }
05404 #endif /* MBEDTLS_PSA_INJECT_ENTROPY */
05405 
05406 #if defined(MBEDTLS_RSA_C) && defined(MBEDTLS_GENPRIME)
05407 static psa_status_t psa_read_rsa_exponent( const uint8_t *domain_parameters,
05408                                            size_t domain_parameters_size,
05409                                            int *exponent )
05410 {
05411     size_t i;
05412     uint32_t acc = 0;
05413 
05414     if( domain_parameters_size == 0 )
05415     {
05416         *exponent = 65537;
05417         return( PSA_SUCCESS );
05418     }
05419 
05420     /* Mbed TLS encodes the public exponent as an int. For simplicity, only
05421      * support values that fit in a 32-bit integer, which is larger than
05422      * int on just about every platform anyway. */
05423     if( domain_parameters_size > sizeof( acc ) )
05424         return( PSA_ERROR_NOT_SUPPORTED );
05425     for( i = 0; i < domain_parameters_size; i++ )
05426         acc = ( acc << 8 ) | domain_parameters[i];
05427     if( acc > INT_MAX )
05428         return( PSA_ERROR_NOT_SUPPORTED );
05429     *exponent = acc;
05430     return( PSA_SUCCESS );
05431 }
05432 #endif /* MBEDTLS_RSA_C && MBEDTLS_GENPRIME */
05433 
05434 static psa_status_t psa_generate_key_internal(
05435     psa_key_slot_t *slot, size_t bits,
05436     const uint8_t *domain_parameters, size_t domain_parameters_size )
05437 {
05438     psa_key_type_t type = slot->attr.type;
05439 
05440     if( domain_parameters == NULL && domain_parameters_size != 0 )
05441         return( PSA_ERROR_INVALID_ARGUMENT );
05442 
05443     if( key_type_is_raw_bytes( type ) )
05444     {
05445         psa_status_t status;
05446         status = prepare_raw_data_slot( type, bits, &slot->data.raw );
05447         if( status != PSA_SUCCESS )
05448             return( status );
05449         status = psa_generate_random( slot->data.raw.data,
05450                                       slot->data.raw.bytes );
05451         if( status != PSA_SUCCESS )
05452             return( status );
05453 #if defined(MBEDTLS_DES_C)
05454         if( type == PSA_KEY_TYPE_DES )
05455             psa_des_set_key_parity( slot->data.raw.data,
05456                                     slot->data.raw.bytes );
05457 #endif /* MBEDTLS_DES_C */
05458     }
05459     else
05460 
05461 #if defined(MBEDTLS_RSA_C) && defined(MBEDTLS_GENPRIME)
05462     if ( type == PSA_KEY_TYPE_RSA_KEY_PAIR )
05463     {
05464         mbedtls_rsa_context *rsa;
05465         int ret;
05466         int exponent;
05467         psa_status_t status;
05468         if( bits > PSA_VENDOR_RSA_MAX_KEY_BITS )
05469             return( PSA_ERROR_NOT_SUPPORTED );
05470         /* Accept only byte-aligned keys, for the same reasons as
05471          * in psa_import_rsa_key(). */
05472         if( bits % 8 != 0 )
05473             return( PSA_ERROR_NOT_SUPPORTED );
05474         status = psa_read_rsa_exponent( domain_parameters,
05475                                         domain_parameters_size,
05476                                         &exponent );
05477         if( status != PSA_SUCCESS )
05478             return( status );
05479         rsa = mbedtls_calloc( 1, sizeof( *rsa ) );
05480         if( rsa == NULL )
05481             return( PSA_ERROR_INSUFFICIENT_MEMORY );
05482         mbedtls_rsa_init( rsa, MBEDTLS_RSA_PKCS_V15, MBEDTLS_MD_NONE );
05483         ret = mbedtls_rsa_gen_key( rsa,
05484                                    mbedtls_ctr_drbg_random,
05485                                    &global_data.ctr_drbg,
05486                                    (unsigned int) bits,
05487                                    exponent );
05488         if( ret != 0 )
05489         {
05490             mbedtls_rsa_free( rsa );
05491             mbedtls_free( rsa );
05492             return( mbedtls_to_psa_error( ret ) );
05493         }
05494         slot->data.rsa = rsa;
05495     }
05496     else
05497 #endif /* MBEDTLS_RSA_C && MBEDTLS_GENPRIME */
05498 
05499 #if defined(MBEDTLS_ECP_C)
05500     if ( PSA_KEY_TYPE_IS_ECC( type ) && PSA_KEY_TYPE_IS_KEY_PAIR( type ) )
05501     {
05502         psa_ecc_curve_t curve = PSA_KEY_TYPE_GET_CURVE( type );
05503         mbedtls_ecp_group_id grp_id = mbedtls_ecc_group_of_psa( curve );
05504         const mbedtls_ecp_curve_info *curve_info =
05505             mbedtls_ecp_curve_info_from_grp_id( grp_id );
05506         mbedtls_ecp_keypair *ecp;
05507         int ret;
05508         if( domain_parameters_size != 0 )
05509             return( PSA_ERROR_NOT_SUPPORTED );
05510         if( grp_id == MBEDTLS_ECP_DP_NONE || curve_info == NULL )
05511             return( PSA_ERROR_NOT_SUPPORTED );
05512         if( curve_info->bit_size  != bits )
05513             return( PSA_ERROR_INVALID_ARGUMENT );
05514         ecp = mbedtls_calloc( 1, sizeof( *ecp ) );
05515         if( ecp == NULL )
05516             return( PSA_ERROR_INSUFFICIENT_MEMORY );
05517         mbedtls_ecp_keypair_init( ecp );
05518         ret = mbedtls_ecp_gen_key( grp_id, ecp,
05519                                    mbedtls_ctr_drbg_random,
05520                                    &global_data.ctr_drbg );
05521         if( ret != 0 )
05522         {
05523             mbedtls_ecp_keypair_free( ecp );
05524             mbedtls_free( ecp );
05525             return( mbedtls_to_psa_error( ret ) );
05526         }
05527         slot->data.ecp = ecp;
05528     }
05529     else
05530 #endif /* MBEDTLS_ECP_C */
05531 
05532         return( PSA_ERROR_NOT_SUPPORTED );
05533 
05534     return( PSA_SUCCESS );
05535 }
05536 
05537 psa_status_t psa_generate_key( const psa_key_attributes_t *attributes,
05538                                psa_key_handle_t *handle )
05539 {
05540     psa_status_t status;
05541     psa_key_slot_t *slot = NULL;
05542     psa_se_drv_table_entry_t *driver = NULL;
05543 
05544     /* Reject any attempt to create a zero-length key so that we don't
05545      * risk tripping up later, e.g. on a malloc(0) that returns NULL. */
05546     if( psa_get_key_bits( attributes ) == 0 )
05547         return( PSA_ERROR_INVALID_ARGUMENT );
05548 
05549     status = psa_start_key_creation( PSA_KEY_CREATION_GENERATE,
05550                                      attributes, handle, &slot, &driver );
05551     if( status != PSA_SUCCESS )
05552         goto exit;
05553 
05554 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
05555     if( driver != NULL )
05556     {
05557         const psa_drv_se_t *drv = psa_get_se_driver_methods( driver );
05558         size_t pubkey_length = 0; /* We don't support this feature yet */
05559         if( drv->key_management == NULL ||
05560             drv->key_management->p_generate == NULL )
05561         {
05562             status = PSA_ERROR_NOT_SUPPORTED;
05563             goto exit;
05564         }
05565         status = drv->key_management->p_generate(
05566             psa_get_se_driver_context( driver ),
05567             slot->data.se.slot_number, attributes,
05568             NULL, 0, &pubkey_length );
05569     }
05570     else
05571 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
05572     {
05573         status = psa_generate_key_internal(
05574             slot, attributes->core.bits,
05575             attributes->domain_parameters, attributes->domain_parameters_size );
05576     }
05577 
05578 exit:
05579     if( status == PSA_SUCCESS )
05580         status = psa_finish_key_creation( slot, driver );
05581     if( status != PSA_SUCCESS )
05582     {
05583         psa_fail_key_creation( slot, driver );
05584         *handle = 0;
05585     }
05586     return( status );
05587 }
05588 
05589 
05590 
05591 /****************************************************************/
05592 /* Module setup */
05593 /****************************************************************/
05594 
05595 psa_status_t mbedtls_psa_crypto_configure_entropy_sources(
05596     void (* entropy_init )( mbedtls_entropy_context *ctx ),
05597     void (* entropy_free )( mbedtls_entropy_context *ctx ) )
05598 {
05599     if( global_data.rng_state != RNG_NOT_INITIALIZED )
05600         return( PSA_ERROR_BAD_STATE );
05601     global_data.entropy_init = entropy_init;
05602     global_data.entropy_free = entropy_free;
05603     return( PSA_SUCCESS );
05604 }
05605 
05606 void mbedtls_psa_crypto_free( void )
05607 {
05608     psa_wipe_all_key_slots( );
05609     if( global_data.rng_state != RNG_NOT_INITIALIZED )
05610     {
05611         mbedtls_ctr_drbg_free( &global_data.ctr_drbg );
05612         global_data.entropy_free( &global_data.entropy );
05613     }
05614     /* Wipe all remaining data, including configuration.
05615      * In particular, this sets all state indicator to the value
05616      * indicating "uninitialized". */
05617     mbedtls_platform_zeroize( &global_data, sizeof( global_data ) );
05618 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
05619     /* Unregister all secure element drivers, so that we restart from
05620      * a pristine state. */
05621     psa_unregister_all_se_drivers( );
05622 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
05623 }
05624 
05625 #if defined(PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS)
05626 /** Recover a transaction that was interrupted by a power failure.
05627  *
05628  * This function is called during initialization, before psa_crypto_init()
05629  * returns. If this function returns a failure status, the initialization
05630  * fails.
05631  */
05632 static psa_status_t psa_crypto_recover_transaction(
05633     const psa_crypto_transaction_t *transaction )
05634 {
05635     switch( transaction->unknown.type )
05636     {
05637         case PSA_CRYPTO_TRANSACTION_CREATE_KEY:
05638         case PSA_CRYPTO_TRANSACTION_DESTROY_KEY:
05639             /* TODO - fall through to the failure case until this
05640              * is implemented.
05641              * https://github.com/ARMmbed/mbed-crypto/issues/218
05642              */
05643         default:
05644             /* We found an unsupported transaction in the storage.
05645              * We don't know what state the storage is in. Give up. */
05646             return( PSA_ERROR_STORAGE_FAILURE );
05647     }
05648 }
05649 #endif /* PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS */
05650 
05651 psa_status_t psa_crypto_init( void )
05652 {
05653     psa_status_t status;
05654     const unsigned char drbg_seed[] = "PSA";
05655 
05656     /* Double initialization is explicitly allowed. */
05657     if( global_data.initialized != 0 )
05658         return( PSA_SUCCESS );
05659 
05660     /* Set default configuration if
05661      * mbedtls_psa_crypto_configure_entropy_sources() hasn't been called. */
05662     if( global_data.entropy_init == NULL )
05663         global_data.entropy_init = mbedtls_entropy_init;
05664     if( global_data.entropy_free == NULL )
05665         global_data.entropy_free = mbedtls_entropy_free;
05666 
05667     /* Initialize the random generator. */
05668     global_data.entropy_init( &global_data.entropy );
05669 #if defined(MBEDTLS_PSA_INJECT_ENTROPY) && \
05670     defined(MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES)
05671     /* The PSA entropy injection feature depends on using NV seed as an entropy
05672      * source. Add NV seed as an entropy source for PSA entropy injection. */
05673     mbedtls_entropy_add_source( &global_data.entropy,
05674                                 mbedtls_nv_seed_poll, NULL,
05675                                 MBEDTLS_ENTROPY_BLOCK_SIZE,
05676                                 MBEDTLS_ENTROPY_SOURCE_STRONG );
05677 #endif
05678     mbedtls_ctr_drbg_init( &global_data.ctr_drbg );
05679     global_data.rng_state = RNG_INITIALIZED;
05680     status = mbedtls_to_psa_error(
05681         mbedtls_ctr_drbg_seed( &global_data.ctr_drbg,
05682                                mbedtls_entropy_func,
05683                                &global_data.entropy,
05684                                drbg_seed, sizeof( drbg_seed ) - 1 ) );
05685     if( status != PSA_SUCCESS )
05686         goto exit;
05687     global_data.rng_state = RNG_SEEDED;
05688 
05689     status = psa_initialize_key_slots( );
05690     if( status != PSA_SUCCESS )
05691         goto exit;
05692 
05693 #if defined(MBEDTLS_PSA_CRYPTO_SE_C)
05694     status = psa_init_all_se_drivers( );
05695     if( status != PSA_SUCCESS )
05696         goto exit;
05697 #endif /* MBEDTLS_PSA_CRYPTO_SE_C */
05698 
05699 #if defined(PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS)
05700     status = psa_crypto_load_transaction( );
05701     if( status == PSA_SUCCESS )
05702     {
05703         status = psa_crypto_recover_transaction( &psa_crypto_transaction );
05704         if( status != PSA_SUCCESS )
05705             goto exit;
05706         status = psa_crypto_stop_transaction( );
05707     }
05708     else if( status == PSA_ERROR_DOES_NOT_EXIST )
05709     {
05710         /* There's no transaction to complete. It's all good. */
05711         status = PSA_SUCCESS;
05712     }
05713 #endif /* PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS */
05714 
05715     /* All done. */
05716     global_data.initialized = 1;
05717 
05718 exit:
05719     if( status != PSA_SUCCESS )
05720         mbedtls_psa_crypto_free( );
05721     return( status );
05722 }
05723 
05724 #endif /* MBEDTLS_PSA_CRYPTO_C */