Merge branch 'psa_cipher_integration' into development-psa-proposed
diff --git a/library/ssl_ticket.c b/library/ssl_ticket.c
index 985b7cd..9fc690f 100644
--- a/library/ssl_ticket.c
+++ b/library/ssl_ticket.c
@@ -54,6 +54,19 @@
 
 #define MAX_KEY_BYTES 32    /* 256 bits */
 
+#define TICKET_KEY_NAME_BYTES    4
+#define TICKET_IV_BYTES         12
+#define TICKET_CRYPT_LEN_BYTES   2
+#define TICKET_AUTH_TAG_BYTES   16
+
+#define TICKET_MIN_LEN ( TICKET_KEY_NAME_BYTES  +        \
+                         TICKET_IV_BYTES        +        \
+                         TICKET_CRYPT_LEN_BYTES +        \
+                         TICKET_AUTH_TAG_BYTES )
+#define TICKET_ADD_DATA_LEN ( TICKET_KEY_NAME_BYTES  +        \
+                              TICKET_IV_BYTES        +        \
+                              TICKET_CRYPT_LEN_BYTES )
+
 /*
  * Generate/update a key
  */
@@ -141,11 +154,27 @@
     if( cipher_info->key_bitlen > 8 * MAX_KEY_BYTES )
         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
 
-    if( ( ret = mbedtls_cipher_setup( &ctx->keys[0].ctx, cipher_info ) ) != 0 ||
-        ( ret = mbedtls_cipher_setup( &ctx->keys[1].ctx, cipher_info ) ) != 0 )
-    {
+#if defined(MBEDTLS_USE_PSA_CRYPTO)
+    ret = mbedtls_cipher_setup_psa( &ctx->keys[0].ctx,
+                                    cipher_info, TICKET_AUTH_TAG_BYTES );
+    if( ret != 0 && ret != MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE )
         return( ret );
-    }
+    /* We don't yet expect to support all ciphers through PSA,
+     * so allow fallback to ordinary mbedtls_cipher_setup(). */
+    if( ret == MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE )
+#endif /* MBEDTLS_USE_PSA_CRYPTO */
+    if( ( ret = mbedtls_cipher_setup( &ctx->keys[0].ctx, cipher_info ) ) != 0 )
+        return( ret );
+
+#if defined(MBEDTLS_USE_PSA_CRYPTO)
+    ret = mbedtls_cipher_setup_psa( &ctx->keys[1].ctx,
+                                    cipher_info, TICKET_AUTH_TAG_BYTES );
+    if( ret != 0 && ret != MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE )
+        return( ret );
+    if( ret == MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE )
+#endif /* MBEDTLS_USE_PSA_CRYPTO */
+    if( ( ret = mbedtls_cipher_setup( &ctx->keys[1].ctx, cipher_info ) ) != 0 )
+        return( ret );
 
     if( ( ret = ssl_ticket_gen_key( ctx, 0 ) ) != 0 ||
         ( ret = ssl_ticket_gen_key( ctx, 1 ) ) != 0 )
@@ -278,6 +307,7 @@
  * The key_name, iv, and length of encrypted_state are the additional
  * authenticated data.
  */
+
 int mbedtls_ssl_ticket_write( void *p_ticket,
                               const mbedtls_ssl_session *session,
                               unsigned char *start,
@@ -289,9 +319,9 @@
     mbedtls_ssl_ticket_context *ctx = p_ticket;
     mbedtls_ssl_ticket_key *key;
     unsigned char *key_name = start;
-    unsigned char *iv = start + 4;
-    unsigned char *state_len_bytes = iv + 12;
-    unsigned char *state = state_len_bytes + 2;
+    unsigned char *iv = start + TICKET_KEY_NAME_BYTES;
+    unsigned char *state_len_bytes = iv + TICKET_IV_BYTES;
+    unsigned char *state = state_len_bytes + TICKET_CRYPT_LEN_BYTES;
     unsigned char *tag;
     size_t clear_len, ciph_len;
 
@@ -302,7 +332,7 @@
 
     /* We need at least 4 bytes for key_name, 12 for IV, 2 for len 16 for tag,
      * in addition to session itself, that will be checked when writing it. */
-    if( end - start < 4 + 12 + 2 + 16 )
+    if( end - start < TICKET_MIN_LEN )
         return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
 
 #if defined(MBEDTLS_THREADING_C)
@@ -317,9 +347,9 @@
 
     *ticket_lifetime = ctx->ticket_lifetime;
 
-    memcpy( key_name, key->name, 4 );
+    memcpy( key_name, key->name, TICKET_KEY_NAME_BYTES );
 
-    if( ( ret = ctx->f_rng( ctx->p_rng, iv, 12 ) ) != 0 )
+    if( ( ret = ctx->f_rng( ctx->p_rng, iv, TICKET_IV_BYTES ) ) != 0 )
         goto cleanup;
 
     /* Dump session state */
@@ -335,8 +365,11 @@
     /* Encrypt and authenticate */
     tag = state + clear_len;
     if( ( ret = mbedtls_cipher_auth_encrypt( &key->ctx,
-                    iv, 12, key_name, 4 + 12 + 2,
-                    state, clear_len, state, &ciph_len, tag, 16 ) ) != 0 )
+                    iv, TICKET_IV_BYTES,
+                    /* Additional data: key name, IV and length */
+                    key_name, TICKET_ADD_DATA_LEN,
+                    state, clear_len, state, &ciph_len,
+                    tag, TICKET_AUTH_TAG_BYTES ) ) != 0 )
     {
         goto cleanup;
     }
@@ -346,7 +379,7 @@
         goto cleanup;
     }
 
-    *tlen = 4 + 12 + 2 + 16 + ciph_len;
+    *tlen = TICKET_MIN_LEN + ciph_len;
 
 cleanup:
 #if defined(MBEDTLS_THREADING_C)
@@ -385,17 +418,16 @@
     mbedtls_ssl_ticket_context *ctx = p_ticket;
     mbedtls_ssl_ticket_key *key;
     unsigned char *key_name = buf;
-    unsigned char *iv = buf + 4;
-    unsigned char *enc_len_p = iv + 12;
-    unsigned char *ticket = enc_len_p + 2;
+    unsigned char *iv = buf + TICKET_KEY_NAME_BYTES;
+    unsigned char *enc_len_p = iv + TICKET_IV_BYTES;
+    unsigned char *ticket = enc_len_p + TICKET_CRYPT_LEN_BYTES;
     unsigned char *tag;
     size_t enc_len, clear_len;
 
     if( ctx == NULL || ctx->f_rng == NULL )
         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
 
-    /* See mbedtls_ssl_ticket_write() */
-    if( len < 4 + 12 + 2 + 16 )
+    if( len < TICKET_MIN_LEN )
         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
 
 #if defined(MBEDTLS_THREADING_C)
@@ -409,7 +441,7 @@
     enc_len = ( enc_len_p[0] << 8 ) | enc_len_p[1];
     tag = ticket + enc_len;
 
-    if( len != 4 + 12 + 2 + enc_len + 16 )
+    if( len != TICKET_MIN_LEN + enc_len )
     {
         ret = MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
         goto cleanup;
@@ -425,9 +457,13 @@
     }
 
     /* Decrypt and authenticate */
-    if( ( ret = mbedtls_cipher_auth_decrypt( &key->ctx, iv, 12,
-                    key_name, 4 + 12 + 2, ticket, enc_len,
-                    ticket, &clear_len, tag, 16 ) ) != 0 )
+    if( ( ret = mbedtls_cipher_auth_decrypt( &key->ctx,
+                    iv, TICKET_IV_BYTES,
+                    /* Additional data: key name, IV and length */
+                    key_name, TICKET_ADD_DATA_LEN,
+                    ticket, enc_len,
+                    ticket, &clear_len,
+                    tag, TICKET_AUTH_TAG_BYTES ) ) != 0 )
     {
         if( ret == MBEDTLS_ERR_CIPHER_AUTH_FAILED )
             ret = MBEDTLS_ERR_SSL_INVALID_MAC;
diff --git a/library/ssl_tls.c b/library/ssl_tls.c
index 9343969..d14434a 100644
--- a/library/ssl_tls.c
+++ b/library/ssl_tls.c
@@ -632,6 +632,9 @@
 int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl )
 {
     int ret = 0;
+#if defined(MBEDTLS_USE_PSA_CRYPTO)
+    int psa_fallthrough;
+#endif /* MBEDTLS_USE_PSA_CRYPTO */
     unsigned char tmp[64];
     unsigned char keyblk[256];
     unsigned char *key1;
@@ -640,6 +643,7 @@
     unsigned char *mac_dec;
     size_t mac_key_len;
     size_t iv_copy_len;
+    size_t taglen = 0;
     const mbedtls_cipher_info_t *cipher_info;
     const mbedtls_md_info_t *md_info;
 
@@ -899,7 +903,7 @@
         cipher_info->mode == MBEDTLS_MODE_CCM ||
         cipher_info->mode == MBEDTLS_MODE_CHACHAPOLY )
     {
-        size_t taglen, explicit_ivlen;
+        size_t explicit_ivlen;
 
         transform->maclen = 0;
         mac_key_len = 0;
@@ -1119,6 +1123,43 @@
     }
 #endif
 
+#if defined(MBEDTLS_USE_PSA_CRYPTO)
+
+    /* Only use PSA-based ciphers for TLS-1.2.
+     * That's relevant at least for TLS-1.0, where
+     * we assume that mbedtls_cipher_crypt() updates
+     * the structure field for the IV, which the PSA-based
+     * implementation currently doesn't. */
+#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
+    if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
+    {
+        ret = mbedtls_cipher_setup_psa( &transform->cipher_ctx_enc,
+                                        cipher_info, taglen );
+        if( ret != 0 && ret != MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE )
+        {
+            MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup_psa", ret );
+            return( ret );
+        }
+
+        if( ret == 0 )
+        {
+            MBEDTLS_SSL_DEBUG_MSG( 1, ( "Successfully setup PSA-based encryption cipher context" ) );
+            psa_fallthrough = 0;
+        }
+        else
+        {
+            MBEDTLS_SSL_DEBUG_MSG( 1, ( "Failed to setup PSA-based cipher context for record encryption - fall through to default setup." ) );
+            psa_fallthrough = 1;
+        }
+    }
+    else
+        psa_fallthrough = 1;
+#else
+    psa_fallthrough = 1;
+#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
+
+    if( psa_fallthrough == 1 )
+#endif /* MBEDTLS_USE_PSA_CRYPTO */
     if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_enc,
                                  cipher_info ) ) != 0 )
     {
@@ -1126,6 +1167,42 @@
         return( ret );
     }
 
+#if defined(MBEDTLS_USE_PSA_CRYPTO)
+    /* Only use PSA-based ciphers for TLS-1.2.
+     * That's relevant at least for TLS-1.0, where
+     * we assume that mbedtls_cipher_crypt() updates
+     * the structure field for the IV, which the PSA-based
+     * implementation currently doesn't. */
+#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
+    if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
+    {
+        ret = mbedtls_cipher_setup_psa( &transform->cipher_ctx_dec,
+                                        cipher_info, taglen );
+        if( ret != 0 && ret != MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE )
+        {
+            MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup_psa", ret );
+            return( ret );
+        }
+
+        if( ret == 0 )
+        {
+            MBEDTLS_SSL_DEBUG_MSG( 1, ( "Successfully setup PSA-based decryption cipher context" ) );
+            psa_fallthrough = 0;
+        }
+        else
+        {
+            MBEDTLS_SSL_DEBUG_MSG( 1, ( "Failed to setup PSA-based cipher context for record decryption - fall through to default setup." ) );
+            psa_fallthrough = 1;
+        }
+    }
+    else
+        psa_fallthrough = 1;
+#else
+    psa_fallthrough = 1;
+#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
+
+    if( psa_fallthrough == 1 )
+#endif /* MBEDTLS_USE_PSA_CRYPTO */
     if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_dec,
                                  cipher_info ) ) != 0 )
     {
diff --git a/tests/ssl-opt.sh b/tests/ssl-opt.sh
index d3a4338..2ccecc4 100755
--- a/tests/ssl-opt.sh
+++ b/tests/ssl-opt.sh
@@ -185,6 +185,12 @@
     fi
 }
 
+requires_ciphersuite_enabled() {
+    if [ -z "$($P_CLI --help | grep $1)" ]; then
+        SKIP_NEXT="YES"
+    fi
+}
+
 # skip next test if OpenSSL doesn't support FALLBACK_SCSV
 requires_openssl_with_fallback_scsv() {
     if [ -z "${OPENSSL_HAS_FBSCSV:-}" ]; then
@@ -519,14 +525,6 @@
         SKIP_NEXT="YES"
     fi
 
-    # should we skip?
-    if [ "X$SKIP_NEXT" = "XYES" ]; then
-        SKIP_NEXT="NO"
-        echo "SKIP"
-        SKIPS=$(( $SKIPS + 1 ))
-        return
-    fi
-
     # does this test use a proxy?
     if [ "X$1" = "X-p" ]; then
         PXY_CMD="$2"
@@ -541,6 +539,26 @@
     CLI_EXPECT="$3"
     shift 3
 
+    # Check if server forces ciphersuite
+    FORCE_CIPHERSUITE=$(echo "$SRV_CMD" | sed -n 's/^.*force_ciphersuite=\([a-zA-Z0-9\-]*\).*$/\1/p')
+    if [ ! -z "$FORCE_CIPHERSUITE" ]; then
+       requires_ciphersuite_enabled $FORCE_CIPHERSUITE
+    fi
+
+    # Check if client forces ciphersuite
+    FORCE_CIPHERSUITE=$(echo "$CLI_CMD" | sed -n 's/^.*force_ciphersuite=\([a-zA-Z0-9\-]*\).*$/\1/p')
+    if [ ! -z "$FORCE_CIPHERSUITE" ]; then
+       requires_ciphersuite_enabled $FORCE_CIPHERSUITE
+    fi
+
+    # should we skip?
+    if [ "X$SKIP_NEXT" = "XYES" ]; then
+        SKIP_NEXT="NO"
+        echo "SKIP"
+        SKIPS=$(( $SKIPS + 1 ))
+        return
+    fi
+
     # fix client port
     if [ -n "$PXY_CMD" ]; then
         CLI_CMD=$( echo "$CLI_CMD" | sed s/+SRV_PORT/$PXY_PORT/g )
@@ -734,6 +752,23 @@
     rm -f $SRV_OUT $CLI_OUT $PXY_OUT
 }
 
+run_test_psa() {
+    requires_config_enabled MBEDTLS_USE_PSA_CRYPTO
+    run_test    "PSA-supported ciphersuite: $1" \
+                "$P_SRV debug_level=1 force_version=tls1_2" \
+                "$P_CLI debug_level=1 force_version=tls1_2 force_ciphersuite=$1" \
+                0 \
+                -c "Successfully setup PSA-based decryption cipher context" \
+                -c "Successfully setup PSA-based encryption cipher context" \
+                -s "Successfully setup PSA-based decryption cipher context" \
+                -s "Successfully setup PSA-based encryption cipher context" \
+                -C "Failed to setup PSA-based cipher context"\
+                -S "Failed to setup PSA-based cipher context"\
+                -s "Protocol is TLSv1.2" \
+                -S "error" \
+                -C "error"
+}
+
 cleanup() {
     rm -f $CLI_OUT $SRV_OUT $PXY_OUT $SESSION
     test -n "${SRV_PID:-}" && kill $SRV_PID >/dev/null 2>&1
@@ -880,6 +915,18 @@
             -S "error" \
             -C "error"
 
+# Test ciphersuites which we expect to be fully supported by PSA Crypto
+# and check that we don't fall back to Mbed TLS' internal crypto primitives.
+run_test_psa TLS-ECDHE-ECDSA-WITH-AES-128-CCM
+run_test_psa TLS-ECDHE-ECDSA-WITH-AES-128-CCM-8
+run_test_psa TLS-ECDHE-ECDSA-WITH-AES-256-CCM
+run_test_psa TLS-ECDHE-ECDSA-WITH-AES-256-CCM-8
+run_test_psa TLS-ECDHE-ECDSA-WITH-AES-128-GCM-SHA256
+run_test_psa TLS-ECDHE-ECDSA-WITH-AES-256-GCM-SHA384
+run_test_psa TLS-ECDHE-ECDSA-WITH-AES-128-CBC-SHA
+run_test_psa TLS-ECDHE-ECDSA-WITH-AES-128-CBC-SHA256
+run_test_psa TLS-ECDHE-ECDSA-WITH-AES-256-CBC-SHA384
+
 # Test current time in ServerHello
 requires_config_enabled MBEDTLS_HAVE_TIME
 run_test    "ServerHello contains gmt_unix_time" \