Merge pull request #212 from ARMmbed/psa-integration-utilities_CRYPTO

Mbed TLS integration: Shared code between module-specific integration work
diff --git a/include/mbedtls/check_config.h b/include/mbedtls/check_config.h
index 21bede7..508c00a 100644
--- a/include/mbedtls/check_config.h
+++ b/include/mbedtls/check_config.h
@@ -670,6 +670,10 @@
 #endif
 #undef MBEDTLS_THREADING_IMPL
 
+#if defined(MBEDTLS_USE_PSA_CRYPTO) && !defined(MBEDTLS_PSA_CRYPTO_C)
+#error "MBEDTLS_USE_PSA_CRYPTO defined, but not all prerequisites"
+#endif
+
 #if defined(MBEDTLS_VERSION_FEATURES) && !defined(MBEDTLS_VERSION_C)
 #error "MBEDTLS_VERSION_FEATURES defined, but not all prerequisites"
 #endif
diff --git a/include/mbedtls/config.h b/include/mbedtls/config.h
index c1619fb..1f37d08 100644
--- a/include/mbedtls/config.h
+++ b/include/mbedtls/config.h
@@ -1617,6 +1617,24 @@
 //#define MBEDTLS_THREADING_PTHREAD
 
 /**
+ * \def MBEDTLS_USE_PSA_CRYPTO
+ *
+ * Make the X.509 and TLS library use PSA for cryptographic operations, see
+ * #MBEDTLS_PSA_CRYPTO_C.
+ *
+ * Note: this option is still in progress, the full X.509 and TLS modules are
+ * not covered yet, but parts that are not ported to PSA yet will still work
+ * as usual, so enabling this option should not break backwards compatibility.
+ *
+ * \warning  Support for PSA is still an experimental feature.
+ *           Any public API that depends on this option may change
+ *           at any time until this warning is removed.
+ *
+ * Requires: MBEDTLS_PSA_CRYPTO_C.
+ */
+//#define MBEDTLS_USE_PSA_CRYPTO
+
+/**
  * \def MBEDTLS_VERSION_FEATURES
  *
  * Allow run-time checking of compile-time enabled features. Thus allowing users
diff --git a/include/mbedtls/psa_util.h b/include/mbedtls/psa_util.h
new file mode 100644
index 0000000..5766133
--- /dev/null
+++ b/include/mbedtls/psa_util.h
@@ -0,0 +1,264 @@
+/**
+ * \file psa_util.h
+ *
+ * \brief Utility functions for the use of the PSA Crypto library.
+ *
+ * \warning This function is not part of the public API and may
+ *          change at any time.
+ */
+/*
+ *  Copyright (C) 2006-2018, ARM Limited, All Rights Reserved
+ *  SPDX-License-Identifier: Apache-2.0
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License"); you may
+ *  not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ *  This file is part of mbed TLS (https://tls.mbed.org)
+ */
+
+#ifndef MBEDTLS_PSA_UTIL_H
+#define MBEDTLS_PSA_UTIL_H
+
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
+
+#if defined(MBEDTLS_USE_PSA_CRYPTO)
+
+#include "psa/crypto.h"
+
+#include "ecp.h"
+#include "md.h"
+#include "pk.h"
+
+/* Slot allocation */
+
+static inline psa_status_t mbedtls_psa_get_free_key_slot( psa_key_slot_t *key )
+{
+    for( psa_key_slot_t slot = 1; slot <= 32; slot++ )
+    {
+        if( psa_get_key_information( slot, NULL, NULL ) == PSA_ERROR_EMPTY_SLOT )
+        {
+            *key = slot;
+            return( PSA_SUCCESS );
+        }
+    }
+    return( PSA_ERROR_INSUFFICIENT_MEMORY );
+}
+
+/* Translations for symmetric crypto. */
+
+static inline psa_key_type_t mbedtls_psa_translate_cipher_type(
+    mbedtls_cipher_type_t cipher )
+{
+    switch( cipher )
+    {
+        case MBEDTLS_CIPHER_AES_128_CCM:
+        case MBEDTLS_CIPHER_AES_192_CCM:
+        case MBEDTLS_CIPHER_AES_256_CCM:
+        case MBEDTLS_CIPHER_AES_128_GCM:
+        case MBEDTLS_CIPHER_AES_192_GCM:
+        case MBEDTLS_CIPHER_AES_256_GCM:
+        case MBEDTLS_CIPHER_AES_128_CBC:
+        case MBEDTLS_CIPHER_AES_192_CBC:
+        case MBEDTLS_CIPHER_AES_256_CBC:
+            return( PSA_KEY_TYPE_AES );
+
+        /* ARIA not yet supported in PSA. */
+        /* case MBEDTLS_CIPHER_ARIA_128_CCM:
+           case MBEDTLS_CIPHER_ARIA_192_CCM:
+           case MBEDTLS_CIPHER_ARIA_256_CCM:
+           case MBEDTLS_CIPHER_ARIA_128_GCM:
+           case MBEDTLS_CIPHER_ARIA_192_GCM:
+           case MBEDTLS_CIPHER_ARIA_256_GCM:
+           case MBEDTLS_CIPHER_ARIA_128_CBC:
+           case MBEDTLS_CIPHER_ARIA_192_CBC:
+           case MBEDTLS_CIPHER_ARIA_256_CBC:
+               return( PSA_KEY_TYPE_ARIA ); */
+
+        default:
+            return( 0 );
+    }
+}
+
+static inline psa_algorithm_t mbedtls_psa_translate_cipher_mode(
+    mbedtls_cipher_mode_t mode, size_t taglen )
+{
+    switch( mode )
+    {
+        case MBEDTLS_MODE_GCM:
+            return( PSA_ALG_AEAD_WITH_TAG_LENGTH( PSA_ALG_GCM, taglen ) );
+        case MBEDTLS_MODE_CCM:
+            return( PSA_ALG_AEAD_WITH_TAG_LENGTH( PSA_ALG_CCM, taglen ) );
+        case MBEDTLS_MODE_CBC:
+            if( taglen == 0 )
+                return( PSA_ALG_CBC_NO_PADDING );
+            /* Intentional fallthrough for taglen != 0 */
+        default:
+            return( 0 );
+    }
+}
+
+static inline psa_key_usage_t mbedtls_psa_translate_cipher_operation(
+    mbedtls_operation_t op )
+{
+    switch( op )
+    {
+        case MBEDTLS_ENCRYPT:
+            return( PSA_KEY_USAGE_ENCRYPT );
+        case MBEDTLS_DECRYPT:
+            return( PSA_KEY_USAGE_DECRYPT );
+        default:
+            return( 0 );
+    }
+}
+
+/* Translations for hashing. */
+
+static inline psa_algorithm_t mbedtls_psa_translate_md( mbedtls_md_type_t md_alg )
+{
+    switch( md_alg )
+    {
+#if defined(MBEDTLS_MD2_C)
+    case MBEDTLS_MD_MD2:
+        return( PSA_ALG_MD2 );
+#endif
+#if defined(MBEDTLS_MD4_C)
+    case MBEDTLS_MD_MD4:
+        return( PSA_ALG_MD4 );
+#endif
+#if defined(MBEDTLS_MD5_C)
+    case MBEDTLS_MD_MD5:
+        return( PSA_ALG_MD5 );
+#endif
+#if defined(MBEDTLS_SHA1_C)
+    case MBEDTLS_MD_SHA1:
+        return( PSA_ALG_SHA_1 );
+#endif
+#if defined(MBEDTLS_SHA256_C)
+    case MBEDTLS_MD_SHA224:
+        return( PSA_ALG_SHA_224 );
+    case MBEDTLS_MD_SHA256:
+        return( PSA_ALG_SHA_256 );
+#endif
+#if defined(MBEDTLS_SHA512_C)
+    case MBEDTLS_MD_SHA384:
+        return( PSA_ALG_SHA_384 );
+    case MBEDTLS_MD_SHA512:
+        return( PSA_ALG_SHA_512 );
+#endif
+#if defined(MBEDTLS_RIPEMD160_C)
+    case MBEDTLS_MD_RIPEMD160:
+        return( PSA_ALG_RIPEMD160 );
+#endif
+    case MBEDTLS_MD_NONE:  /* Intentional fallthrough */
+    default:
+        return( 0 );
+    }
+}
+
+/* Translations for ECC. */
+
+static inline psa_ecc_curve_t mbedtls_psa_translate_ecc_group( mbedtls_ecp_group_id grpid )
+{
+    switch( grpid )
+    {
+#if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED)
+        case MBEDTLS_ECP_DP_SECP192R1:
+            return( PSA_ECC_CURVE_SECP192R1 );
+#endif
+#if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED)
+        case MBEDTLS_ECP_DP_SECP224R1:
+            return( PSA_ECC_CURVE_SECP224R1 );
+#endif
+#if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED)
+        case MBEDTLS_ECP_DP_SECP256R1:
+            return( PSA_ECC_CURVE_SECP256R1 );
+#endif
+#if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)
+        case MBEDTLS_ECP_DP_SECP384R1:
+            return( PSA_ECC_CURVE_SECP384R1 );
+#endif
+#if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED)
+        case MBEDTLS_ECP_DP_SECP521R1:
+            return( PSA_ECC_CURVE_SECP521R1 );
+#endif
+#if defined(MBEDTLS_ECP_DP_BP256R1_ENABLED)
+        case MBEDTLS_ECP_DP_BP256R1:
+            return( PSA_ECC_CURVE_BRAINPOOL_P256R1 );
+#endif
+#if defined(MBEDTLS_ECP_DP_BP384R1_ENABLED)
+        case MBEDTLS_ECP_DP_BP384R1:
+            return( PSA_ECC_CURVE_BRAINPOOL_P384R1 );
+#endif
+#if defined(MBEDTLS_ECP_DP_BP512R1_ENABLED)
+        case MBEDTLS_ECP_DP_BP512R1:
+            return( PSA_ECC_CURVE_BRAINPOOL_P512R1 );
+#endif
+#if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED)
+        case MBEDTLS_ECP_DP_CURVE25519:
+            return( PSA_ECC_CURVE_CURVE25519 );
+#endif
+#if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED)
+        case MBEDTLS_ECP_DP_SECP192K1:
+            return( PSA_ECC_CURVE_SECP192K1 );
+#endif
+#if defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED)
+        case MBEDTLS_ECP_DP_SECP224K1:
+            return( PSA_ECC_CURVE_SECP224K1 );
+#endif
+#if defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED)
+        case MBEDTLS_ECP_DP_SECP256K1:
+            return( PSA_ECC_CURVE_SECP256K1 );
+#endif
+#if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED)
+        case MBEDTLS_ECP_DP_CURVE448:
+            return( PSA_ECC_CURVE_CURVE448 );
+#endif
+        default:
+            return( 0 );
+    }
+}
+
+/* Translations for PK layer */
+
+static inline int mbedtls_psa_err_translate_pk( psa_status_t status )
+{
+    switch( status )
+    {
+        case PSA_SUCCESS:
+            return( 0 );
+        case PSA_ERROR_NOT_SUPPORTED:
+            return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE );
+        case PSA_ERROR_INSUFFICIENT_MEMORY:
+            return( MBEDTLS_ERR_PK_ALLOC_FAILED );
+        case PSA_ERROR_INSUFFICIENT_ENTROPY:
+            return( MBEDTLS_ERR_ECP_RANDOM_FAILED );
+        case PSA_ERROR_BAD_STATE:
+            return( MBEDTLS_ERR_PK_BAD_INPUT_DATA );
+        /* All other failures */
+        case PSA_ERROR_COMMUNICATION_FAILURE:
+        case PSA_ERROR_HARDWARE_FAILURE:
+        case PSA_ERROR_TAMPERING_DETECTED:
+            return( MBEDTLS_ERR_PK_HW_ACCEL_FAILED );
+        default: /* We return the same as for the 'other failures',
+                  * but list them separately nonetheless to indicate
+                  * which failure conditions we have considered. */
+            return( MBEDTLS_ERR_PK_HW_ACCEL_FAILED );
+    }
+}
+
+#endif /* MBEDTLS_USE_PSA_CRYPTO */
+
+#endif /* MBEDTLS_PSA_UTIL_H */
diff --git a/library/version_features.c b/library/version_features.c
index 590f949..2bfcfc0 100644
--- a/library/version_features.c
+++ b/library/version_features.c
@@ -522,6 +522,9 @@
 #if defined(MBEDTLS_THREADING_PTHREAD)
     "MBEDTLS_THREADING_PTHREAD",
 #endif /* MBEDTLS_THREADING_PTHREAD */
+#if defined(MBEDTLS_USE_PSA_CRYPTO)
+    "MBEDTLS_USE_PSA_CRYPTO",
+#endif /* MBEDTLS_USE_PSA_CRYPTO */
 #if defined(MBEDTLS_VERSION_FEATURES)
     "MBEDTLS_VERSION_FEATURES",
 #endif /* MBEDTLS_VERSION_FEATURES */
diff --git a/programs/ssl/ssl_client2.c b/programs/ssl/ssl_client2.c
index 15c778d..87b9ab1 100644
--- a/programs/ssl/ssl_client2.c
+++ b/programs/ssl/ssl_client2.c
@@ -59,6 +59,10 @@
 #include "mbedtls/debug.h"
 #include "mbedtls/timing.h"
 
+#if defined(MBEDTLS_USE_PSA_CRYPTO)
+#include "psa/crypto.h"
+#endif
+
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -555,6 +559,9 @@
 #endif
     char *p, *q;
     const int *list;
+#if defined(MBEDTLS_USE_PSA_CRYPTO)
+    psa_status_t status;
+#endif
 
     /*
      * Make sure memory references are valid.
@@ -573,6 +580,17 @@
     memset( (void * ) alpn_list, 0, sizeof( alpn_list ) );
 #endif
 
+#if defined(MBEDTLS_USE_PSA_CRYPTO)
+    status = psa_crypto_init();
+    if( status != PSA_SUCCESS )
+    {
+        mbedtls_fprintf( stderr, "Failed to initialize PSA Crypto implementation: %d\n",
+                         (int) status );
+        ret = MBEDTLS_ERR_SSL_HW_ACCEL_FAILED;
+        goto exit;
+    }
+#endif
+
     if( argc == 0 )
     {
     usage:
diff --git a/programs/ssl/ssl_server2.c b/programs/ssl/ssl_server2.c
index efda65d..1c6ccae 100644
--- a/programs/ssl/ssl_server2.c
+++ b/programs/ssl/ssl_server2.c
@@ -60,6 +60,10 @@
 #include "mbedtls/debug.h"
 #include "mbedtls/timing.h"
 
+#if defined(MBEDTLS_USE_PSA_CRYPTO)
+#include "psa/crypto.h"
+#endif
+
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -1238,6 +1242,9 @@
     int i;
     char *p, *q;
     const int *list;
+#if defined(MBEDTLS_USE_PSA_CRYPTO)
+    psa_status_t status;
+#endif
 
 #if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C)
     mbedtls_memory_buffer_alloc_init( alloc_buf, sizeof(alloc_buf) );
@@ -1277,6 +1284,17 @@
     mbedtls_ssl_cookie_init( &cookie_ctx );
 #endif
 
+#if defined(MBEDTLS_USE_PSA_CRYPTO)
+    status = psa_crypto_init();
+    if( status != PSA_SUCCESS )
+    {
+        mbedtls_fprintf( stderr, "Failed to initialize PSA Crypto implementation: %d\n",
+                         (int) status );
+        ret = MBEDTLS_ERR_SSL_HW_ACCEL_FAILED;
+        goto exit;
+    }
+#endif
+
 #if !defined(_WIN32)
     /* Abort cleanly on SIGTERM and SIGINT */
     signal( SIGTERM, term_handler );
diff --git a/scripts/config.pl b/scripts/config.pl
index 6d02ec0..55f4b6e 100755
--- a/scripts/config.pl
+++ b/scripts/config.pl
@@ -36,6 +36,8 @@
 #       - this could be enabled if the respective tests were adapted
 #   MBEDTLS_ZLIB_SUPPORT
 #   MBEDTLS_PKCS11_C
+#   MBEDTLS_USE_PSA_CRYPTO
+#       - experimental, and more an alternative implementation than a feature
 #   and any symbol beginning _ALT
 #
 
@@ -99,6 +101,7 @@
 MBEDTLS_PSA_CRYPTO_SPM
 MBEDTLS_PSA_HAS_ITS_IO
 MBEDTLS_PSA_CRYPTO_STORAGE_ITS_C
+MBEDTLS_USE_PSA_CRYPTO
 _ALT\s*$
 );
 
diff --git a/tests/scripts/all.sh b/tests/scripts/all.sh
index 43f1db6..6af13e6 100755
--- a/tests/scripts/all.sh
+++ b/tests/scripts/all.sh
@@ -573,6 +573,35 @@
 msg "test: compat.sh ARIA + ChachaPoly"
 if_build_succeeded env OPENSSL_CMD="$OPENSSL_NEXT" tests/compat.sh -e '^$' -f 'ARIA\|CHACHA'
 
+# MBEDTLS_USE_PSA_CRYPTO: run the same set of tests as basic-build-test.sh
+msg "build: cmake, full config + MBEDTLS_USE_PSA_CRYPTO, ASan"
+cleanup
+cp "$CONFIG_H" "$CONFIG_BAK"
+scripts/config.pl full
+scripts/config.pl unset MBEDTLS_MEMORY_BACKTRACE # too slow for tests
+scripts/config.pl set MBEDTLS_PSA_CRYPTO_C
+scripts/config.pl set MBEDTLS_USE_PSA_CRYPTO
+CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan .
+make
+
+msg "test: main suites (MBEDTLS_USE_PSA_CRYPTO)"
+make test
+
+msg "test: ssl-opt.sh (MBEDTLS_USE_PSA_CRYPTO)"
+if_build_succeeded tests/ssl-opt.sh
+
+msg "test: compat.sh default (MBEDTLS_USE_PSA_CRYPTO)"
+if_build_succeeded tests/compat.sh
+
+msg "test: compat.sh ssl3 (MBEDTLS_USE_PSA_CRYPTO)"
+if_build_succeeded env OPENSSL_CMD="$OPENSSL_LEGACY" tests/compat.sh -m 'ssl3'
+
+msg "test: compat.sh RC4, DES & NULL (MBEDTLS_USE_PSA_CRYPTO)"
+if_build_succeeded env OPENSSL_CMD="$OPENSSL_LEGACY" GNUTLS_CLI="$GNUTLS_LEGACY_CLI" GNUTLS_SERV="$GNUTLS_LEGACY_SERV" tests/compat.sh -e '3DES\|DES-CBC3' -f 'NULL\|DES\|RC4\|ARCFOUR'
+
+msg "test: compat.sh ARIA + ChachaPoly (MBEDTLS_USE_PSA_CRYPTO)"
+if_build_succeeded env OPENSSL_CMD="$OPENSSL_NEXT" tests/compat.sh -e '^$' -f 'ARIA\|CHACHA'
+
 msg "build: make, full config + DEPRECATED_WARNING, gcc -O" # ~ 30s
 cleanup
 cp "$CONFIG_H" "$CONFIG_BAK"
diff --git a/tests/suites/main_test.function b/tests/suites/main_test.function
index 2ba919c..8bd408c 100644
--- a/tests/suites/main_test.function
+++ b/tests/suites/main_test.function
@@ -25,6 +25,9 @@
 #include MBEDTLS_CONFIG_FILE
 #endif
 
+#if defined(MBEDTLS_USE_PSA_CRYPTO)
+#include "psa/crypto.h"
+#endif /* MBEDTLS_USE_PSA_CRYPTO */
 
 /*----------------------------------------------------------------------------*/
 /* Common helper code */
@@ -221,8 +224,22 @@
                          ret );
         return( -1 );
     }
+
+#if defined(MBEDTLS_USE_PSA_CRYPTO)
+    {
+        psa_status_t status;
+        status = psa_crypto_init();
+        if( status != PSA_SUCCESS )
+        {
+            mbedtls_fprintf( stderr,
+                          "FATAL: Failed to initialize PSA Crypto - error %d\n",
+                          status );
+            return( -1 );
+        }
+    }
+#endif /* MBEDTLS_USE_PSA_CRYPTO */
+
     ret = execute_tests( argc, argv );
     platform_teardown();
     return( ret );
 }
-
diff --git a/visualc/VS2010/mbedTLS.vcxproj b/visualc/VS2010/mbedTLS.vcxproj
index 5d57a75..6535d48 100644
--- a/visualc/VS2010/mbedTLS.vcxproj
+++ b/visualc/VS2010/mbedTLS.vcxproj
@@ -204,6 +204,7 @@
     <ClInclude Include="..\..\include\mbedtls\platform_time.h" />

     <ClInclude Include="..\..\include\mbedtls\platform_util.h" />

     <ClInclude Include="..\..\include\mbedtls\poly1305.h" />

+    <ClInclude Include="..\..\include\mbedtls\psa_util.h" />

     <ClInclude Include="..\..\include\mbedtls\ripemd160.h" />

     <ClInclude Include="..\..\include\mbedtls\rsa.h" />

     <ClInclude Include="..\..\include\mbedtls\rsa_internal.h" />