Merge pull request #4953 from yuhaoth/pr/add-tls13-read-certificate-verfify

TLS1.3: CertificateVerify:add tls13 read certificate verfify
diff --git a/library/ssl_misc.h b/library/ssl_misc.h
index c7d966b..7ca460c 100644
--- a/library/ssl_misc.h
+++ b/library/ssl_misc.h
@@ -1639,6 +1639,11 @@
 int mbedtls_ssl_tls13_process_certificate( mbedtls_ssl_context *ssl );
 
 /*
+ * Generic handler of Certificate Verify
+ */
+int mbedtls_ssl_tls13_process_certificate_verify( mbedtls_ssl_context *ssl );
+
+/*
  * Write TLS 1.3 handshake message tail
  */
 int mbedtls_ssl_tls13_finish_handshake_msg( mbedtls_ssl_context *ssl,
diff --git a/library/ssl_tls13_client.c b/library/ssl_tls13_client.c
index 9c88484..869465c 100644
--- a/library/ssl_tls13_client.c
+++ b/library/ssl_tls13_client.c
@@ -1582,7 +1582,12 @@
  */
 static int ssl_tls1_3_process_certificate_verify( mbedtls_ssl_context *ssl )
 {
-    MBEDTLS_SSL_DEBUG_MSG( 1, ( "%s hasn't been implemented", __func__ ) );
+    int ret;
+
+    ret = mbedtls_ssl_tls13_process_certificate_verify( ssl );
+    if( ret != 0 )
+        return( ret );
+
     mbedtls_ssl_handshake_set_state( ssl, MBEDTLS_SSL_SERVER_FINISHED );
     return( 0 );
 }
diff --git a/library/ssl_tls13_generic.c b/library/ssl_tls13_generic.c
index c8601ce..75b11c9 100644
--- a/library/ssl_tls13_generic.c
+++ b/library/ssl_tls13_generic.c
@@ -23,14 +23,15 @@
 
 #if defined(MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL)
 
+#include <string.h>
+
 #include "mbedtls/error.h"
 #include "mbedtls/debug.h"
+#include "mbedtls/oid.h"
+#include "mbedtls/platform.h"
 
 #include "ssl_misc.h"
-#include <mbedtls/debug.h>
-#include <mbedtls/oid.h>
-#include <mbedtls/platform.h>
-
+#include "ssl_tls13_keys.h"
 
 int mbedtls_ssl_tls1_3_fetch_handshake_msg( mbedtls_ssl_context *ssl,
                                             unsigned hs_type,
@@ -217,8 +218,300 @@
     return( 0 );
 }
 
+/*
+ * STATE HANDLING: Read CertificateVerify
+ */
+/* Macro to express the maximum length of the verify structure.
+ *
+ * The structure is computed per TLS 1.3 specification as:
+ *   - 64 bytes of octet 32,
+ *   - 33 bytes for the context string
+ *        (which is either "TLS 1.3, client CertificateVerify"
+ *         or "TLS 1.3, server CertificateVerify"),
+ *   - 1 byte for the octet 0x0, which serves as a separator,
+ *   - 32 or 48 bytes for the Transcript-Hash(Handshake Context, Certificate)
+ *     (depending on the size of the transcript_hash)
+ *
+ * This results in a total size of
+ * - 130 bytes for a SHA256-based transcript hash, or
+ *   (64 + 33 + 1 + 32 bytes)
+ * - 146 bytes for a SHA384-based transcript hash.
+ *   (64 + 33 + 1 + 48 bytes)
+ *
+ */
+#define SSL_VERIFY_STRUCT_MAX_SIZE  ( 64 +                          \
+                                      33 +                          \
+                                       1 +                          \
+                                      MBEDTLS_TLS1_3_MD_MAX_SIZE    \
+                                    )
+
+/*
+ * The ssl_tls13_create_verify_structure() creates the verify structure.
+ * As input, it requires the transcript hash.
+ *
+ * The caller has to ensure that the buffer has size at least
+ * SSL_VERIFY_STRUCT_MAX_SIZE bytes.
+ */
+static void ssl_tls13_create_verify_structure( const unsigned char *transcript_hash,
+                                               size_t transcript_hash_len,
+                                               unsigned char *verify_buffer,
+                                               size_t *verify_buffer_len,
+                                               int from )
+{
+    size_t idx;
+
+    /* RFC 8446, Section 4.4.3:
+     *
+     * The digital signature [in the CertificateVerify message] is then
+     * computed over the concatenation of:
+     * -  A string that consists of octet 32 (0x20) repeated 64 times
+     * -  The context string
+     * -  A single 0 byte which serves as the separator
+     * -  The content to be signed
+     */
+    memset( verify_buffer, 0x20, 64 );
+    idx = 64;
+
+    if( from == MBEDTLS_SSL_IS_CLIENT )
+    {
+        memcpy( verify_buffer + idx, MBEDTLS_SSL_TLS1_3_LBL_WITH_LEN( client_cv ) );
+        idx += MBEDTLS_SSL_TLS1_3_LBL_LEN( client_cv );
+    }
+    else
+    { /* from == MBEDTLS_SSL_IS_SERVER */
+        memcpy( verify_buffer + idx, MBEDTLS_SSL_TLS1_3_LBL_WITH_LEN( server_cv ) );
+        idx += MBEDTLS_SSL_TLS1_3_LBL_LEN( server_cv );
+    }
+
+    verify_buffer[idx++] = 0x0;
+
+    memcpy( verify_buffer + idx, transcript_hash, transcript_hash_len );
+    idx += transcript_hash_len;
+
+    *verify_buffer_len = idx;
+}
+
+static int ssl_tls13_sig_alg_is_offered( const mbedtls_ssl_context *ssl,
+                                         uint16_t sig_alg )
+{
+    const uint16_t *tls13_sig_alg = ssl->conf->tls13_sig_algs;
+
+    for( ; *tls13_sig_alg != MBEDTLS_TLS13_SIG_NONE ; tls13_sig_alg++ )
+    {
+        if( *tls13_sig_alg == sig_alg )
+            return( 1 );
+    }
+    return( 0 );
+}
+
+static int ssl_tls13_parse_certificate_verify( mbedtls_ssl_context *ssl,
+                                               const unsigned char *buf,
+                                               const unsigned char *end,
+                                               const unsigned char *verify_buffer,
+                                               size_t verify_buffer_len )
+{
+    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
+    const unsigned char *p = buf;
+    uint16_t algorithm;
+    size_t signature_len;
+    mbedtls_pk_type_t sig_alg;
+    mbedtls_md_type_t md_alg;
+    unsigned char verify_hash[MBEDTLS_MD_MAX_SIZE];
+    size_t verify_hash_len;
+
+    /*
+     * struct {
+     *     SignatureScheme algorithm;
+     *     opaque signature<0..2^16-1>;
+     * } CertificateVerify;
+     */
+    MBEDTLS_SSL_CHK_BUF_READ_PTR( p, end, 2 );
+    algorithm = MBEDTLS_GET_UINT16_BE( p, 0 );
+    p += 2;
+
+    /* RFC 8446 section 4.4.3
+     *
+     * If the CertificateVerify message is sent by a server, the signature algorithm
+     * MUST be one offered in the client's "signature_algorithms" extension unless
+     * no valid certificate chain can be produced without unsupported algorithms
+     *
+     * RFC 8446 section 4.4.2.2
+     *
+     * If the client cannot construct an acceptable chain using the provided
+     * certificates and decides to abort the handshake, then it MUST abort the handshake
+     * with an appropriate certificate-related alert (by default, "unsupported_certificate").
+     *
+     * Check if algorithm is an offered signature algorithm.
+     */
+    if( ! ssl_tls13_sig_alg_is_offered( ssl, algorithm ) )
+    {
+        /* algorithm not in offered signature algorithms list */
+        MBEDTLS_SSL_DEBUG_MSG( 1, ( "Received signature algorithm(%04x) is not "
+                                    "offered.",
+                                    ( unsigned int ) algorithm ) );
+        goto error;
+    }
+
+    /* We currently only support ECDSA-based signatures */
+    switch( algorithm )
+    {
+        case MBEDTLS_TLS13_SIG_ECDSA_SECP256R1_SHA256:
+            md_alg = MBEDTLS_MD_SHA256;
+            sig_alg = MBEDTLS_PK_ECDSA;
+            break;
+        case MBEDTLS_TLS13_SIG_ECDSA_SECP384R1_SHA384:
+            md_alg = MBEDTLS_MD_SHA384;
+            sig_alg = MBEDTLS_PK_ECDSA;
+            break;
+        case MBEDTLS_TLS13_SIG_ECDSA_SECP521R1_SHA512:
+            md_alg = MBEDTLS_MD_SHA512;
+            sig_alg = MBEDTLS_PK_ECDSA;
+            break;
+        default:
+            MBEDTLS_SSL_DEBUG_MSG( 1, ( "Certificate Verify: Unknown signature algorithm." ) );
+            goto error;
+    }
+
+    MBEDTLS_SSL_DEBUG_MSG( 3, ( "Certificate Verify: Signature algorithm ( %04x )",
+                                ( unsigned int ) algorithm ) );
+
+    /*
+     * Check the certificate's key type matches the signature alg
+     */
+    if( !mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk, sig_alg ) )
+    {
+        MBEDTLS_SSL_DEBUG_MSG( 1, ( "signature algorithm doesn't match cert key" ) );
+        goto error;
+    }
+
+    MBEDTLS_SSL_CHK_BUF_READ_PTR( p, end, 2 );
+    signature_len = MBEDTLS_GET_UINT16_BE( p, 0 );
+    p += 2;
+    MBEDTLS_SSL_CHK_BUF_READ_PTR( p, end, signature_len );
+
+    /* Hash verify buffer with indicated hash function */
+    switch( md_alg )
+    {
+#if defined(MBEDTLS_SHA256_C)
+        case MBEDTLS_MD_SHA256:
+            verify_hash_len = 32;
+            ret = mbedtls_sha256( verify_buffer, verify_buffer_len, verify_hash, 0 );
+            break;
+#endif /* MBEDTLS_SHA256_C */
+
+#if defined(MBEDTLS_SHA384_C)
+        case MBEDTLS_MD_SHA384:
+            verify_hash_len = 48;
+            ret = mbedtls_sha512( verify_buffer, verify_buffer_len, verify_hash, 1 );
+            break;
+#endif /* MBEDTLS_SHA384_C */
+
+#if defined(MBEDTLS_SHA512_C)
+        case MBEDTLS_MD_SHA512:
+            verify_hash_len = 64;
+            ret = mbedtls_sha512( verify_buffer, verify_buffer_len, verify_hash, 0 );
+            break;
+#endif /* MBEDTLS_SHA512_C */
+
+        default:
+            ret = MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
+            break;
+    }
+
+    if( ret != 0 )
+    {
+        MBEDTLS_SSL_DEBUG_RET( 1, "hash computation error", ret );
+        goto error;
+    }
+
+    MBEDTLS_SSL_DEBUG_BUF( 3, "verify hash", verify_hash, verify_hash_len );
+
+    if( ( ret = mbedtls_pk_verify_ext( sig_alg, NULL,
+                                       &ssl->session_negotiate->peer_cert->pk,
+                                       md_alg, verify_hash, verify_hash_len,
+                                       p, signature_len ) ) == 0 )
+    {
+        return( 0 );
+    }
+    MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_verify_ext", ret );
+
+error:
+    /* RFC 8446 section 4.4.3
+     *
+     * If the verification fails, the receiver MUST terminate the handshake
+     * with a "decrypt_error" alert.
+    */
+    MBEDTLS_SSL_PEND_FATAL_ALERT( MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR,
+                                  MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE );
+    return( MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE );
+
+}
 #endif /* MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
 
+int mbedtls_ssl_tls13_process_certificate_verify( mbedtls_ssl_context *ssl )
+{
+
+#if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
+    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
+    unsigned char verify_buffer[SSL_VERIFY_STRUCT_MAX_SIZE];
+    size_t verify_buffer_len;
+    unsigned char transcript[MBEDTLS_TLS1_3_MD_MAX_SIZE];
+    size_t transcript_len;
+    unsigned char *buf;
+    size_t buf_len;
+
+    MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate verify" ) );
+
+    MBEDTLS_SSL_PROC_CHK(
+        mbedtls_ssl_tls1_3_fetch_handshake_msg( ssl,
+                MBEDTLS_SSL_HS_CERTIFICATE_VERIFY, &buf, &buf_len ) );
+
+    /* Need to calculate the hash of the transcript first
+     * before reading the message since otherwise it gets
+     * included in the transcript
+     */
+    ret = mbedtls_ssl_get_handshake_transcript( ssl,
+                            ssl->handshake->ciphersuite_info->mac,
+                            transcript, sizeof( transcript ),
+                            &transcript_len );
+    if( ret != 0 )
+    {
+        MBEDTLS_SSL_PEND_FATAL_ALERT(
+            MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR,
+            MBEDTLS_ERR_SSL_INTERNAL_ERROR );
+        return( ret );
+    }
+
+    MBEDTLS_SSL_DEBUG_BUF( 3, "handshake hash", transcript, transcript_len );
+
+    /* Create verify structure */
+    ssl_tls13_create_verify_structure( transcript,
+                                       transcript_len,
+                                       verify_buffer,
+                                       &verify_buffer_len,
+                                       ( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ) ?
+                                         MBEDTLS_SSL_IS_SERVER :
+                                         MBEDTLS_SSL_IS_CLIENT );
+
+    /* Process the message contents */
+    MBEDTLS_SSL_PROC_CHK( ssl_tls13_parse_certificate_verify( ssl, buf,
+                            buf + buf_len, verify_buffer, verify_buffer_len ) );
+
+    mbedtls_ssl_tls1_3_add_hs_msg_to_checksum( ssl,
+                        MBEDTLS_SSL_HS_CERTIFICATE_VERIFY, buf, buf_len );
+
+cleanup:
+
+    MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse certificate verify" ) );
+    MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_tls13_process_certificate_verify", ret );
+    return( ret );
+#else
+    ((void) ssl);
+    MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
+    return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
+#endif /* MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
+}
+
 /*
  *
  * STATE HANDLING: Incoming Certificate, client-side only currently.
diff --git a/library/ssl_tls13_keys.h b/library/ssl_tls13_keys.h
index 384f433..165b58a 100644
--- a/library/ssl_tls13_keys.h
+++ b/library/ssl_tls13_keys.h
@@ -22,25 +22,27 @@
 /* This requires MBEDTLS_SSL_TLS1_3_LABEL( idx, name, string ) to be defined at
  * the point of use. See e.g. the definition of mbedtls_ssl_tls1_3_labels_union
  * below. */
-#define MBEDTLS_SSL_TLS1_3_LABEL_LIST                               \
-    MBEDTLS_SSL_TLS1_3_LABEL( finished    , "finished"     ) \
-    MBEDTLS_SSL_TLS1_3_LABEL( resumption  , "resumption"   ) \
-    MBEDTLS_SSL_TLS1_3_LABEL( traffic_upd , "traffic upd"  ) \
-    MBEDTLS_SSL_TLS1_3_LABEL( exporter    , "exporter"     ) \
-    MBEDTLS_SSL_TLS1_3_LABEL( key         , "key"          ) \
-    MBEDTLS_SSL_TLS1_3_LABEL( iv          , "iv"           ) \
-    MBEDTLS_SSL_TLS1_3_LABEL( c_hs_traffic, "c hs traffic" ) \
-    MBEDTLS_SSL_TLS1_3_LABEL( c_ap_traffic, "c ap traffic" ) \
-    MBEDTLS_SSL_TLS1_3_LABEL( c_e_traffic , "c e traffic"  ) \
-    MBEDTLS_SSL_TLS1_3_LABEL( s_hs_traffic, "s hs traffic" ) \
-    MBEDTLS_SSL_TLS1_3_LABEL( s_ap_traffic, "s ap traffic" ) \
-    MBEDTLS_SSL_TLS1_3_LABEL( s_e_traffic , "s e traffic"  ) \
-    MBEDTLS_SSL_TLS1_3_LABEL( e_exp_master, "e exp master" ) \
-    MBEDTLS_SSL_TLS1_3_LABEL( res_master  , "res master"   ) \
-    MBEDTLS_SSL_TLS1_3_LABEL( exp_master  , "exp master"   ) \
-    MBEDTLS_SSL_TLS1_3_LABEL( ext_binder  , "ext binder"   ) \
-    MBEDTLS_SSL_TLS1_3_LABEL( res_binder  , "res binder"   ) \
-    MBEDTLS_SSL_TLS1_3_LABEL( derived     , "derived"      )
+#define MBEDTLS_SSL_TLS1_3_LABEL_LIST                                             \
+    MBEDTLS_SSL_TLS1_3_LABEL( finished    , "finished"                          ) \
+    MBEDTLS_SSL_TLS1_3_LABEL( resumption  , "resumption"                        ) \
+    MBEDTLS_SSL_TLS1_3_LABEL( traffic_upd , "traffic upd"                       ) \
+    MBEDTLS_SSL_TLS1_3_LABEL( exporter    , "exporter"                          ) \
+    MBEDTLS_SSL_TLS1_3_LABEL( key         , "key"                               ) \
+    MBEDTLS_SSL_TLS1_3_LABEL( iv          , "iv"                                ) \
+    MBEDTLS_SSL_TLS1_3_LABEL( c_hs_traffic, "c hs traffic"                      ) \
+    MBEDTLS_SSL_TLS1_3_LABEL( c_ap_traffic, "c ap traffic"                      ) \
+    MBEDTLS_SSL_TLS1_3_LABEL( c_e_traffic , "c e traffic"                       ) \
+    MBEDTLS_SSL_TLS1_3_LABEL( s_hs_traffic, "s hs traffic"                      ) \
+    MBEDTLS_SSL_TLS1_3_LABEL( s_ap_traffic, "s ap traffic"                      ) \
+    MBEDTLS_SSL_TLS1_3_LABEL( s_e_traffic , "s e traffic"                       ) \
+    MBEDTLS_SSL_TLS1_3_LABEL( e_exp_master, "e exp master"                      ) \
+    MBEDTLS_SSL_TLS1_3_LABEL( res_master  , "res master"                        ) \
+    MBEDTLS_SSL_TLS1_3_LABEL( exp_master  , "exp master"                        ) \
+    MBEDTLS_SSL_TLS1_3_LABEL( ext_binder  , "ext binder"                        ) \
+    MBEDTLS_SSL_TLS1_3_LABEL( res_binder  , "res binder"                        ) \
+    MBEDTLS_SSL_TLS1_3_LABEL( derived     , "derived"                           ) \
+    MBEDTLS_SSL_TLS1_3_LABEL( client_cv   , "TLS 1.3, client CertificateVerify" ) \
+    MBEDTLS_SSL_TLS1_3_LABEL( server_cv   , "TLS 1.3, server CertificateVerify" )
 
 #define MBEDTLS_SSL_TLS1_3_LABEL( name, string )       \
     const unsigned char name    [ sizeof(string) - 1 ];
@@ -57,9 +59,12 @@
 
 extern const struct mbedtls_ssl_tls1_3_labels_struct mbedtls_ssl_tls1_3_labels;
 
+#define MBEDTLS_SSL_TLS1_3_LBL_LEN( LABEL )  \
+    sizeof(mbedtls_ssl_tls1_3_labels.LABEL)
+
 #define MBEDTLS_SSL_TLS1_3_LBL_WITH_LEN( LABEL )  \
     mbedtls_ssl_tls1_3_labels.LABEL,              \
-    sizeof(mbedtls_ssl_tls1_3_labels.LABEL)
+    MBEDTLS_SSL_TLS1_3_LBL_LEN( LABEL )
 
 #define MBEDTLS_SSL_TLS1_3_KEY_SCHEDULE_MAX_LABEL_LEN  \
     sizeof( union mbedtls_ssl_tls1_3_labels_union )
diff --git a/tests/ssl-opt.sh b/tests/ssl-opt.sh
index 9930210..0e78356 100755
--- a/tests/ssl-opt.sh
+++ b/tests/ssl-opt.sh
@@ -8831,8 +8831,11 @@
             -c "server hello, chosen ciphersuite: ( 1301 ) - TLS1-3-AES-128-GCM-SHA256" \
             -c "ECDH curve: x25519"         \
             -c "=> ssl_tls1_3_process_server_hello" \
+            -c "<= parse encrypted extensions"      \
             -c "Certificate verification flags clear" \
-            -c "<= parse encrypted extensions"
+            -c "=> parse certificate verify"          \
+            -c "<= parse certificate verify"          \
+            -c "mbedtls_ssl_tls13_process_certificate_verify() returned 0"
 
 requires_gnutls_tls1_3
 requires_gnutls_next_no_ticket
@@ -8861,8 +8864,11 @@
             -c "server hello, chosen ciphersuite: ( 1301 ) - TLS1-3-AES-128-GCM-SHA256" \
             -c "ECDH curve: x25519"         \
             -c "=> ssl_tls1_3_process_server_hello" \
+            -c "<= parse encrypted extensions"      \
             -c "Certificate verification flags clear" \
-            -c "<= parse encrypted extensions"
+            -c "=> parse certificate verify"          \
+            -c "<= parse certificate verify"          \
+            -c "mbedtls_ssl_tls13_process_certificate_verify() returned 0"
 
 # Test heap memory usage after handshake
 requires_config_enabled MBEDTLS_MEMORY_DEBUG