Subversion Repositories Kolibri OS

Rev

Blame | Last modification | View Log | Download | RSS feed

  1. /*
  2.  *  SSLv3/TLSv1 server-side functions
  3.  *
  4.  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  5.  *  SPDX-License-Identifier: GPL-2.0
  6.  *
  7.  *  This program is free software; you can redistribute it and/or modify
  8.  *  it under the terms of the GNU General Public License as published by
  9.  *  the Free Software Foundation; either version 2 of the License, or
  10.  *  (at your option) any later version.
  11.  *
  12.  *  This program is distributed in the hope that it will be useful,
  13.  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  14.  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  15.  *  GNU General Public License for more details.
  16.  *
  17.  *  You should have received a copy of the GNU General Public License along
  18.  *  with this program; if not, write to the Free Software Foundation, Inc.,
  19.  *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  20.  *
  21.  *  This file is part of mbed TLS (https://tls.mbed.org)
  22.  */
  23.  
  24. #if !defined(MBEDTLS_CONFIG_FILE)
  25. #include "mbedtls/config.h"
  26. #else
  27. #include MBEDTLS_CONFIG_FILE
  28. #endif
  29.  
  30. #if defined(MBEDTLS_SSL_SRV_C)
  31.  
  32. #if defined(MBEDTLS_PLATFORM_C)
  33. #include "mbedtls/platform.h"
  34. #else
  35. #include <stdlib.h>
  36. #define mbedtls_calloc    calloc
  37. #define mbedtls_free      free
  38. #endif
  39.  
  40. #include "mbedtls/debug.h"
  41. #include "mbedtls/ssl.h"
  42. #include "mbedtls/ssl_internal.h"
  43. #include "mbedtls/platform_util.h"
  44.  
  45. #include <string.h>
  46.  
  47. #if defined(MBEDTLS_ECP_C)
  48. #include "mbedtls/ecp.h"
  49. #endif
  50.  
  51. #if defined(MBEDTLS_HAVE_TIME)
  52. #include "mbedtls/platform_time.h"
  53. #endif
  54.  
  55. #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY)
  56. int mbedtls_ssl_set_client_transport_id( mbedtls_ssl_context *ssl,
  57.                                  const unsigned char *info,
  58.                                  size_t ilen )
  59. {
  60.     if( ssl->conf->endpoint != MBEDTLS_SSL_IS_SERVER )
  61.         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  62.  
  63.     mbedtls_free( ssl->cli_id );
  64.  
  65.     if( ( ssl->cli_id = mbedtls_calloc( 1, ilen ) ) == NULL )
  66.         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
  67.  
  68.     memcpy( ssl->cli_id, info, ilen );
  69.     ssl->cli_id_len = ilen;
  70.  
  71.     return( 0 );
  72. }
  73.  
  74. void mbedtls_ssl_conf_dtls_cookies( mbedtls_ssl_config *conf,
  75.                            mbedtls_ssl_cookie_write_t *f_cookie_write,
  76.                            mbedtls_ssl_cookie_check_t *f_cookie_check,
  77.                            void *p_cookie )
  78. {
  79.     conf->f_cookie_write = f_cookie_write;
  80.     conf->f_cookie_check = f_cookie_check;
  81.     conf->p_cookie       = p_cookie;
  82. }
  83. #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */
  84.  
  85. #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
  86. static int ssl_parse_servername_ext( mbedtls_ssl_context *ssl,
  87.                                      const unsigned char *buf,
  88.                                      size_t len )
  89. {
  90.     int ret;
  91.     size_t servername_list_size, hostname_len;
  92.     const unsigned char *p;
  93.  
  94.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "parse ServerName extension" ) );
  95.  
  96.     if( len < 2 )
  97.     {
  98.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
  99.         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  100.                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  101.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  102.     }
  103.     servername_list_size = ( ( buf[0] << 8 ) | ( buf[1] ) );
  104.     if( servername_list_size + 2 != len )
  105.     {
  106.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
  107.         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  108.                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  109.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  110.     }
  111.  
  112.     p = buf + 2;
  113.     while( servername_list_size > 2 )
  114.     {
  115.         hostname_len = ( ( p[1] << 8 ) | p[2] );
  116.         if( hostname_len + 3 > servername_list_size )
  117.         {
  118.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
  119.             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  120.                                             MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  121.             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  122.         }
  123.  
  124.         if( p[0] == MBEDTLS_TLS_EXT_SERVERNAME_HOSTNAME )
  125.         {
  126.             ret = ssl->conf->f_sni( ssl->conf->p_sni,
  127.                                     ssl, p + 3, hostname_len );
  128.             if( ret != 0 )
  129.             {
  130.                 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_sni_wrapper", ret );
  131.                 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  132.                         MBEDTLS_SSL_ALERT_MSG_UNRECOGNIZED_NAME );
  133.                 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  134.             }
  135.             return( 0 );
  136.         }
  137.  
  138.         servername_list_size -= hostname_len + 3;
  139.         p += hostname_len + 3;
  140.     }
  141.  
  142.     if( servername_list_size != 0 )
  143.     {
  144.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
  145.         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  146.                                         MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
  147.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  148.     }
  149.  
  150.     return( 0 );
  151. }
  152. #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
  153.  
  154. static int ssl_parse_renegotiation_info( mbedtls_ssl_context *ssl,
  155.                                          const unsigned char *buf,
  156.                                          size_t len )
  157. {
  158. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  159.     if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE )
  160.     {
  161.         /* Check verify-data in constant-time. The length OTOH is no secret */
  162.         if( len    != 1 + ssl->verify_data_len ||
  163.             buf[0] !=     ssl->verify_data_len ||
  164.             mbedtls_ssl_safer_memcmp( buf + 1, ssl->peer_verify_data,
  165.                           ssl->verify_data_len ) != 0 )
  166.         {
  167.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching renegotiation info" ) );
  168.             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  169.                                             MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
  170.             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  171.         }
  172.     }
  173.     else
  174. #endif /* MBEDTLS_SSL_RENEGOTIATION */
  175.     {
  176.         if( len != 1 || buf[0] != 0x0 )
  177.         {
  178.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-zero length renegotiation info" ) );
  179.             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  180.                                             MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
  181.             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  182.         }
  183.  
  184.         ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION;
  185.     }
  186.  
  187.     return( 0 );
  188. }
  189.  
  190. #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
  191.     defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
  192.  
  193. /*
  194.  * Status of the implementation of signature-algorithms extension:
  195.  *
  196.  * Currently, we are only considering the signature-algorithm extension
  197.  * to pick a ciphersuite which allows us to send the ServerKeyExchange
  198.  * message with a signature-hash combination that the user allows.
  199.  *
  200.  * We do *not* check whether all certificates in our certificate
  201.  * chain are signed with an allowed signature-hash pair.
  202.  * This needs to be done at a later stage.
  203.  *
  204.  */
  205. static int ssl_parse_signature_algorithms_ext( mbedtls_ssl_context *ssl,
  206.                                                const unsigned char *buf,
  207.                                                size_t len )
  208. {
  209.     size_t sig_alg_list_size;
  210.  
  211.     const unsigned char *p;
  212.     const unsigned char *end = buf + len;
  213.  
  214.     mbedtls_md_type_t md_cur;
  215.     mbedtls_pk_type_t sig_cur;
  216.  
  217.     if ( len < 2 ) {
  218.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
  219.         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  220.                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  221.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  222.     }
  223.     sig_alg_list_size = ( ( buf[0] << 8 ) | ( buf[1] ) );
  224.     if( sig_alg_list_size + 2 != len ||
  225.         sig_alg_list_size % 2 != 0 )
  226.     {
  227.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
  228.         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  229.                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  230.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  231.     }
  232.  
  233.     /* Currently we only guarantee signing the ServerKeyExchange message according
  234.      * to the constraints specified in this extension (see above), so it suffices
  235.      * to remember only one suitable hash for each possible signature algorithm.
  236.      *
  237.      * This will change when we also consider certificate signatures,
  238.      * in which case we will need to remember the whole signature-hash
  239.      * pair list from the extension.
  240.      */
  241.  
  242.     for( p = buf + 2; p < end; p += 2 )
  243.     {
  244.         /* Silently ignore unknown signature or hash algorithms. */
  245.  
  246.         if( ( sig_cur = mbedtls_ssl_pk_alg_from_sig( p[1] ) ) == MBEDTLS_PK_NONE )
  247.         {
  248.             MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext"
  249.                                         " unknown sig alg encoding %d", p[1] ) );
  250.             continue;
  251.         }
  252.  
  253.         /* Check if we support the hash the user proposes */
  254.         md_cur = mbedtls_ssl_md_alg_from_hash( p[0] );
  255.         if( md_cur == MBEDTLS_MD_NONE )
  256.         {
  257.             MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext:"
  258.                                         " unknown hash alg encoding %d", p[0] ) );
  259.             continue;
  260.         }
  261.  
  262.         if( mbedtls_ssl_check_sig_hash( ssl, md_cur ) == 0 )
  263.         {
  264.             mbedtls_ssl_sig_hash_set_add( &ssl->handshake->hash_algs, sig_cur, md_cur );
  265.             MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext:"
  266.                                         " match sig %d and hash %d",
  267.                                         sig_cur, md_cur ) );
  268.         }
  269.         else
  270.         {
  271.             MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext: "
  272.                                         "hash alg %d not supported", md_cur ) );
  273.         }
  274.     }
  275.  
  276.     return( 0 );
  277. }
  278. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&
  279.           MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
  280.  
  281. #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
  282.     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
  283. static int ssl_parse_supported_elliptic_curves( mbedtls_ssl_context *ssl,
  284.                                                 const unsigned char *buf,
  285.                                                 size_t len )
  286. {
  287.     size_t list_size, our_size;
  288.     const unsigned char *p;
  289.     const mbedtls_ecp_curve_info *curve_info, **curves;
  290.  
  291.     if ( len < 2 ) {
  292.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
  293.         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  294.                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  295.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  296.     }
  297.     list_size = ( ( buf[0] << 8 ) | ( buf[1] ) );
  298.     if( list_size + 2 != len ||
  299.         list_size % 2 != 0 )
  300.     {
  301.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
  302.         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  303.                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  304.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  305.     }
  306.  
  307.     /* Should never happen unless client duplicates the extension */
  308.     if( ssl->handshake->curves != NULL )
  309.     {
  310.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
  311.         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  312.                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  313.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  314.     }
  315.  
  316.     /* Don't allow our peer to make us allocate too much memory,
  317.      * and leave room for a final 0 */
  318.     our_size = list_size / 2 + 1;
  319.     if( our_size > MBEDTLS_ECP_DP_MAX )
  320.         our_size = MBEDTLS_ECP_DP_MAX;
  321.  
  322.     if( ( curves = mbedtls_calloc( our_size, sizeof( *curves ) ) ) == NULL )
  323.     {
  324.         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  325.                                         MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
  326.         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
  327.     }
  328.  
  329.     ssl->handshake->curves = curves;
  330.  
  331.     p = buf + 2;
  332.     while( list_size > 0 && our_size > 1 )
  333.     {
  334.         curve_info = mbedtls_ecp_curve_info_from_tls_id( ( p[0] << 8 ) | p[1] );
  335.  
  336.         if( curve_info != NULL )
  337.         {
  338.             *curves++ = curve_info;
  339.             our_size--;
  340.         }
  341.  
  342.         list_size -= 2;
  343.         p += 2;
  344.     }
  345.  
  346.     return( 0 );
  347. }
  348.  
  349. static int ssl_parse_supported_point_formats( mbedtls_ssl_context *ssl,
  350.                                               const unsigned char *buf,
  351.                                               size_t len )
  352. {
  353.     size_t list_size;
  354.     const unsigned char *p;
  355.  
  356.     if( len == 0 || (size_t)( buf[0] + 1 ) != len )
  357.     {
  358.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
  359.         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  360.                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  361.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  362.     }
  363.     list_size = buf[0];
  364.  
  365.     p = buf + 1;
  366.     while( list_size > 0 )
  367.     {
  368.         if( p[0] == MBEDTLS_ECP_PF_UNCOMPRESSED ||
  369.             p[0] == MBEDTLS_ECP_PF_COMPRESSED )
  370.         {
  371. #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C)
  372.             ssl->handshake->ecdh_ctx.point_format = p[0];
  373. #endif
  374. #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
  375.             ssl->handshake->ecjpake_ctx.point_format = p[0];
  376. #endif
  377.             MBEDTLS_SSL_DEBUG_MSG( 4, ( "point format selected: %d", p[0] ) );
  378.             return( 0 );
  379.         }
  380.  
  381.         list_size--;
  382.         p++;
  383.     }
  384.  
  385.     return( 0 );
  386. }
  387. #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
  388.           MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
  389.  
  390. #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
  391. static int ssl_parse_ecjpake_kkpp( mbedtls_ssl_context *ssl,
  392.                                    const unsigned char *buf,
  393.                                    size_t len )
  394. {
  395.     int ret;
  396.  
  397.     if( mbedtls_ecjpake_check( &ssl->handshake->ecjpake_ctx ) != 0 )
  398.     {
  399.         MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip ecjpake kkpp extension" ) );
  400.         return( 0 );
  401.     }
  402.  
  403.     if( ( ret = mbedtls_ecjpake_read_round_one( &ssl->handshake->ecjpake_ctx,
  404.                                                 buf, len ) ) != 0 )
  405.     {
  406.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_one", ret );
  407.         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  408.                                         MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
  409.         return( ret );
  410.     }
  411.  
  412.     /* Only mark the extension as OK when we're sure it is */
  413.     ssl->handshake->cli_exts |= MBEDTLS_TLS_EXT_ECJPAKE_KKPP_OK;
  414.  
  415.     return( 0 );
  416. }
  417. #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
  418.  
  419. #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
  420. static int ssl_parse_max_fragment_length_ext( mbedtls_ssl_context *ssl,
  421.                                               const unsigned char *buf,
  422.                                               size_t len )
  423. {
  424.     if( len != 1 || buf[0] >= MBEDTLS_SSL_MAX_FRAG_LEN_INVALID )
  425.     {
  426.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
  427.         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  428.                                         MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
  429.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  430.     }
  431.  
  432.     ssl->session_negotiate->mfl_code = buf[0];
  433.  
  434.     return( 0 );
  435. }
  436. #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
  437.  
  438. #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
  439. static int ssl_parse_truncated_hmac_ext( mbedtls_ssl_context *ssl,
  440.                                          const unsigned char *buf,
  441.                                          size_t len )
  442. {
  443.     if( len != 0 )
  444.     {
  445.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
  446.         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  447.                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  448.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  449.     }
  450.  
  451.     ((void) buf);
  452.  
  453.     if( ssl->conf->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_ENABLED )
  454.         ssl->session_negotiate->trunc_hmac = MBEDTLS_SSL_TRUNC_HMAC_ENABLED;
  455.  
  456.     return( 0 );
  457. }
  458. #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
  459.  
  460. #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
  461. static int ssl_parse_encrypt_then_mac_ext( mbedtls_ssl_context *ssl,
  462.                                       const unsigned char *buf,
  463.                                       size_t len )
  464. {
  465.     if( len != 0 )
  466.     {
  467.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
  468.         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  469.                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  470.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  471.     }
  472.  
  473.     ((void) buf);
  474.  
  475.     if( ssl->conf->encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED &&
  476.         ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_0 )
  477.     {
  478.         ssl->session_negotiate->encrypt_then_mac = MBEDTLS_SSL_ETM_ENABLED;
  479.     }
  480.  
  481.     return( 0 );
  482. }
  483. #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
  484.  
  485. #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
  486. static int ssl_parse_extended_ms_ext( mbedtls_ssl_context *ssl,
  487.                                       const unsigned char *buf,
  488.                                       size_t len )
  489. {
  490.     if( len != 0 )
  491.     {
  492.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
  493.         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  494.                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  495.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  496.     }
  497.  
  498.     ((void) buf);
  499.  
  500.     if( ssl->conf->extended_ms == MBEDTLS_SSL_EXTENDED_MS_ENABLED &&
  501.         ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_0 )
  502.     {
  503.         ssl->handshake->extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED;
  504.     }
  505.  
  506.     return( 0 );
  507. }
  508. #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
  509.  
  510. #if defined(MBEDTLS_SSL_SESSION_TICKETS)
  511. static int ssl_parse_session_ticket_ext( mbedtls_ssl_context *ssl,
  512.                                          unsigned char *buf,
  513.                                          size_t len )
  514. {
  515.     int ret;
  516.     mbedtls_ssl_session session;
  517.  
  518.     mbedtls_ssl_session_init( &session );
  519.  
  520.     if( ssl->conf->f_ticket_parse == NULL ||
  521.         ssl->conf->f_ticket_write == NULL )
  522.     {
  523.         return( 0 );
  524.     }
  525.  
  526.     /* Remember the client asked us to send a new ticket */
  527.     ssl->handshake->new_session_ticket = 1;
  528.  
  529.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket length: %d", len ) );
  530.  
  531.     if( len == 0 )
  532.         return( 0 );
  533.  
  534. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  535.     if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE )
  536.     {
  537.         MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket rejected: renegotiating" ) );
  538.         return( 0 );
  539.     }
  540. #endif /* MBEDTLS_SSL_RENEGOTIATION */
  541.  
  542.     /*
  543.      * Failures are ok: just ignore the ticket and proceed.
  544.      */
  545.     if( ( ret = ssl->conf->f_ticket_parse( ssl->conf->p_ticket, &session,
  546.                                            buf, len ) ) != 0 )
  547.     {
  548.         mbedtls_ssl_session_free( &session );
  549.  
  550.         if( ret == MBEDTLS_ERR_SSL_INVALID_MAC )
  551.             MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket is not authentic" ) );
  552.         else if( ret == MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED )
  553.             MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket is expired" ) );
  554.         else
  555.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_ticket_parse", ret );
  556.  
  557.         return( 0 );
  558.     }
  559.  
  560.     /*
  561.      * Keep the session ID sent by the client, since we MUST send it back to
  562.      * inform them we're accepting the ticket  (RFC 5077 section 3.4)
  563.      */
  564.     session.id_len = ssl->session_negotiate->id_len;
  565.     memcpy( &session.id, ssl->session_negotiate->id, session.id_len );
  566.  
  567.     mbedtls_ssl_session_free( ssl->session_negotiate );
  568.     memcpy( ssl->session_negotiate, &session, sizeof( mbedtls_ssl_session ) );
  569.  
  570.     /* Zeroize instead of free as we copied the content */
  571.     mbedtls_platform_zeroize( &session, sizeof( mbedtls_ssl_session ) );
  572.  
  573.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "session successfully restored from ticket" ) );
  574.  
  575.     ssl->handshake->resume = 1;
  576.  
  577.     /* Don't send a new ticket after all, this one is OK */
  578.     ssl->handshake->new_session_ticket = 0;
  579.  
  580.     return( 0 );
  581. }
  582. #endif /* MBEDTLS_SSL_SESSION_TICKETS */
  583.  
  584. #if defined(MBEDTLS_SSL_ALPN)
  585. static int ssl_parse_alpn_ext( mbedtls_ssl_context *ssl,
  586.                                const unsigned char *buf, size_t len )
  587. {
  588.     size_t list_len, cur_len, ours_len;
  589.     const unsigned char *theirs, *start, *end;
  590.     const char **ours;
  591.  
  592.     /* If ALPN not configured, just ignore the extension */
  593.     if( ssl->conf->alpn_list == NULL )
  594.         return( 0 );
  595.  
  596.     /*
  597.      * opaque ProtocolName<1..2^8-1>;
  598.      *
  599.      * struct {
  600.      *     ProtocolName protocol_name_list<2..2^16-1>
  601.      * } ProtocolNameList;
  602.      */
  603.  
  604.     /* Min length is 2 (list_len) + 1 (name_len) + 1 (name) */
  605.     if( len < 4 )
  606.     {
  607.         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  608.                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  609.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  610.     }
  611.  
  612.     list_len = ( buf[0] << 8 ) | buf[1];
  613.     if( list_len != len - 2 )
  614.     {
  615.         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  616.                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  617.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  618.     }
  619.  
  620.     /*
  621.      * Validate peer's list (lengths)
  622.      */
  623.     start = buf + 2;
  624.     end = buf + len;
  625.     for( theirs = start; theirs != end; theirs += cur_len )
  626.     {
  627.         cur_len = *theirs++;
  628.  
  629.         /* Current identifier must fit in list */
  630.         if( cur_len > (size_t)( end - theirs ) )
  631.         {
  632.             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  633.                                             MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  634.             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  635.         }
  636.  
  637.         /* Empty strings MUST NOT be included */
  638.         if( cur_len == 0 )
  639.         {
  640.             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  641.                                             MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
  642.             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  643.         }
  644.     }
  645.  
  646.     /*
  647.      * Use our order of preference
  648.      */
  649.     for( ours = ssl->conf->alpn_list; *ours != NULL; ours++ )
  650.     {
  651.         ours_len = strlen( *ours );
  652.         for( theirs = start; theirs != end; theirs += cur_len )
  653.         {
  654.             cur_len = *theirs++;
  655.  
  656.             if( cur_len == ours_len &&
  657.                 memcmp( theirs, *ours, cur_len ) == 0 )
  658.             {
  659.                 ssl->alpn_chosen = *ours;
  660.                 return( 0 );
  661.             }
  662.         }
  663.     }
  664.  
  665.     /* If we get there, no match was found */
  666.     mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  667.                             MBEDTLS_SSL_ALERT_MSG_NO_APPLICATION_PROTOCOL );
  668.     return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  669. }
  670. #endif /* MBEDTLS_SSL_ALPN */
  671.  
  672. /*
  673.  * Auxiliary functions for ServerHello parsing and related actions
  674.  */
  675.  
  676. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  677. /*
  678.  * Return 0 if the given key uses one of the acceptable curves, -1 otherwise
  679.  */
  680. #if defined(MBEDTLS_ECDSA_C)
  681. static int ssl_check_key_curve( mbedtls_pk_context *pk,
  682.                                 const mbedtls_ecp_curve_info **curves )
  683. {
  684.     const mbedtls_ecp_curve_info **crv = curves;
  685.     mbedtls_ecp_group_id grp_id = mbedtls_pk_ec( *pk )->grp.id;
  686.  
  687.     while( *crv != NULL )
  688.     {
  689.         if( (*crv)->grp_id == grp_id )
  690.             return( 0 );
  691.         crv++;
  692.     }
  693.  
  694.     return( -1 );
  695. }
  696. #endif /* MBEDTLS_ECDSA_C */
  697.  
  698. /*
  699.  * Try picking a certificate for this ciphersuite,
  700.  * return 0 on success and -1 on failure.
  701.  */
  702. static int ssl_pick_cert( mbedtls_ssl_context *ssl,
  703.                           const mbedtls_ssl_ciphersuite_t * ciphersuite_info )
  704. {
  705.     mbedtls_ssl_key_cert *cur, *list, *fallback = NULL;
  706.     mbedtls_pk_type_t pk_alg =
  707.         mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info );
  708.     uint32_t flags;
  709.  
  710. #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
  711.     if( ssl->handshake->sni_key_cert != NULL )
  712.         list = ssl->handshake->sni_key_cert;
  713.     else
  714. #endif
  715.         list = ssl->conf->key_cert;
  716.  
  717.     if( pk_alg == MBEDTLS_PK_NONE )
  718.         return( 0 );
  719.  
  720.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite requires certificate" ) );
  721.  
  722.     if( list == NULL )
  723.     {
  724.         MBEDTLS_SSL_DEBUG_MSG( 3, ( "server has no certificate" ) );
  725.         return( -1 );
  726.     }
  727.  
  728.     for( cur = list; cur != NULL; cur = cur->next )
  729.     {
  730.         MBEDTLS_SSL_DEBUG_CRT( 3, "candidate certificate chain, certificate",
  731.                           cur->cert );
  732.  
  733.         if( ! mbedtls_pk_can_do( &cur->cert->pk, pk_alg ) )
  734.         {
  735.             MBEDTLS_SSL_DEBUG_MSG( 3, ( "certificate mismatch: key type" ) );
  736.             continue;
  737.         }
  738.  
  739.         /*
  740.          * This avoids sending the client a cert it'll reject based on
  741.          * keyUsage or other extensions.
  742.          *
  743.          * It also allows the user to provision different certificates for
  744.          * different uses based on keyUsage, eg if they want to avoid signing
  745.          * and decrypting with the same RSA key.
  746.          */
  747.         if( mbedtls_ssl_check_cert_usage( cur->cert, ciphersuite_info,
  748.                                   MBEDTLS_SSL_IS_SERVER, &flags ) != 0 )
  749.         {
  750.             MBEDTLS_SSL_DEBUG_MSG( 3, ( "certificate mismatch: "
  751.                                 "(extended) key usage extension" ) );
  752.             continue;
  753.         }
  754.  
  755. #if defined(MBEDTLS_ECDSA_C)
  756.         if( pk_alg == MBEDTLS_PK_ECDSA &&
  757.             ssl_check_key_curve( &cur->cert->pk, ssl->handshake->curves ) != 0 )
  758.         {
  759.             MBEDTLS_SSL_DEBUG_MSG( 3, ( "certificate mismatch: elliptic curve" ) );
  760.             continue;
  761.         }
  762. #endif
  763.  
  764.         /*
  765.          * Try to select a SHA-1 certificate for pre-1.2 clients, but still
  766.          * present them a SHA-higher cert rather than failing if it's the only
  767.          * one we got that satisfies the other conditions.
  768.          */
  769.         if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 &&
  770.             cur->cert->sig_md != MBEDTLS_MD_SHA1 )
  771.         {
  772.             if( fallback == NULL )
  773.                 fallback = cur;
  774.             {
  775.                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "certificate not preferred: "
  776.                                     "sha-2 with pre-TLS 1.2 client" ) );
  777.             continue;
  778.             }
  779.         }
  780.  
  781.         /* If we get there, we got a winner */
  782.         break;
  783.     }
  784.  
  785.     if( cur == NULL )
  786.         cur = fallback;
  787.  
  788.     /* Do not update ssl->handshake->key_cert unless there is a match */
  789.     if( cur != NULL )
  790.     {
  791.         ssl->handshake->key_cert = cur;
  792.         MBEDTLS_SSL_DEBUG_CRT( 3, "selected certificate chain, certificate",
  793.                           ssl->handshake->key_cert->cert );
  794.         return( 0 );
  795.     }
  796.  
  797.     return( -1 );
  798. }
  799. #endif /* MBEDTLS_X509_CRT_PARSE_C */
  800.  
  801. /*
  802.  * Check if a given ciphersuite is suitable for use with our config/keys/etc
  803.  * Sets ciphersuite_info only if the suite matches.
  804.  */
  805. static int ssl_ciphersuite_match( mbedtls_ssl_context *ssl, int suite_id,
  806.                                   const mbedtls_ssl_ciphersuite_t **ciphersuite_info )
  807. {
  808.     const mbedtls_ssl_ciphersuite_t *suite_info;
  809.  
  810. #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
  811.     defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
  812.     mbedtls_pk_type_t sig_type;
  813. #endif
  814.  
  815.     suite_info = mbedtls_ssl_ciphersuite_from_id( suite_id );
  816.     if( suite_info == NULL )
  817.     {
  818.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  819.         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  820.     }
  821.  
  822.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "trying ciphersuite: %s", suite_info->name ) );
  823.  
  824.     if( suite_info->min_minor_ver > ssl->minor_ver ||
  825.         suite_info->max_minor_ver < ssl->minor_ver )
  826.     {
  827.         MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: version" ) );
  828.         return( 0 );
  829.     }
  830.  
  831. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  832.     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  833.         ( suite_info->flags & MBEDTLS_CIPHERSUITE_NODTLS ) )
  834.         return( 0 );
  835. #endif
  836.  
  837. #if defined(MBEDTLS_ARC4_C)
  838.     if( ssl->conf->arc4_disabled == MBEDTLS_SSL_ARC4_DISABLED &&
  839.             suite_info->cipher == MBEDTLS_CIPHER_ARC4_128 )
  840.     {
  841.         MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: rc4" ) );
  842.         return( 0 );
  843.     }
  844. #endif
  845.  
  846. #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
  847.     if( suite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE &&
  848.         ( ssl->handshake->cli_exts & MBEDTLS_TLS_EXT_ECJPAKE_KKPP_OK ) == 0 )
  849.     {
  850.         MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: ecjpake "
  851.                                     "not configured or ext missing" ) );
  852.         return( 0 );
  853.     }
  854. #endif
  855.  
  856.  
  857. #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C)
  858.     if( mbedtls_ssl_ciphersuite_uses_ec( suite_info ) &&
  859.         ( ssl->handshake->curves == NULL ||
  860.           ssl->handshake->curves[0] == NULL ) )
  861.     {
  862.         MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: "
  863.                             "no common elliptic curve" ) );
  864.         return( 0 );
  865.     }
  866. #endif
  867.  
  868. #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
  869.     /* If the ciphersuite requires a pre-shared key and we don't
  870.      * have one, skip it now rather than failing later */
  871.     if( mbedtls_ssl_ciphersuite_uses_psk( suite_info ) &&
  872.         ssl->conf->f_psk == NULL &&
  873.         ( ssl->conf->psk == NULL || ssl->conf->psk_identity == NULL ||
  874.           ssl->conf->psk_identity_len == 0 || ssl->conf->psk_len == 0 ) )
  875.     {
  876.         MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: no pre-shared key" ) );
  877.         return( 0 );
  878.     }
  879. #endif
  880.  
  881. #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
  882.     defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
  883.     /* If the ciphersuite requires signing, check whether
  884.      * a suitable hash algorithm is present. */
  885.     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
  886.     {
  887.         sig_type = mbedtls_ssl_get_ciphersuite_sig_alg( suite_info );
  888.         if( sig_type != MBEDTLS_PK_NONE &&
  889.             mbedtls_ssl_sig_hash_set_find( &ssl->handshake->hash_algs, sig_type ) == MBEDTLS_MD_NONE )
  890.         {
  891.             MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: no suitable hash algorithm "
  892.                                         "for signature algorithm %d", sig_type ) );
  893.             return( 0 );
  894.         }
  895.     }
  896.  
  897. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&
  898.           MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
  899.  
  900. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  901.     /*
  902.      * Final check: if ciphersuite requires us to have a
  903.      * certificate/key of a particular type:
  904.      * - select the appropriate certificate if we have one, or
  905.      * - try the next ciphersuite if we don't
  906.      * This must be done last since we modify the key_cert list.
  907.      */
  908.     if( ssl_pick_cert( ssl, suite_info ) != 0 )
  909.     {
  910.         MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: "
  911.                             "no suitable certificate" ) );
  912.         return( 0 );
  913.     }
  914. #endif
  915.  
  916.     *ciphersuite_info = suite_info;
  917.     return( 0 );
  918. }
  919.  
  920. #if defined(MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO)
  921. static int ssl_parse_client_hello_v2( mbedtls_ssl_context *ssl )
  922. {
  923.     int ret, got_common_suite;
  924.     unsigned int i, j;
  925.     size_t n;
  926.     unsigned int ciph_len, sess_len, chal_len;
  927.     unsigned char *buf, *p;
  928.     const int *ciphersuites;
  929.     const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
  930.  
  931.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse client hello v2" ) );
  932.  
  933. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  934.     if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE )
  935.     {
  936.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "client hello v2 illegal for renegotiation" ) );
  937.         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  938.                                         MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
  939.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  940.     }
  941. #endif /* MBEDTLS_SSL_RENEGOTIATION */
  942.  
  943.     buf = ssl->in_hdr;
  944.  
  945.     MBEDTLS_SSL_DEBUG_BUF( 4, "record header", buf, 5 );
  946.  
  947.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v2, message type: %d",
  948.                    buf[2] ) );
  949.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v2, message len.: %d",
  950.                    ( ( buf[0] & 0x7F ) << 8 ) | buf[1] ) );
  951.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v2, max. version: [%d:%d]",
  952.                    buf[3], buf[4] ) );
  953.  
  954.     /*
  955.      * SSLv2 Client Hello
  956.      *
  957.      * Record layer:
  958.      *     0  .   1   message length
  959.      *
  960.      * SSL layer:
  961.      *     2  .   2   message type
  962.      *     3  .   4   protocol version
  963.      */
  964.     if( buf[2] != MBEDTLS_SSL_HS_CLIENT_HELLO ||
  965.         buf[3] != MBEDTLS_SSL_MAJOR_VERSION_3 )
  966.     {
  967.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
  968.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  969.     }
  970.  
  971.     n = ( ( buf[0] << 8 ) | buf[1] ) & 0x7FFF;
  972.  
  973.     if( n < 17 || n > 512 )
  974.     {
  975.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
  976.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  977.     }
  978.  
  979.     ssl->major_ver = MBEDTLS_SSL_MAJOR_VERSION_3;
  980.     ssl->minor_ver = ( buf[4] <= ssl->conf->max_minor_ver )
  981.                      ? buf[4]  : ssl->conf->max_minor_ver;
  982.  
  983.     if( ssl->minor_ver < ssl->conf->min_minor_ver )
  984.     {
  985.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "client only supports ssl smaller than minimum"
  986.                             " [%d:%d] < [%d:%d]",
  987.                             ssl->major_ver, ssl->minor_ver,
  988.                             ssl->conf->min_major_ver, ssl->conf->min_minor_ver ) );
  989.  
  990.         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  991.                                      MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION );
  992.         return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION );
  993.     }
  994.  
  995.     ssl->handshake->max_major_ver = buf[3];
  996.     ssl->handshake->max_minor_ver = buf[4];
  997.  
  998.     if( ( ret = mbedtls_ssl_fetch_input( ssl, 2 + n ) ) != 0 )
  999.     {
  1000.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret );
  1001.         return( ret );
  1002.     }
  1003.  
  1004.     ssl->handshake->update_checksum( ssl, buf + 2, n );
  1005.  
  1006.     buf = ssl->in_msg;
  1007.     n = ssl->in_left - 5;
  1008.  
  1009.     /*
  1010.      *    0  .   1   ciphersuitelist length
  1011.      *    2  .   3   session id length
  1012.      *    4  .   5   challenge length
  1013.      *    6  .  ..   ciphersuitelist
  1014.      *   ..  .  ..   session id
  1015.      *   ..  .  ..   challenge
  1016.      */
  1017.     MBEDTLS_SSL_DEBUG_BUF( 4, "record contents", buf, n );
  1018.  
  1019.     ciph_len = ( buf[0] << 8 ) | buf[1];
  1020.     sess_len = ( buf[2] << 8 ) | buf[3];
  1021.     chal_len = ( buf[4] << 8 ) | buf[5];
  1022.  
  1023.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciph_len: %d, sess_len: %d, chal_len: %d",
  1024.                    ciph_len, sess_len, chal_len ) );
  1025.  
  1026.     /*
  1027.      * Make sure each parameter length is valid
  1028.      */
  1029.     if( ciph_len < 3 || ( ciph_len % 3 ) != 0 )
  1030.     {
  1031.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
  1032.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  1033.     }
  1034.  
  1035.     if( sess_len > 32 )
  1036.     {
  1037.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
  1038.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  1039.     }
  1040.  
  1041.     if( chal_len < 8 || chal_len > 32 )
  1042.     {
  1043.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
  1044.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  1045.     }
  1046.  
  1047.     if( n != 6 + ciph_len + sess_len + chal_len )
  1048.     {
  1049.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
  1050.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  1051.     }
  1052.  
  1053.     MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, ciphersuitelist",
  1054.                    buf + 6, ciph_len );
  1055.     MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, session id",
  1056.                    buf + 6 + ciph_len, sess_len );
  1057.     MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, challenge",
  1058.                    buf + 6 + ciph_len + sess_len, chal_len );
  1059.  
  1060.     p = buf + 6 + ciph_len;
  1061.     ssl->session_negotiate->id_len = sess_len;
  1062.     memset( ssl->session_negotiate->id, 0,
  1063.             sizeof( ssl->session_negotiate->id ) );
  1064.     memcpy( ssl->session_negotiate->id, p, ssl->session_negotiate->id_len );
  1065.  
  1066.     p += sess_len;
  1067.     memset( ssl->handshake->randbytes, 0, 64 );
  1068.     memcpy( ssl->handshake->randbytes + 32 - chal_len, p, chal_len );
  1069.  
  1070.     /*
  1071.      * Check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV
  1072.      */
  1073.     for( i = 0, p = buf + 6; i < ciph_len; i += 3, p += 3 )
  1074.     {
  1075.         if( p[0] == 0 && p[1] == 0 && p[2] == MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO )
  1076.         {
  1077.             MBEDTLS_SSL_DEBUG_MSG( 3, ( "received TLS_EMPTY_RENEGOTIATION_INFO " ) );
  1078. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  1079.             if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
  1080.             {
  1081.                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "received RENEGOTIATION SCSV "
  1082.                                     "during renegotiation" ) );
  1083.  
  1084.                 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  1085.                                                 MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
  1086.                 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  1087.             }
  1088. #endif /* MBEDTLS_SSL_RENEGOTIATION */
  1089.             ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION;
  1090.             break;
  1091.         }
  1092.     }
  1093.  
  1094. #if defined(MBEDTLS_SSL_FALLBACK_SCSV)
  1095.     for( i = 0, p = buf + 6; i < ciph_len; i += 3, p += 3 )
  1096.     {
  1097.         if( p[0] == 0 &&
  1098.             p[1] == (unsigned char)( ( MBEDTLS_SSL_FALLBACK_SCSV_VALUE >> 8 ) & 0xff ) &&
  1099.             p[2] == (unsigned char)( ( MBEDTLS_SSL_FALLBACK_SCSV_VALUE      ) & 0xff ) )
  1100.         {
  1101.             MBEDTLS_SSL_DEBUG_MSG( 3, ( "received FALLBACK_SCSV" ) );
  1102.  
  1103.             if( ssl->minor_ver < ssl->conf->max_minor_ver )
  1104.             {
  1105.                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "inapropriate fallback" ) );
  1106.  
  1107.                 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  1108.                                         MBEDTLS_SSL_ALERT_MSG_INAPROPRIATE_FALLBACK );
  1109.  
  1110.                 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  1111.             }
  1112.  
  1113.             break;
  1114.         }
  1115.     }
  1116. #endif /* MBEDTLS_SSL_FALLBACK_SCSV */
  1117.  
  1118.     got_common_suite = 0;
  1119.     ciphersuites = ssl->conf->ciphersuite_list[ssl->minor_ver];
  1120.     ciphersuite_info = NULL;
  1121. #if defined(MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE)
  1122.     for( j = 0, p = buf + 6; j < ciph_len; j += 3, p += 3 )
  1123.         for( i = 0; ciphersuites[i] != 0; i++ )
  1124. #else
  1125.     for( i = 0; ciphersuites[i] != 0; i++ )
  1126.         for( j = 0, p = buf + 6; j < ciph_len; j += 3, p += 3 )
  1127. #endif
  1128.         {
  1129.             if( p[0] != 0 ||
  1130.                 p[1] != ( ( ciphersuites[i] >> 8 ) & 0xFF ) ||
  1131.                 p[2] != ( ( ciphersuites[i]      ) & 0xFF ) )
  1132.                 continue;
  1133.  
  1134.             got_common_suite = 1;
  1135.  
  1136.             if( ( ret = ssl_ciphersuite_match( ssl, ciphersuites[i],
  1137.                                                &ciphersuite_info ) ) != 0 )
  1138.                 return( ret );
  1139.  
  1140.             if( ciphersuite_info != NULL )
  1141.                 goto have_ciphersuite_v2;
  1142.         }
  1143.  
  1144.     if( got_common_suite )
  1145.     {
  1146.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "got ciphersuites in common, "
  1147.                             "but none of them usable" ) );
  1148.         return( MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE );
  1149.     }
  1150.     else
  1151.     {
  1152.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no ciphersuites in common" ) );
  1153.         return( MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN );
  1154.     }
  1155.  
  1156. have_ciphersuite_v2:
  1157.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "selected ciphersuite: %s", ciphersuite_info->name ) );
  1158.  
  1159.     ssl->session_negotiate->ciphersuite = ciphersuites[i];
  1160.     ssl->transform_negotiate->ciphersuite_info = ciphersuite_info;
  1161.  
  1162.     /*
  1163.      * SSLv2 Client Hello relevant renegotiation security checks
  1164.      */
  1165.     if( ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
  1166.         ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE )
  1167.     {
  1168.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation, breaking off handshake" ) );
  1169.         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  1170.                                         MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
  1171.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  1172.     }
  1173.  
  1174.     ssl->in_left = 0;
  1175.     ssl->state++;
  1176.  
  1177.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse client hello v2" ) );
  1178.  
  1179.     return( 0 );
  1180. }
  1181. #endif /* MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO */
  1182.  
  1183. /* This function doesn't alert on errors that happen early during
  1184.    ClientHello parsing because they might indicate that the client is
  1185.    not talking SSL/TLS at all and would not understand our alert. */
  1186. static int ssl_parse_client_hello( mbedtls_ssl_context *ssl )
  1187. {
  1188.     int ret, got_common_suite;
  1189.     size_t i, j;
  1190.     size_t ciph_offset, comp_offset, ext_offset;
  1191.     size_t msg_len, ciph_len, sess_len, comp_len, ext_len;
  1192. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  1193.     size_t cookie_offset, cookie_len;
  1194. #endif
  1195.     unsigned char *buf, *p, *ext;
  1196. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  1197.     int renegotiation_info_seen = 0;
  1198. #endif
  1199.     int handshake_failure = 0;
  1200.     const int *ciphersuites;
  1201.     const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
  1202.     int major, minor;
  1203.  
  1204.     /* If there is no signature-algorithm extension present,
  1205.      * we need to fall back to the default values for allowed
  1206.      * signature-hash pairs. */
  1207. #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
  1208.     defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
  1209.     int sig_hash_alg_ext_present = 0;
  1210. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&
  1211.           MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
  1212.  
  1213.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse client hello" ) );
  1214.  
  1215. #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
  1216. read_record_header:
  1217. #endif
  1218.     /*
  1219.      * If renegotiating, then the input was read with mbedtls_ssl_read_record(),
  1220.      * otherwise read it ourselves manually in order to support SSLv2
  1221.      * ClientHello, which doesn't use the same record layer format.
  1222.      */
  1223. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  1224.     if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE )
  1225. #endif
  1226.     {
  1227.         if( ( ret = mbedtls_ssl_fetch_input( ssl, 5 ) ) != 0 )
  1228.         {
  1229.             /* No alert on a read error. */
  1230.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret );
  1231.             return( ret );
  1232.         }
  1233.     }
  1234.  
  1235.     buf = ssl->in_hdr;
  1236.  
  1237. #if defined(MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO)
  1238. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  1239.     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_STREAM )
  1240. #endif
  1241.         if( ( buf[0] & 0x80 ) != 0 )
  1242.             return( ssl_parse_client_hello_v2( ssl ) );
  1243. #endif
  1244.  
  1245.     MBEDTLS_SSL_DEBUG_BUF( 4, "record header", buf, mbedtls_ssl_hdr_len( ssl ) );
  1246.  
  1247.     /*
  1248.      * SSLv3/TLS Client Hello
  1249.      *
  1250.      * Record layer:
  1251.      *     0  .   0   message type
  1252.      *     1  .   2   protocol version
  1253.      *     3  .   11  DTLS: epoch + record sequence number
  1254.      *     3  .   4   message length
  1255.      */
  1256.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, message type: %d",
  1257.                    buf[0] ) );
  1258.  
  1259.     if( buf[0] != MBEDTLS_SSL_MSG_HANDSHAKE )
  1260.     {
  1261.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
  1262.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  1263.     }
  1264.  
  1265.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, message len.: %d",
  1266.                    ( ssl->in_len[0] << 8 ) | ssl->in_len[1] ) );
  1267.  
  1268.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, protocol version: [%d:%d]",
  1269.                    buf[1], buf[2] ) );
  1270.  
  1271.     mbedtls_ssl_read_version( &major, &minor, ssl->conf->transport, buf + 1 );
  1272.  
  1273.     /* According to RFC 5246 Appendix E.1, the version here is typically
  1274.      * "{03,00}, the lowest version number supported by the client, [or] the
  1275.      * value of ClientHello.client_version", so the only meaningful check here
  1276.      * is the major version shouldn't be less than 3 */
  1277.     if( major < MBEDTLS_SSL_MAJOR_VERSION_3 )
  1278.     {
  1279.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
  1280.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  1281.     }
  1282.  
  1283.     /* For DTLS if this is the initial handshake, remember the client sequence
  1284.      * number to use it in our next message (RFC 6347 4.2.1) */
  1285. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  1286.     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM
  1287. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  1288.         && ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE
  1289. #endif
  1290.         )
  1291.     {
  1292.         /* Epoch should be 0 for initial handshakes */
  1293.         if( ssl->in_ctr[0] != 0 || ssl->in_ctr[1] != 0 )
  1294.         {
  1295.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
  1296.             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  1297.         }
  1298.  
  1299.         memcpy( ssl->cur_out_ctr + 2, ssl->in_ctr + 2, 6 );
  1300.  
  1301. #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
  1302.         if( mbedtls_ssl_dtls_replay_check( ssl ) != 0 )
  1303.         {
  1304.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "replayed record, discarding" ) );
  1305.             ssl->next_record_offset = 0;
  1306.             ssl->in_left = 0;
  1307.             goto read_record_header;
  1308.         }
  1309.  
  1310.         /* No MAC to check yet, so we can update right now */
  1311.         mbedtls_ssl_dtls_replay_update( ssl );
  1312. #endif
  1313.     }
  1314. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  1315.  
  1316.     msg_len = ( ssl->in_len[0] << 8 ) | ssl->in_len[1];
  1317.  
  1318. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  1319.     if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE )
  1320.     {
  1321.         /* Set by mbedtls_ssl_read_record() */
  1322.         msg_len = ssl->in_hslen;
  1323.     }
  1324.     else
  1325. #endif
  1326.     {
  1327.         if( msg_len > MBEDTLS_SSL_IN_CONTENT_LEN )
  1328.         {
  1329.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
  1330.             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  1331.         }
  1332.  
  1333.         if( ( ret = mbedtls_ssl_fetch_input( ssl,
  1334.                        mbedtls_ssl_hdr_len( ssl ) + msg_len ) ) != 0 )
  1335.         {
  1336.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret );
  1337.             return( ret );
  1338.         }
  1339.  
  1340.     /* Done reading this record, get ready for the next one */
  1341. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  1342.         if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  1343.             ssl->next_record_offset = msg_len + mbedtls_ssl_hdr_len( ssl );
  1344.         else
  1345. #endif
  1346.             ssl->in_left = 0;
  1347.     }
  1348.  
  1349.     buf = ssl->in_msg;
  1350.  
  1351.     MBEDTLS_SSL_DEBUG_BUF( 4, "record contents", buf, msg_len );
  1352.  
  1353.     ssl->handshake->update_checksum( ssl, buf, msg_len );
  1354.  
  1355.     /*
  1356.      * Handshake layer:
  1357.      *     0  .   0   handshake type
  1358.      *     1  .   3   handshake length
  1359.      *     4  .   5   DTLS only: message seqence number
  1360.      *     6  .   8   DTLS only: fragment offset
  1361.      *     9  .  11   DTLS only: fragment length
  1362.      */
  1363.     if( msg_len < mbedtls_ssl_hs_hdr_len( ssl ) )
  1364.     {
  1365.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
  1366.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  1367.     }
  1368.  
  1369.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, handshake type: %d", buf[0] ) );
  1370.  
  1371.     if( buf[0] != MBEDTLS_SSL_HS_CLIENT_HELLO )
  1372.     {
  1373.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
  1374.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  1375.     }
  1376.  
  1377.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, handshake len.: %d",
  1378.                    ( buf[1] << 16 ) | ( buf[2] << 8 ) | buf[3] ) );
  1379.  
  1380.     /* We don't support fragmentation of ClientHello (yet?) */
  1381.     if( buf[1] != 0 ||
  1382.         msg_len != mbedtls_ssl_hs_hdr_len( ssl ) + ( ( buf[2] << 8 ) | buf[3] ) )
  1383.     {
  1384.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
  1385.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  1386.     }
  1387.  
  1388. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  1389.     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  1390.     {
  1391.         /*
  1392.          * Copy the client's handshake message_seq on initial handshakes,
  1393.          * check sequence number on renego.
  1394.          */
  1395. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  1396.         if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
  1397.         {
  1398.             /* This couldn't be done in ssl_prepare_handshake_record() */
  1399.             unsigned int cli_msg_seq = ( ssl->in_msg[4] << 8 ) |
  1400.                                          ssl->in_msg[5];
  1401.  
  1402.             if( cli_msg_seq != ssl->handshake->in_msg_seq )
  1403.             {
  1404.                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message_seq: "
  1405.                                     "%d (expected %d)", cli_msg_seq,
  1406.                                     ssl->handshake->in_msg_seq ) );
  1407.                 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  1408.             }
  1409.  
  1410.             ssl->handshake->in_msg_seq++;
  1411.         }
  1412.         else
  1413. #endif
  1414.         {
  1415.             unsigned int cli_msg_seq = ( ssl->in_msg[4] << 8 ) |
  1416.                                          ssl->in_msg[5];
  1417.             ssl->handshake->out_msg_seq = cli_msg_seq;
  1418.             ssl->handshake->in_msg_seq  = cli_msg_seq + 1;
  1419.         }
  1420.  
  1421.         /*
  1422.          * For now we don't support fragmentation, so make sure
  1423.          * fragment_offset == 0 and fragment_length == length
  1424.          */
  1425.         if( ssl->in_msg[6] != 0 || ssl->in_msg[7] != 0 || ssl->in_msg[8] != 0 ||
  1426.             memcmp( ssl->in_msg + 1, ssl->in_msg + 9, 3 ) != 0 )
  1427.         {
  1428.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "ClientHello fragmentation not supported" ) );
  1429.             return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
  1430.         }
  1431.     }
  1432. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  1433.  
  1434.     buf += mbedtls_ssl_hs_hdr_len( ssl );
  1435.     msg_len -= mbedtls_ssl_hs_hdr_len( ssl );
  1436.  
  1437.     /*
  1438.      * ClientHello layer:
  1439.      *     0  .   1   protocol version
  1440.      *     2  .  33   random bytes (starting with 4 bytes of Unix time)
  1441.      *    34  .  35   session id length (1 byte)
  1442.      *    35  . 34+x  session id
  1443.      *   35+x . 35+x  DTLS only: cookie length (1 byte)
  1444.      *   36+x .  ..   DTLS only: cookie
  1445.      *    ..  .  ..   ciphersuite list length (2 bytes)
  1446.      *    ..  .  ..   ciphersuite list
  1447.      *    ..  .  ..   compression alg. list length (1 byte)
  1448.      *    ..  .  ..   compression alg. list
  1449.      *    ..  .  ..   extensions length (2 bytes, optional)
  1450.      *    ..  .  ..   extensions (optional)
  1451.      */
  1452.  
  1453.     /*
  1454.      * Minimal length (with everything empty and extensions omitted) is
  1455.      * 2 + 32 + 1 + 2 + 1 = 38 bytes. Check that first, so that we can
  1456.      * read at least up to session id length without worrying.
  1457.      */
  1458.     if( msg_len < 38 )
  1459.     {
  1460.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
  1461.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  1462.     }
  1463.  
  1464.     /*
  1465.      * Check and save the protocol version
  1466.      */
  1467.     MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, version", buf, 2 );
  1468.  
  1469.     mbedtls_ssl_read_version( &ssl->major_ver, &ssl->minor_ver,
  1470.                       ssl->conf->transport, buf );
  1471.  
  1472.     ssl->handshake->max_major_ver = ssl->major_ver;
  1473.     ssl->handshake->max_minor_ver = ssl->minor_ver;
  1474.  
  1475.     if( ssl->major_ver < ssl->conf->min_major_ver ||
  1476.         ssl->minor_ver < ssl->conf->min_minor_ver )
  1477.     {
  1478.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "client only supports ssl smaller than minimum"
  1479.                             " [%d:%d] < [%d:%d]",
  1480.                             ssl->major_ver, ssl->minor_ver,
  1481.                             ssl->conf->min_major_ver, ssl->conf->min_minor_ver ) );
  1482.         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  1483.                                      MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION );
  1484.         return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION );
  1485.     }
  1486.  
  1487.     if( ssl->major_ver > ssl->conf->max_major_ver )
  1488.     {
  1489.         ssl->major_ver = ssl->conf->max_major_ver;
  1490.         ssl->minor_ver = ssl->conf->max_minor_ver;
  1491.     }
  1492.     else if( ssl->minor_ver > ssl->conf->max_minor_ver )
  1493.         ssl->minor_ver = ssl->conf->max_minor_ver;
  1494.  
  1495.     /*
  1496.      * Save client random (inc. Unix time)
  1497.      */
  1498.     MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, random bytes", buf + 2, 32 );
  1499.  
  1500.     memcpy( ssl->handshake->randbytes, buf + 2, 32 );
  1501.  
  1502.     /*
  1503.      * Check the session ID length and save session ID
  1504.      */
  1505.     sess_len = buf[34];
  1506.  
  1507.     if( sess_len > sizeof( ssl->session_negotiate->id ) ||
  1508.         sess_len + 34 + 2 > msg_len ) /* 2 for cipherlist length field */
  1509.     {
  1510.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
  1511.         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  1512.                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  1513.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  1514.     }
  1515.  
  1516.     MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, session id", buf + 35, sess_len );
  1517.  
  1518.     ssl->session_negotiate->id_len = sess_len;
  1519.     memset( ssl->session_negotiate->id, 0,
  1520.             sizeof( ssl->session_negotiate->id ) );
  1521.     memcpy( ssl->session_negotiate->id, buf + 35,
  1522.             ssl->session_negotiate->id_len );
  1523.  
  1524.     /*
  1525.      * Check the cookie length and content
  1526.      */
  1527. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  1528.     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  1529.     {
  1530.         cookie_offset = 35 + sess_len;
  1531.         cookie_len = buf[cookie_offset];
  1532.  
  1533.         if( cookie_offset + 1 + cookie_len + 2 > msg_len )
  1534.         {
  1535.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
  1536.             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  1537.                                             MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION );
  1538.             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  1539.         }
  1540.  
  1541.         MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, cookie",
  1542.                        buf + cookie_offset + 1, cookie_len );
  1543.  
  1544. #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY)
  1545.         if( ssl->conf->f_cookie_check != NULL
  1546. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  1547.             && ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE
  1548. #endif
  1549.             )
  1550.         {
  1551.             if( ssl->conf->f_cookie_check( ssl->conf->p_cookie,
  1552.                                      buf + cookie_offset + 1, cookie_len,
  1553.                                      ssl->cli_id, ssl->cli_id_len ) != 0 )
  1554.             {
  1555.                 MBEDTLS_SSL_DEBUG_MSG( 2, ( "cookie verification failed" ) );
  1556.                 ssl->handshake->verify_cookie_len = 1;
  1557.             }
  1558.             else
  1559.             {
  1560.                 MBEDTLS_SSL_DEBUG_MSG( 2, ( "cookie verification passed" ) );
  1561.                 ssl->handshake->verify_cookie_len = 0;
  1562.             }
  1563.         }
  1564.         else
  1565. #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */
  1566.         {
  1567.             /* We know we didn't send a cookie, so it should be empty */
  1568.             if( cookie_len != 0 )
  1569.             {
  1570.                 /* This may be an attacker's probe, so don't send an alert */
  1571.                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
  1572.                 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  1573.             }
  1574.  
  1575.             MBEDTLS_SSL_DEBUG_MSG( 2, ( "cookie verification skipped" ) );
  1576.         }
  1577.  
  1578.     /*
  1579.      * Check the ciphersuitelist length (will be parsed later)
  1580.      */
  1581.         ciph_offset = cookie_offset + 1 + cookie_len;
  1582.     }
  1583.     else
  1584. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  1585.         ciph_offset = 35 + sess_len;
  1586.  
  1587.     ciph_len = ( buf[ciph_offset + 0] << 8 )
  1588.              | ( buf[ciph_offset + 1]      );
  1589.  
  1590.     if( ciph_len < 2 ||
  1591.         ciph_len + 2 + ciph_offset + 1 > msg_len || /* 1 for comp. alg. len */
  1592.         ( ciph_len % 2 ) != 0 )
  1593.     {
  1594.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
  1595.         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  1596.                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  1597.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  1598.     }
  1599.  
  1600.     MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, ciphersuitelist",
  1601.                    buf + ciph_offset + 2,  ciph_len );
  1602.  
  1603.     /*
  1604.      * Check the compression algorithms length and pick one
  1605.      */
  1606.     comp_offset = ciph_offset + 2 + ciph_len;
  1607.  
  1608.     comp_len = buf[comp_offset];
  1609.  
  1610.     if( comp_len < 1 ||
  1611.         comp_len > 16 ||
  1612.         comp_len + comp_offset + 1 > msg_len )
  1613.     {
  1614.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
  1615.         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  1616.                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  1617.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  1618.     }
  1619.  
  1620.     MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, compression",
  1621.                       buf + comp_offset + 1, comp_len );
  1622.  
  1623.     ssl->session_negotiate->compression = MBEDTLS_SSL_COMPRESS_NULL;
  1624. #if defined(MBEDTLS_ZLIB_SUPPORT)
  1625.     for( i = 0; i < comp_len; ++i )
  1626.     {
  1627.         if( buf[comp_offset + 1 + i] == MBEDTLS_SSL_COMPRESS_DEFLATE )
  1628.         {
  1629.             ssl->session_negotiate->compression = MBEDTLS_SSL_COMPRESS_DEFLATE;
  1630.             break;
  1631.         }
  1632.     }
  1633. #endif
  1634.  
  1635.     /* See comments in ssl_write_client_hello() */
  1636. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  1637.     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  1638.         ssl->session_negotiate->compression = MBEDTLS_SSL_COMPRESS_NULL;
  1639. #endif
  1640.  
  1641.     /* Do not parse the extensions if the protocol is SSLv3 */
  1642. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  1643.     if( ( ssl->major_ver != 3 ) || ( ssl->minor_ver != 0 ) )
  1644.     {
  1645. #endif
  1646.         /*
  1647.          * Check the extension length
  1648.          */
  1649.         ext_offset = comp_offset + 1 + comp_len;
  1650.         if( msg_len > ext_offset )
  1651.         {
  1652.             if( msg_len < ext_offset + 2 )
  1653.             {
  1654.                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
  1655.                 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  1656.                                                 MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  1657.                 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  1658.             }
  1659.  
  1660.             ext_len = ( buf[ext_offset + 0] << 8 )
  1661.                     | ( buf[ext_offset + 1]      );
  1662.  
  1663.             if( ( ext_len > 0 && ext_len < 4 ) ||
  1664.                 msg_len != ext_offset + 2 + ext_len )
  1665.             {
  1666.                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
  1667.                 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  1668.                                                 MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  1669.                 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  1670.             }
  1671.         }
  1672.         else
  1673.             ext_len = 0;
  1674.  
  1675.         ext = buf + ext_offset + 2;
  1676.         MBEDTLS_SSL_DEBUG_BUF( 3, "client hello extensions", ext, ext_len );
  1677.  
  1678.         while( ext_len != 0 )
  1679.         {
  1680.             unsigned int ext_id;
  1681.             unsigned int ext_size;
  1682.             if ( ext_len < 4 ) {
  1683.                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
  1684.                 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  1685.                                                MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  1686.                 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  1687.             }
  1688.             ext_id   = ( ( ext[0] <<  8 ) | ( ext[1] ) );
  1689.             ext_size = ( ( ext[2] <<  8 ) | ( ext[3] ) );
  1690.  
  1691.             if( ext_size + 4 > ext_len )
  1692.             {
  1693.                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
  1694.                 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  1695.                                                 MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  1696.                 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  1697.             }
  1698.             switch( ext_id )
  1699.             {
  1700. #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
  1701.             case MBEDTLS_TLS_EXT_SERVERNAME:
  1702.                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found ServerName extension" ) );
  1703.                 if( ssl->conf->f_sni == NULL )
  1704.                     break;
  1705.  
  1706.                 ret = ssl_parse_servername_ext( ssl, ext + 4, ext_size );
  1707.                 if( ret != 0 )
  1708.                     return( ret );
  1709.                 break;
  1710. #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
  1711.  
  1712.             case MBEDTLS_TLS_EXT_RENEGOTIATION_INFO:
  1713.                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found renegotiation extension" ) );
  1714. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  1715.                 renegotiation_info_seen = 1;
  1716. #endif
  1717.  
  1718.                 ret = ssl_parse_renegotiation_info( ssl, ext + 4, ext_size );
  1719.                 if( ret != 0 )
  1720.                     return( ret );
  1721.                 break;
  1722.  
  1723. #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
  1724.     defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
  1725.             case MBEDTLS_TLS_EXT_SIG_ALG:
  1726.                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found signature_algorithms extension" ) );
  1727.  
  1728.                 ret = ssl_parse_signature_algorithms_ext( ssl, ext + 4, ext_size );
  1729.                 if( ret != 0 )
  1730.                     return( ret );
  1731.  
  1732.                 sig_hash_alg_ext_present = 1;
  1733.                 break;
  1734. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&
  1735.           MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
  1736.  
  1737. #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
  1738.     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
  1739.             case MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES:
  1740.                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found supported elliptic curves extension" ) );
  1741.  
  1742.                 ret = ssl_parse_supported_elliptic_curves( ssl, ext + 4, ext_size );
  1743.                 if( ret != 0 )
  1744.                     return( ret );
  1745.                 break;
  1746.  
  1747.             case MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS:
  1748.                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found supported point formats extension" ) );
  1749.                 ssl->handshake->cli_exts |= MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT;
  1750.  
  1751.                 ret = ssl_parse_supported_point_formats( ssl, ext + 4, ext_size );
  1752.                 if( ret != 0 )
  1753.                     return( ret );
  1754.                 break;
  1755. #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
  1756.           MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
  1757.  
  1758. #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
  1759.             case MBEDTLS_TLS_EXT_ECJPAKE_KKPP:
  1760.                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found ecjpake kkpp extension" ) );
  1761.  
  1762.                 ret = ssl_parse_ecjpake_kkpp( ssl, ext + 4, ext_size );
  1763.                 if( ret != 0 )
  1764.                     return( ret );
  1765.                 break;
  1766. #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
  1767.  
  1768. #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
  1769.             case MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH:
  1770.                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found max fragment length extension" ) );
  1771.  
  1772.                 ret = ssl_parse_max_fragment_length_ext( ssl, ext + 4, ext_size );
  1773.                 if( ret != 0 )
  1774.                     return( ret );
  1775.                 break;
  1776. #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
  1777.  
  1778. #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
  1779.             case MBEDTLS_TLS_EXT_TRUNCATED_HMAC:
  1780.                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found truncated hmac extension" ) );
  1781.  
  1782.                 ret = ssl_parse_truncated_hmac_ext( ssl, ext + 4, ext_size );
  1783.                 if( ret != 0 )
  1784.                     return( ret );
  1785.                 break;
  1786. #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
  1787.  
  1788. #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
  1789.             case MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC:
  1790.                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found encrypt then mac extension" ) );
  1791.  
  1792.                 ret = ssl_parse_encrypt_then_mac_ext( ssl, ext + 4, ext_size );
  1793.                 if( ret != 0 )
  1794.                     return( ret );
  1795.                 break;
  1796. #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
  1797.  
  1798. #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
  1799.             case MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET:
  1800.                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found extended master secret extension" ) );
  1801.  
  1802.                 ret = ssl_parse_extended_ms_ext( ssl, ext + 4, ext_size );
  1803.                 if( ret != 0 )
  1804.                     return( ret );
  1805.                 break;
  1806. #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
  1807.  
  1808. #if defined(MBEDTLS_SSL_SESSION_TICKETS)
  1809.             case MBEDTLS_TLS_EXT_SESSION_TICKET:
  1810.                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found session ticket extension" ) );
  1811.  
  1812.                 ret = ssl_parse_session_ticket_ext( ssl, ext + 4, ext_size );
  1813.                 if( ret != 0 )
  1814.                     return( ret );
  1815.                 break;
  1816. #endif /* MBEDTLS_SSL_SESSION_TICKETS */
  1817.  
  1818. #if defined(MBEDTLS_SSL_ALPN)
  1819.             case MBEDTLS_TLS_EXT_ALPN:
  1820.                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found alpn extension" ) );
  1821.  
  1822.                 ret = ssl_parse_alpn_ext( ssl, ext + 4, ext_size );
  1823.                 if( ret != 0 )
  1824.                     return( ret );
  1825.                 break;
  1826. #endif /* MBEDTLS_SSL_SESSION_TICKETS */
  1827.  
  1828.             default:
  1829.                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "unknown extension found: %d (ignoring)",
  1830.                                ext_id ) );
  1831.             }
  1832.  
  1833.             ext_len -= 4 + ext_size;
  1834.             ext += 4 + ext_size;
  1835.  
  1836.             if( ext_len > 0 && ext_len < 4 )
  1837.             {
  1838.                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
  1839.                 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  1840.                                                 MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  1841.                 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  1842.             }
  1843.         }
  1844. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  1845.     }
  1846. #endif
  1847.  
  1848. #if defined(MBEDTLS_SSL_FALLBACK_SCSV)
  1849.     for( i = 0, p = buf + ciph_offset + 2; i < ciph_len; i += 2, p += 2 )
  1850.     {
  1851.         if( p[0] == (unsigned char)( ( MBEDTLS_SSL_FALLBACK_SCSV_VALUE >> 8 ) & 0xff ) &&
  1852.             p[1] == (unsigned char)( ( MBEDTLS_SSL_FALLBACK_SCSV_VALUE      ) & 0xff ) )
  1853.         {
  1854.             MBEDTLS_SSL_DEBUG_MSG( 2, ( "received FALLBACK_SCSV" ) );
  1855.  
  1856.             if( ssl->minor_ver < ssl->conf->max_minor_ver )
  1857.             {
  1858.                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "inapropriate fallback" ) );
  1859.  
  1860.                 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  1861.                                         MBEDTLS_SSL_ALERT_MSG_INAPROPRIATE_FALLBACK );
  1862.  
  1863.                 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  1864.             }
  1865.  
  1866.             break;
  1867.         }
  1868.     }
  1869. #endif /* MBEDTLS_SSL_FALLBACK_SCSV */
  1870.  
  1871. #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
  1872.     defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
  1873.  
  1874.     /*
  1875.      * Try to fall back to default hash SHA1 if the client
  1876.      * hasn't provided any preferred signature-hash combinations.
  1877.      */
  1878.     if( sig_hash_alg_ext_present == 0 )
  1879.     {
  1880.         mbedtls_md_type_t md_default = MBEDTLS_MD_SHA1;
  1881.  
  1882.         if( mbedtls_ssl_check_sig_hash( ssl, md_default ) != 0 )
  1883.             md_default = MBEDTLS_MD_NONE;
  1884.  
  1885.         mbedtls_ssl_sig_hash_set_const_hash( &ssl->handshake->hash_algs, md_default );
  1886.     }
  1887.  
  1888. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&
  1889.           MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
  1890.  
  1891.     /*
  1892.      * Check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV
  1893.      */
  1894.     for( i = 0, p = buf + ciph_offset + 2; i < ciph_len; i += 2, p += 2 )
  1895.     {
  1896.         if( p[0] == 0 && p[1] == MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO )
  1897.         {
  1898.             MBEDTLS_SSL_DEBUG_MSG( 3, ( "received TLS_EMPTY_RENEGOTIATION_INFO " ) );
  1899. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  1900.             if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
  1901.             {
  1902.                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "received RENEGOTIATION SCSV "
  1903.                                             "during renegotiation" ) );
  1904.                 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  1905.                                                 MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
  1906.                 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  1907.             }
  1908. #endif
  1909.             ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION;
  1910.             break;
  1911.         }
  1912.     }
  1913.  
  1914.     /*
  1915.      * Renegotiation security checks
  1916.      */
  1917.     if( ssl->secure_renegotiation != MBEDTLS_SSL_SECURE_RENEGOTIATION &&
  1918.         ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE )
  1919.     {
  1920.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation, breaking off handshake" ) );
  1921.         handshake_failure = 1;
  1922.     }
  1923. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  1924.     else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
  1925.              ssl->secure_renegotiation == MBEDTLS_SSL_SECURE_RENEGOTIATION &&
  1926.              renegotiation_info_seen == 0 )
  1927.     {
  1928.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation_info extension missing (secure)" ) );
  1929.         handshake_failure = 1;
  1930.     }
  1931.     else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
  1932.              ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
  1933.              ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION )
  1934.     {
  1935.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation not allowed" ) );
  1936.         handshake_failure = 1;
  1937.     }
  1938.     else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
  1939.              ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
  1940.              renegotiation_info_seen == 1 )
  1941.     {
  1942.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation_info extension present (legacy)" ) );
  1943.         handshake_failure = 1;
  1944.     }
  1945. #endif /* MBEDTLS_SSL_RENEGOTIATION */
  1946.  
  1947.     if( handshake_failure == 1 )
  1948.     {
  1949.         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  1950.                                         MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
  1951.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  1952.     }
  1953.  
  1954.     /*
  1955.      * Search for a matching ciphersuite
  1956.      * (At the end because we need information from the EC-based extensions
  1957.      * and certificate from the SNI callback triggered by the SNI extension.)
  1958.      */
  1959.     got_common_suite = 0;
  1960.     ciphersuites = ssl->conf->ciphersuite_list[ssl->minor_ver];
  1961.     ciphersuite_info = NULL;
  1962. #if defined(MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE)
  1963.     for( j = 0, p = buf + ciph_offset + 2; j < ciph_len; j += 2, p += 2 )
  1964.         for( i = 0; ciphersuites[i] != 0; i++ )
  1965. #else
  1966.     for( i = 0; ciphersuites[i] != 0; i++ )
  1967.         for( j = 0, p = buf + ciph_offset + 2; j < ciph_len; j += 2, p += 2 )
  1968. #endif
  1969.         {
  1970.             if( p[0] != ( ( ciphersuites[i] >> 8 ) & 0xFF ) ||
  1971.                 p[1] != ( ( ciphersuites[i]      ) & 0xFF ) )
  1972.                 continue;
  1973.  
  1974.             got_common_suite = 1;
  1975.  
  1976.             if( ( ret = ssl_ciphersuite_match( ssl, ciphersuites[i],
  1977.                                                &ciphersuite_info ) ) != 0 )
  1978.                 return( ret );
  1979.  
  1980.             if( ciphersuite_info != NULL )
  1981.                 goto have_ciphersuite;
  1982.         }
  1983.  
  1984.     if( got_common_suite )
  1985.     {
  1986.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "got ciphersuites in common, "
  1987.                             "but none of them usable" ) );
  1988.         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  1989.                                         MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
  1990.         return( MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE );
  1991.     }
  1992.     else
  1993.     {
  1994.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no ciphersuites in common" ) );
  1995.         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  1996.                                         MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
  1997.         return( MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN );
  1998.     }
  1999.  
  2000. have_ciphersuite:
  2001.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "selected ciphersuite: %s", ciphersuite_info->name ) );
  2002.  
  2003.     ssl->session_negotiate->ciphersuite = ciphersuites[i];
  2004.     ssl->transform_negotiate->ciphersuite_info = ciphersuite_info;
  2005.  
  2006.     ssl->state++;
  2007.  
  2008. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  2009.     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  2010.         mbedtls_ssl_recv_flight_completed( ssl );
  2011. #endif
  2012.  
  2013.     /* Debugging-only output for testsuite */
  2014. #if defined(MBEDTLS_DEBUG_C)                         && \
  2015.     defined(MBEDTLS_SSL_PROTO_TLS1_2)                && \
  2016.     defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
  2017.     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
  2018.     {
  2019.         mbedtls_pk_type_t sig_alg = mbedtls_ssl_get_ciphersuite_sig_alg( ciphersuite_info );
  2020.         if( sig_alg != MBEDTLS_PK_NONE )
  2021.         {
  2022.             mbedtls_md_type_t md_alg = mbedtls_ssl_sig_hash_set_find( &ssl->handshake->hash_algs,
  2023.                                                                   sig_alg );
  2024.             MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext: %d",
  2025.                                         mbedtls_ssl_hash_from_md_alg( md_alg ) ) );
  2026.         }
  2027.         else
  2028.         {
  2029.             MBEDTLS_SSL_DEBUG_MSG( 3, ( "no hash algorithm for signature algorithm "
  2030.                                         "%d - should not happen", sig_alg ) );
  2031.         }
  2032.     }
  2033. #endif
  2034.  
  2035.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse client hello" ) );
  2036.  
  2037.     return( 0 );
  2038. }
  2039.  
  2040. #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
  2041. static void ssl_write_truncated_hmac_ext( mbedtls_ssl_context *ssl,
  2042.                                           unsigned char *buf,
  2043.                                           size_t *olen )
  2044. {
  2045.     unsigned char *p = buf;
  2046.  
  2047.     if( ssl->session_negotiate->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_DISABLED )
  2048.     {
  2049.         *olen = 0;
  2050.         return;
  2051.     }
  2052.  
  2053.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding truncated hmac extension" ) );
  2054.  
  2055.     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_TRUNCATED_HMAC >> 8 ) & 0xFF );
  2056.     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_TRUNCATED_HMAC      ) & 0xFF );
  2057.  
  2058.     *p++ = 0x00;
  2059.     *p++ = 0x00;
  2060.  
  2061.     *olen = 4;
  2062. }
  2063. #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
  2064.  
  2065. #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
  2066. static void ssl_write_encrypt_then_mac_ext( mbedtls_ssl_context *ssl,
  2067.                                             unsigned char *buf,
  2068.                                             size_t *olen )
  2069. {
  2070.     unsigned char *p = buf;
  2071.     const mbedtls_ssl_ciphersuite_t *suite = NULL;
  2072.     const mbedtls_cipher_info_t *cipher = NULL;
  2073.  
  2074.     if( ssl->session_negotiate->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED ||
  2075.         ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
  2076.     {
  2077.         *olen = 0;
  2078.         return;
  2079.     }
  2080.  
  2081.     /*
  2082.      * RFC 7366: "If a server receives an encrypt-then-MAC request extension
  2083.      * from a client and then selects a stream or Authenticated Encryption
  2084.      * with Associated Data (AEAD) ciphersuite, it MUST NOT send an
  2085.      * encrypt-then-MAC response extension back to the client."
  2086.      */
  2087.     if( ( suite = mbedtls_ssl_ciphersuite_from_id(
  2088.                     ssl->session_negotiate->ciphersuite ) ) == NULL ||
  2089.         ( cipher = mbedtls_cipher_info_from_type( suite->cipher ) ) == NULL ||
  2090.         cipher->mode != MBEDTLS_MODE_CBC )
  2091.     {
  2092.         *olen = 0;
  2093.         return;
  2094.     }
  2095.  
  2096.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding encrypt then mac extension" ) );
  2097.  
  2098.     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC >> 8 ) & 0xFF );
  2099.     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC      ) & 0xFF );
  2100.  
  2101.     *p++ = 0x00;
  2102.     *p++ = 0x00;
  2103.  
  2104.     *olen = 4;
  2105. }
  2106. #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
  2107.  
  2108. #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
  2109. static void ssl_write_extended_ms_ext( mbedtls_ssl_context *ssl,
  2110.                                        unsigned char *buf,
  2111.                                        size_t *olen )
  2112. {
  2113.     unsigned char *p = buf;
  2114.  
  2115.     if( ssl->handshake->extended_ms == MBEDTLS_SSL_EXTENDED_MS_DISABLED ||
  2116.         ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
  2117.     {
  2118.         *olen = 0;
  2119.         return;
  2120.     }
  2121.  
  2122.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding extended master secret "
  2123.                         "extension" ) );
  2124.  
  2125.     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET >> 8 ) & 0xFF );
  2126.     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET      ) & 0xFF );
  2127.  
  2128.     *p++ = 0x00;
  2129.     *p++ = 0x00;
  2130.  
  2131.     *olen = 4;
  2132. }
  2133. #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
  2134.  
  2135. #if defined(MBEDTLS_SSL_SESSION_TICKETS)
  2136. static void ssl_write_session_ticket_ext( mbedtls_ssl_context *ssl,
  2137.                                           unsigned char *buf,
  2138.                                           size_t *olen )
  2139. {
  2140.     unsigned char *p = buf;
  2141.  
  2142.     if( ssl->handshake->new_session_ticket == 0 )
  2143.     {
  2144.         *olen = 0;
  2145.         return;
  2146.     }
  2147.  
  2148.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding session ticket extension" ) );
  2149.  
  2150.     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SESSION_TICKET >> 8 ) & 0xFF );
  2151.     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SESSION_TICKET      ) & 0xFF );
  2152.  
  2153.     *p++ = 0x00;
  2154.     *p++ = 0x00;
  2155.  
  2156.     *olen = 4;
  2157. }
  2158. #endif /* MBEDTLS_SSL_SESSION_TICKETS */
  2159.  
  2160. static void ssl_write_renegotiation_ext( mbedtls_ssl_context *ssl,
  2161.                                          unsigned char *buf,
  2162.                                          size_t *olen )
  2163. {
  2164.     unsigned char *p = buf;
  2165.  
  2166.     if( ssl->secure_renegotiation != MBEDTLS_SSL_SECURE_RENEGOTIATION )
  2167.     {
  2168.         *olen = 0;
  2169.         return;
  2170.     }
  2171.  
  2172.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, secure renegotiation extension" ) );
  2173.  
  2174.     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO >> 8 ) & 0xFF );
  2175.     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO      ) & 0xFF );
  2176.  
  2177. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  2178.     if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE )
  2179.     {
  2180.         *p++ = 0x00;
  2181.         *p++ = ( ssl->verify_data_len * 2 + 1 ) & 0xFF;
  2182.         *p++ = ssl->verify_data_len * 2 & 0xFF;
  2183.  
  2184.         memcpy( p, ssl->peer_verify_data, ssl->verify_data_len );
  2185.         p += ssl->verify_data_len;
  2186.         memcpy( p, ssl->own_verify_data, ssl->verify_data_len );
  2187.         p += ssl->verify_data_len;
  2188.     }
  2189.     else
  2190. #endif /* MBEDTLS_SSL_RENEGOTIATION */
  2191.     {
  2192.         *p++ = 0x00;
  2193.         *p++ = 0x01;
  2194.         *p++ = 0x00;
  2195.     }
  2196.  
  2197.     *olen = p - buf;
  2198. }
  2199.  
  2200. #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
  2201. static void ssl_write_max_fragment_length_ext( mbedtls_ssl_context *ssl,
  2202.                                                unsigned char *buf,
  2203.                                                size_t *olen )
  2204. {
  2205.     unsigned char *p = buf;
  2206.  
  2207.     if( ssl->session_negotiate->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE )
  2208.     {
  2209.         *olen = 0;
  2210.         return;
  2211.     }
  2212.  
  2213.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, max_fragment_length extension" ) );
  2214.  
  2215.     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH >> 8 ) & 0xFF );
  2216.     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH      ) & 0xFF );
  2217.  
  2218.     *p++ = 0x00;
  2219.     *p++ = 1;
  2220.  
  2221.     *p++ = ssl->session_negotiate->mfl_code;
  2222.  
  2223.     *olen = 5;
  2224. }
  2225. #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
  2226.  
  2227. #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
  2228.     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
  2229. static void ssl_write_supported_point_formats_ext( mbedtls_ssl_context *ssl,
  2230.                                                    unsigned char *buf,
  2231.                                                    size_t *olen )
  2232. {
  2233.     unsigned char *p = buf;
  2234.     ((void) ssl);
  2235.  
  2236.     if( ( ssl->handshake->cli_exts &
  2237.           MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT ) == 0 )
  2238.     {
  2239.         *olen = 0;
  2240.         return;
  2241.     }
  2242.  
  2243.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, supported_point_formats extension" ) );
  2244.  
  2245.     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS >> 8 ) & 0xFF );
  2246.     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS      ) & 0xFF );
  2247.  
  2248.     *p++ = 0x00;
  2249.     *p++ = 2;
  2250.  
  2251.     *p++ = 1;
  2252.     *p++ = MBEDTLS_ECP_PF_UNCOMPRESSED;
  2253.  
  2254.     *olen = 6;
  2255. }
  2256. #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C || MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
  2257.  
  2258. #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
  2259. static void ssl_write_ecjpake_kkpp_ext( mbedtls_ssl_context *ssl,
  2260.                                         unsigned char *buf,
  2261.                                         size_t *olen )
  2262. {
  2263.     int ret;
  2264.     unsigned char *p = buf;
  2265.     const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;
  2266.     size_t kkpp_len;
  2267.  
  2268.     *olen = 0;
  2269.  
  2270.     /* Skip costly computation if not needed */
  2271.     if( ssl->transform_negotiate->ciphersuite_info->key_exchange !=
  2272.         MBEDTLS_KEY_EXCHANGE_ECJPAKE )
  2273.         return;
  2274.  
  2275.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, ecjpake kkpp extension" ) );
  2276.  
  2277.     if( end - p < 4 )
  2278.     {
  2279.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
  2280.         return;
  2281.     }
  2282.  
  2283.     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ECJPAKE_KKPP >> 8 ) & 0xFF );
  2284.     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ECJPAKE_KKPP      ) & 0xFF );
  2285.  
  2286.     ret = mbedtls_ecjpake_write_round_one( &ssl->handshake->ecjpake_ctx,
  2287.                                         p + 2, end - p - 2, &kkpp_len,
  2288.                                         ssl->conf->f_rng, ssl->conf->p_rng );
  2289.     if( ret != 0 )
  2290.     {
  2291.         MBEDTLS_SSL_DEBUG_RET( 1 , "mbedtls_ecjpake_write_round_one", ret );
  2292.         return;
  2293.     }
  2294.  
  2295.     *p++ = (unsigned char)( ( kkpp_len >> 8 ) & 0xFF );
  2296.     *p++ = (unsigned char)( ( kkpp_len      ) & 0xFF );
  2297.  
  2298.     *olen = kkpp_len + 4;
  2299. }
  2300. #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
  2301.  
  2302. #if defined(MBEDTLS_SSL_ALPN )
  2303. static void ssl_write_alpn_ext( mbedtls_ssl_context *ssl,
  2304.                                 unsigned char *buf, size_t *olen )
  2305. {
  2306.     if( ssl->alpn_chosen == NULL )
  2307.     {
  2308.         *olen = 0;
  2309.         return;
  2310.     }
  2311.  
  2312.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding alpn extension" ) );
  2313.  
  2314.     /*
  2315.      * 0 . 1    ext identifier
  2316.      * 2 . 3    ext length
  2317.      * 4 . 5    protocol list length
  2318.      * 6 . 6    protocol name length
  2319.      * 7 . 7+n  protocol name
  2320.      */
  2321.     buf[0] = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN >> 8 ) & 0xFF );
  2322.     buf[1] = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN      ) & 0xFF );
  2323.  
  2324.     *olen = 7 + strlen( ssl->alpn_chosen );
  2325.  
  2326.     buf[2] = (unsigned char)( ( ( *olen - 4 ) >> 8 ) & 0xFF );
  2327.     buf[3] = (unsigned char)( ( ( *olen - 4 )      ) & 0xFF );
  2328.  
  2329.     buf[4] = (unsigned char)( ( ( *olen - 6 ) >> 8 ) & 0xFF );
  2330.     buf[5] = (unsigned char)( ( ( *olen - 6 )      ) & 0xFF );
  2331.  
  2332.     buf[6] = (unsigned char)( ( ( *olen - 7 )      ) & 0xFF );
  2333.  
  2334.     memcpy( buf + 7, ssl->alpn_chosen, *olen - 7 );
  2335. }
  2336. #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C */
  2337.  
  2338. #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY)
  2339. static int ssl_write_hello_verify_request( mbedtls_ssl_context *ssl )
  2340. {
  2341.     int ret;
  2342.     unsigned char *p = ssl->out_msg + 4;
  2343.     unsigned char *cookie_len_byte;
  2344.  
  2345.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write hello verify request" ) );
  2346.  
  2347.     /*
  2348.      * struct {
  2349.      *   ProtocolVersion server_version;
  2350.      *   opaque cookie<0..2^8-1>;
  2351.      * } HelloVerifyRequest;
  2352.      */
  2353.  
  2354.     /* The RFC is not clear on this point, but sending the actual negotiated
  2355.      * version looks like the most interoperable thing to do. */
  2356.     mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,
  2357.                        ssl->conf->transport, p );
  2358.     MBEDTLS_SSL_DEBUG_BUF( 3, "server version", p, 2 );
  2359.     p += 2;
  2360.  
  2361.     /* If we get here, f_cookie_check is not null */
  2362.     if( ssl->conf->f_cookie_write == NULL )
  2363.     {
  2364.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "inconsistent cookie callbacks" ) );
  2365.         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  2366.     }
  2367.  
  2368.     /* Skip length byte until we know the length */
  2369.     cookie_len_byte = p++;
  2370.  
  2371.     if( ( ret = ssl->conf->f_cookie_write( ssl->conf->p_cookie,
  2372.                                      &p, ssl->out_buf + MBEDTLS_SSL_OUT_BUFFER_LEN,
  2373.                                      ssl->cli_id, ssl->cli_id_len ) ) != 0 )
  2374.     {
  2375.         MBEDTLS_SSL_DEBUG_RET( 1, "f_cookie_write", ret );
  2376.         return( ret );
  2377.     }
  2378.  
  2379.     *cookie_len_byte = (unsigned char)( p - ( cookie_len_byte + 1 ) );
  2380.  
  2381.     MBEDTLS_SSL_DEBUG_BUF( 3, "cookie sent", cookie_len_byte + 1, *cookie_len_byte );
  2382.  
  2383.     ssl->out_msglen  = p - ssl->out_msg;
  2384.     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
  2385.     ssl->out_msg[0]  = MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST;
  2386.  
  2387.     ssl->state = MBEDTLS_SSL_SERVER_HELLO_VERIFY_REQUEST_SENT;
  2388.  
  2389.     if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
  2390.     {
  2391.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
  2392.         return( ret );
  2393.     }
  2394.  
  2395. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  2396.     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  2397.         ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 )
  2398.     {
  2399.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flight_transmit", ret );
  2400.         return( ret );
  2401.     }
  2402. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  2403.  
  2404.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write hello verify request" ) );
  2405.  
  2406.     return( 0 );
  2407. }
  2408. #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */
  2409.  
  2410. static int ssl_write_server_hello( mbedtls_ssl_context *ssl )
  2411. {
  2412. #if defined(MBEDTLS_HAVE_TIME)
  2413.     mbedtls_time_t t;
  2414. #endif
  2415.     int ret;
  2416.     size_t olen, ext_len = 0, n;
  2417.     unsigned char *buf, *p;
  2418.  
  2419.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write server hello" ) );
  2420.  
  2421. #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY)
  2422.     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  2423.         ssl->handshake->verify_cookie_len != 0 )
  2424.     {
  2425.         MBEDTLS_SSL_DEBUG_MSG( 2, ( "client hello was not authenticated" ) );
  2426.         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write server hello" ) );
  2427.  
  2428.         return( ssl_write_hello_verify_request( ssl ) );
  2429.     }
  2430. #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */
  2431.  
  2432.     if( ssl->conf->f_rng == NULL )
  2433.     {
  2434.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "no RNG provided") );
  2435.         return( MBEDTLS_ERR_SSL_NO_RNG );
  2436.     }
  2437.  
  2438.     /*
  2439.      *     0  .   0   handshake type
  2440.      *     1  .   3   handshake length
  2441.      *     4  .   5   protocol version
  2442.      *     6  .   9   UNIX time()
  2443.      *    10  .  37   random bytes
  2444.      */
  2445.     buf = ssl->out_msg;
  2446.     p = buf + 4;
  2447.  
  2448.     mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,
  2449.                        ssl->conf->transport, p );
  2450.     p += 2;
  2451.  
  2452.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen version: [%d:%d]",
  2453.                         buf[4], buf[5] ) );
  2454.  
  2455. #if defined(MBEDTLS_HAVE_TIME)
  2456.     t = mbedtls_time( NULL );
  2457.     *p++ = (unsigned char)( t >> 24 );
  2458.     *p++ = (unsigned char)( t >> 16 );
  2459.     *p++ = (unsigned char)( t >>  8 );
  2460.     *p++ = (unsigned char)( t       );
  2461.  
  2462.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, current time: %lu", t ) );
  2463. #else
  2464.     if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p, 4 ) ) != 0 )
  2465.         return( ret );
  2466.  
  2467.     p += 4;
  2468. #endif /* MBEDTLS_HAVE_TIME */
  2469.  
  2470.     if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p, 28 ) ) != 0 )
  2471.         return( ret );
  2472.  
  2473.     p += 28;
  2474.  
  2475.     memcpy( ssl->handshake->randbytes + 32, buf + 6, 32 );
  2476.  
  2477.     MBEDTLS_SSL_DEBUG_BUF( 3, "server hello, random bytes", buf + 6, 32 );
  2478.  
  2479.     /*
  2480.      * Resume is 0  by default, see ssl_handshake_init().
  2481.      * It may be already set to 1 by ssl_parse_session_ticket_ext().
  2482.      * If not, try looking up session ID in our cache.
  2483.      */
  2484.     if( ssl->handshake->resume == 0 &&
  2485. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  2486.         ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE &&
  2487. #endif
  2488.         ssl->session_negotiate->id_len != 0 &&
  2489.         ssl->conf->f_get_cache != NULL &&
  2490.         ssl->conf->f_get_cache( ssl->conf->p_cache, ssl->session_negotiate ) == 0 )
  2491.     {
  2492.         MBEDTLS_SSL_DEBUG_MSG( 3, ( "session successfully restored from cache" ) );
  2493.         ssl->handshake->resume = 1;
  2494.     }
  2495.  
  2496.     if( ssl->handshake->resume == 0 )
  2497.     {
  2498.         /*
  2499.          * New session, create a new session id,
  2500.          * unless we're about to issue a session ticket
  2501.          */
  2502.         ssl->state++;
  2503.  
  2504. #if defined(MBEDTLS_HAVE_TIME)
  2505.         ssl->session_negotiate->start = mbedtls_time( NULL );
  2506. #endif
  2507.  
  2508. #if defined(MBEDTLS_SSL_SESSION_TICKETS)
  2509.         if( ssl->handshake->new_session_ticket != 0 )
  2510.         {
  2511.             ssl->session_negotiate->id_len = n = 0;
  2512.             memset( ssl->session_negotiate->id, 0, 32 );
  2513.         }
  2514.         else
  2515. #endif /* MBEDTLS_SSL_SESSION_TICKETS */
  2516.         {
  2517.             ssl->session_negotiate->id_len = n = 32;
  2518.             if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, ssl->session_negotiate->id,
  2519.                                     n ) ) != 0 )
  2520.                 return( ret );
  2521.         }
  2522.     }
  2523.     else
  2524.     {
  2525.         /*
  2526.          * Resuming a session
  2527.          */
  2528.         n = ssl->session_negotiate->id_len;
  2529.         ssl->state = MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC;
  2530.  
  2531.         if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )
  2532.         {
  2533.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret );
  2534.             return( ret );
  2535.         }
  2536.     }
  2537.  
  2538.     /*
  2539.      *    38  .  38     session id length
  2540.      *    39  . 38+n    session id
  2541.      *   39+n . 40+n    chosen ciphersuite
  2542.      *   41+n . 41+n    chosen compression alg.
  2543.      *   42+n . 43+n    extensions length
  2544.      *   44+n . 43+n+m  extensions
  2545.      */
  2546.     *p++ = (unsigned char) ssl->session_negotiate->id_len;
  2547.     memcpy( p, ssl->session_negotiate->id, ssl->session_negotiate->id_len );
  2548.     p += ssl->session_negotiate->id_len;
  2549.  
  2550.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, session id len.: %d", n ) );
  2551.     MBEDTLS_SSL_DEBUG_BUF( 3,   "server hello, session id", buf + 39, n );
  2552.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "%s session has been resumed",
  2553.                    ssl->handshake->resume ? "a" : "no" ) );
  2554.  
  2555.     *p++ = (unsigned char)( ssl->session_negotiate->ciphersuite >> 8 );
  2556.     *p++ = (unsigned char)( ssl->session_negotiate->ciphersuite      );
  2557.     *p++ = (unsigned char)( ssl->session_negotiate->compression      );
  2558.  
  2559.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen ciphersuite: %s",
  2560.            mbedtls_ssl_get_ciphersuite_name( ssl->session_negotiate->ciphersuite ) ) );
  2561.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, compress alg.: 0x%02X",
  2562.                    ssl->session_negotiate->compression ) );
  2563.  
  2564.     /* Do not write the extensions if the protocol is SSLv3 */
  2565. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  2566.     if( ( ssl->major_ver != 3 ) || ( ssl->minor_ver != 0 ) )
  2567.     {
  2568. #endif
  2569.  
  2570.     /*
  2571.      *  First write extensions, then the total length
  2572.      */
  2573.     ssl_write_renegotiation_ext( ssl, p + 2 + ext_len, &olen );
  2574.     ext_len += olen;
  2575.  
  2576. #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
  2577.     ssl_write_max_fragment_length_ext( ssl, p + 2 + ext_len, &olen );
  2578.     ext_len += olen;
  2579. #endif
  2580.  
  2581. #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
  2582.     ssl_write_truncated_hmac_ext( ssl, p + 2 + ext_len, &olen );
  2583.     ext_len += olen;
  2584. #endif
  2585.  
  2586. #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
  2587.     ssl_write_encrypt_then_mac_ext( ssl, p + 2 + ext_len, &olen );
  2588.     ext_len += olen;
  2589. #endif
  2590.  
  2591. #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
  2592.     ssl_write_extended_ms_ext( ssl, p + 2 + ext_len, &olen );
  2593.     ext_len += olen;
  2594. #endif
  2595.  
  2596. #if defined(MBEDTLS_SSL_SESSION_TICKETS)
  2597.     ssl_write_session_ticket_ext( ssl, p + 2 + ext_len, &olen );
  2598.     ext_len += olen;
  2599. #endif
  2600.  
  2601. #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
  2602.     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
  2603.     if ( mbedtls_ssl_ciphersuite_uses_ec(
  2604.          mbedtls_ssl_ciphersuite_from_id( ssl->session_negotiate->ciphersuite ) ) )
  2605.     {
  2606.         ssl_write_supported_point_formats_ext( ssl, p + 2 + ext_len, &olen );
  2607.         ext_len += olen;
  2608.     }
  2609. #endif
  2610.  
  2611. #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
  2612.     ssl_write_ecjpake_kkpp_ext( ssl, p + 2 + ext_len, &olen );
  2613.     ext_len += olen;
  2614. #endif
  2615.  
  2616. #if defined(MBEDTLS_SSL_ALPN)
  2617.     ssl_write_alpn_ext( ssl, p + 2 + ext_len, &olen );
  2618.     ext_len += olen;
  2619. #endif
  2620.  
  2621.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, total extension length: %d", ext_len ) );
  2622.  
  2623.     if( ext_len > 0 )
  2624.     {
  2625.         *p++ = (unsigned char)( ( ext_len >> 8 ) & 0xFF );
  2626.         *p++ = (unsigned char)( ( ext_len      ) & 0xFF );
  2627.         p += ext_len;
  2628.     }
  2629.  
  2630. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  2631.     }
  2632. #endif
  2633.  
  2634.     ssl->out_msglen  = p - buf;
  2635.     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
  2636.     ssl->out_msg[0]  = MBEDTLS_SSL_HS_SERVER_HELLO;
  2637.  
  2638.     ret = mbedtls_ssl_write_handshake_msg( ssl );
  2639.  
  2640.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write server hello" ) );
  2641.  
  2642.     return( ret );
  2643. }
  2644.  
  2645. #if !defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)       && \
  2646.     !defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)   && \
  2647.     !defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED)  && \
  2648.     !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) && \
  2649.     !defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)&& \
  2650.     !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
  2651. static int ssl_write_certificate_request( mbedtls_ssl_context *ssl )
  2652. {
  2653.     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
  2654.         ssl->transform_negotiate->ciphersuite_info;
  2655.  
  2656.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate request" ) );
  2657.  
  2658.     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
  2659.         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
  2660.         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
  2661.         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
  2662.         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
  2663.     {
  2664.         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate request" ) );
  2665.         ssl->state++;
  2666.         return( 0 );
  2667.     }
  2668.  
  2669.     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  2670.     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  2671. }
  2672. #else
  2673. static int ssl_write_certificate_request( mbedtls_ssl_context *ssl )
  2674. {
  2675.     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
  2676.     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
  2677.         ssl->transform_negotiate->ciphersuite_info;
  2678.     size_t dn_size, total_dn_size; /* excluding length bytes */
  2679.     size_t ct_len, sa_len; /* including length bytes */
  2680.     unsigned char *buf, *p;
  2681.     const unsigned char * const end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;
  2682.     const mbedtls_x509_crt *crt;
  2683.     int authmode;
  2684.  
  2685.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate request" ) );
  2686.  
  2687.     ssl->state++;
  2688.  
  2689. #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
  2690.     if( ssl->handshake->sni_authmode != MBEDTLS_SSL_VERIFY_UNSET )
  2691.         authmode = ssl->handshake->sni_authmode;
  2692.     else
  2693. #endif
  2694.         authmode = ssl->conf->authmode;
  2695.  
  2696.     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
  2697.         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
  2698.         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
  2699.         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
  2700.         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE ||
  2701.         authmode == MBEDTLS_SSL_VERIFY_NONE )
  2702.     {
  2703.         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate request" ) );
  2704.         return( 0 );
  2705.     }
  2706.  
  2707.     /*
  2708.      *     0  .   0   handshake type
  2709.      *     1  .   3   handshake length
  2710.      *     4  .   4   cert type count
  2711.      *     5  .. m-1  cert types
  2712.      *     m  .. m+1  sig alg length (TLS 1.2 only)
  2713.      *    m+1 .. n-1  SignatureAndHashAlgorithms (TLS 1.2 only)
  2714.      *     n  .. n+1  length of all DNs
  2715.      *    n+2 .. n+3  length of DN 1
  2716.      *    n+4 .. ...  Distinguished Name #1
  2717.      *    ... .. ...  length of DN 2, etc.
  2718.      */
  2719.     buf = ssl->out_msg;
  2720.     p = buf + 4;
  2721.  
  2722.     /*
  2723.      * Supported certificate types
  2724.      *
  2725.      *     ClientCertificateType certificate_types<1..2^8-1>;
  2726.      *     enum { (255) } ClientCertificateType;
  2727.      */
  2728.     ct_len = 0;
  2729.  
  2730. #if defined(MBEDTLS_RSA_C)
  2731.     p[1 + ct_len++] = MBEDTLS_SSL_CERT_TYPE_RSA_SIGN;
  2732. #endif
  2733. #if defined(MBEDTLS_ECDSA_C)
  2734.     p[1 + ct_len++] = MBEDTLS_SSL_CERT_TYPE_ECDSA_SIGN;
  2735. #endif
  2736.  
  2737.     p[0] = (unsigned char) ct_len++;
  2738.     p += ct_len;
  2739.  
  2740.     sa_len = 0;
  2741. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  2742.     /*
  2743.      * Add signature_algorithms for verify (TLS 1.2)
  2744.      *
  2745.      *     SignatureAndHashAlgorithm supported_signature_algorithms<2..2^16-2>;
  2746.      *
  2747.      *     struct {
  2748.      *           HashAlgorithm hash;
  2749.      *           SignatureAlgorithm signature;
  2750.      *     } SignatureAndHashAlgorithm;
  2751.      *
  2752.      *     enum { (255) } HashAlgorithm;
  2753.      *     enum { (255) } SignatureAlgorithm;
  2754.      */
  2755.     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
  2756.     {
  2757.         const int *cur;
  2758.  
  2759.         /*
  2760.          * Supported signature algorithms
  2761.          */
  2762.         for( cur = ssl->conf->sig_hashes; *cur != MBEDTLS_MD_NONE; cur++ )
  2763.         {
  2764.             unsigned char hash = mbedtls_ssl_hash_from_md_alg( *cur );
  2765.  
  2766.             if( MBEDTLS_SSL_HASH_NONE == hash || mbedtls_ssl_set_calc_verify_md( ssl, hash ) )
  2767.                 continue;
  2768.  
  2769. #if defined(MBEDTLS_RSA_C)
  2770.             p[2 + sa_len++] = hash;
  2771.             p[2 + sa_len++] = MBEDTLS_SSL_SIG_RSA;
  2772. #endif
  2773. #if defined(MBEDTLS_ECDSA_C)
  2774.             p[2 + sa_len++] = hash;
  2775.             p[2 + sa_len++] = MBEDTLS_SSL_SIG_ECDSA;
  2776. #endif
  2777.         }
  2778.  
  2779.         p[0] = (unsigned char)( sa_len >> 8 );
  2780.         p[1] = (unsigned char)( sa_len      );
  2781.         sa_len += 2;
  2782.         p += sa_len;
  2783.     }
  2784. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  2785.  
  2786.     /*
  2787.      * DistinguishedName certificate_authorities<0..2^16-1>;
  2788.      * opaque DistinguishedName<1..2^16-1>;
  2789.      */
  2790.     p += 2;
  2791.  
  2792.     total_dn_size = 0;
  2793.  
  2794.     if( ssl->conf->cert_req_ca_list ==  MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED )
  2795.     {
  2796. #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
  2797.         if( ssl->handshake->sni_ca_chain != NULL )
  2798.             crt = ssl->handshake->sni_ca_chain;
  2799.         else
  2800. #endif
  2801.             crt = ssl->conf->ca_chain;
  2802.  
  2803.         while( crt != NULL && crt->version != 0 )
  2804.         {
  2805.             dn_size = crt->subject_raw.len;
  2806.  
  2807.             if( end < p ||
  2808.                 (size_t)( end - p ) < dn_size ||
  2809.                 (size_t)( end - p ) < 2 + dn_size )
  2810.             {
  2811.                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "skipping CAs: buffer too short" ) );
  2812.                 break;
  2813.             }
  2814.  
  2815.             *p++ = (unsigned char)( dn_size >> 8 );
  2816.             *p++ = (unsigned char)( dn_size      );
  2817.             memcpy( p, crt->subject_raw.p, dn_size );
  2818.             p += dn_size;
  2819.  
  2820.             MBEDTLS_SSL_DEBUG_BUF( 3, "requested DN", p - dn_size, dn_size );
  2821.  
  2822.             total_dn_size += 2 + dn_size;
  2823.             crt = crt->next;
  2824.         }
  2825.     }
  2826.  
  2827.     ssl->out_msglen  = p - buf;
  2828.     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
  2829.     ssl->out_msg[0]  = MBEDTLS_SSL_HS_CERTIFICATE_REQUEST;
  2830.     ssl->out_msg[4 + ct_len + sa_len] = (unsigned char)( total_dn_size  >> 8 );
  2831.     ssl->out_msg[5 + ct_len + sa_len] = (unsigned char)( total_dn_size       );
  2832.  
  2833.     ret = mbedtls_ssl_write_handshake_msg( ssl );
  2834.  
  2835.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write certificate request" ) );
  2836.  
  2837.     return( ret );
  2838. }
  2839. #endif /* !MBEDTLS_KEY_EXCHANGE_RSA_ENABLED &&
  2840.           !MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED &&
  2841.           !MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED &&
  2842.           !MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED &&
  2843.           !MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED &&
  2844.           !MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
  2845.  
  2846. #if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
  2847.     defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
  2848. static int ssl_get_ecdh_params_from_cert( mbedtls_ssl_context *ssl )
  2849. {
  2850.     int ret;
  2851.  
  2852.     if( ! mbedtls_pk_can_do( mbedtls_ssl_own_key( ssl ), MBEDTLS_PK_ECKEY ) )
  2853.     {
  2854.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "server key not ECDH capable" ) );
  2855.         return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
  2856.     }
  2857.  
  2858.     if( ( ret = mbedtls_ecdh_get_params( &ssl->handshake->ecdh_ctx,
  2859.                                  mbedtls_pk_ec( *mbedtls_ssl_own_key( ssl ) ),
  2860.                                  MBEDTLS_ECDH_OURS ) ) != 0 )
  2861.     {
  2862.         MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ecdh_get_params" ), ret );
  2863.         return( ret );
  2864.     }
  2865.  
  2866.     return( 0 );
  2867. }
  2868. #endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||
  2869.           MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
  2870.  
  2871. #if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED) && \
  2872.     defined(MBEDTLS_SSL_ASYNC_PRIVATE)
  2873. static int ssl_resume_server_key_exchange( mbedtls_ssl_context *ssl,
  2874.                                            size_t *signature_len )
  2875. {
  2876.     /* Append the signature to ssl->out_msg, leaving 2 bytes for the
  2877.      * signature length which will be added in ssl_write_server_key_exchange
  2878.      * after the call to ssl_prepare_server_key_exchange.
  2879.      * ssl_write_server_key_exchange also takes care of incrementing
  2880.      * ssl->out_msglen. */
  2881.     unsigned char *sig_start = ssl->out_msg + ssl->out_msglen + 2;
  2882.     size_t sig_max_len = ( ssl->out_buf + MBEDTLS_SSL_OUT_CONTENT_LEN
  2883.                            - sig_start );
  2884.     int ret = ssl->conf->f_async_resume( ssl,
  2885.                                          sig_start, signature_len, sig_max_len );
  2886.     if( ret != MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS )
  2887.     {
  2888.         ssl->handshake->async_in_progress = 0;
  2889.         mbedtls_ssl_set_async_operation_data( ssl, NULL );
  2890.     }
  2891.     MBEDTLS_SSL_DEBUG_RET( 2, "ssl_resume_server_key_exchange", ret );
  2892.     return( ret );
  2893. }
  2894. #endif /* defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED) &&
  2895.           defined(MBEDTLS_SSL_ASYNC_PRIVATE) */
  2896.  
  2897. /* Prepare the ServerKeyExchange message, up to and including
  2898.  * calculating the signature if any, but excluding formatting the
  2899.  * signature and sending the message. */
  2900. static int ssl_prepare_server_key_exchange( mbedtls_ssl_context *ssl,
  2901.                                             size_t *signature_len )
  2902. {
  2903.     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
  2904.                             ssl->transform_negotiate->ciphersuite_info;
  2905. #if defined(MBEDTLS_KEY_EXCHANGE__SOME_PFS__ENABLED)
  2906. #if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED)
  2907.     unsigned char *dig_signed = NULL;
  2908. #endif /* MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED */
  2909. #endif /* MBEDTLS_KEY_EXCHANGE__SOME_PFS__ENABLED */
  2910.  
  2911.     (void) ciphersuite_info; /* unused in some configurations */
  2912. #if !defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED)
  2913.     (void) signature_len;
  2914. #endif /* MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED */
  2915.  
  2916.     ssl->out_msglen = 4; /* header (type:1, length:3) to be written later */
  2917.  
  2918.     /*
  2919.      *
  2920.      * Part 1: Provide key exchange parameters for chosen ciphersuite.
  2921.      *
  2922.      */
  2923.  
  2924.     /*
  2925.      * - ECJPAKE key exchanges
  2926.      */
  2927. #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
  2928.     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
  2929.     {
  2930.         int ret;
  2931.         size_t len = 0;
  2932.  
  2933.         ret = mbedtls_ecjpake_write_round_two(
  2934.             &ssl->handshake->ecjpake_ctx,
  2935.             ssl->out_msg + ssl->out_msglen,
  2936.             MBEDTLS_SSL_OUT_CONTENT_LEN - ssl->out_msglen, &len,
  2937.             ssl->conf->f_rng, ssl->conf->p_rng );
  2938.         if( ret != 0 )
  2939.         {
  2940.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_write_round_two", ret );
  2941.             return( ret );
  2942.         }
  2943.  
  2944.         ssl->out_msglen += len;
  2945.     }
  2946. #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
  2947.  
  2948.     /*
  2949.      * For (EC)DHE key exchanges with PSK, parameters are prefixed by support
  2950.      * identity hint (RFC 4279, Sec. 3). Until someone needs this feature,
  2951.      * we use empty support identity hints here.
  2952.      **/
  2953. #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)   || \
  2954.     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
  2955.     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
  2956.         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
  2957.     {
  2958.         ssl->out_msg[ssl->out_msglen++] = 0x00;
  2959.         ssl->out_msg[ssl->out_msglen++] = 0x00;
  2960.     }
  2961. #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED ||
  2962.           MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
  2963.  
  2964.     /*
  2965.      * - DHE key exchanges
  2966.      */
  2967. #if defined(MBEDTLS_KEY_EXCHANGE__SOME__DHE_ENABLED)
  2968.     if( mbedtls_ssl_ciphersuite_uses_dhe( ciphersuite_info ) )
  2969.     {
  2970.         int ret;
  2971.         size_t len = 0;
  2972.  
  2973.         if( ssl->conf->dhm_P.p == NULL || ssl->conf->dhm_G.p == NULL )
  2974.         {
  2975.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "no DH parameters set" ) );
  2976.             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  2977.         }
  2978.  
  2979.         /*
  2980.          * Ephemeral DH parameters:
  2981.          *
  2982.          * struct {
  2983.          *     opaque dh_p<1..2^16-1>;
  2984.          *     opaque dh_g<1..2^16-1>;
  2985.          *     opaque dh_Ys<1..2^16-1>;
  2986.          * } ServerDHParams;
  2987.          */
  2988.         if( ( ret = mbedtls_dhm_set_group( &ssl->handshake->dhm_ctx,
  2989.                                            &ssl->conf->dhm_P,
  2990.                                            &ssl->conf->dhm_G ) ) != 0 )
  2991.         {
  2992.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_set_group", ret );
  2993.             return( ret );
  2994.         }
  2995.  
  2996.         if( ( ret = mbedtls_dhm_make_params(
  2997.                   &ssl->handshake->dhm_ctx,
  2998.                   (int) mbedtls_mpi_size( &ssl->handshake->dhm_ctx.P ),
  2999.                   ssl->out_msg + ssl->out_msglen, &len,
  3000.                   ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
  3001.         {
  3002.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_make_params", ret );
  3003.             return( ret );
  3004.         }
  3005.  
  3006. #if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED)
  3007.         dig_signed = ssl->out_msg + ssl->out_msglen;
  3008. #endif
  3009.  
  3010.         ssl->out_msglen += len;
  3011.  
  3012.         MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: X ", &ssl->handshake->dhm_ctx.X  );
  3013.         MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: P ", &ssl->handshake->dhm_ctx.P  );
  3014.         MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: G ", &ssl->handshake->dhm_ctx.G  );
  3015.         MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: GX", &ssl->handshake->dhm_ctx.GX );
  3016.     }
  3017. #endif /* MBEDTLS_KEY_EXCHANGE__SOME__DHE_ENABLED */
  3018.  
  3019.     /*
  3020.      * - ECDHE key exchanges
  3021.      */
  3022. #if defined(MBEDTLS_KEY_EXCHANGE__SOME__ECDHE_ENABLED)
  3023.     if( mbedtls_ssl_ciphersuite_uses_ecdhe( ciphersuite_info ) )
  3024.     {
  3025.         /*
  3026.          * Ephemeral ECDH parameters:
  3027.          *
  3028.          * struct {
  3029.          *     ECParameters curve_params;
  3030.          *     ECPoint      public;
  3031.          * } ServerECDHParams;
  3032.          */
  3033.         const mbedtls_ecp_curve_info **curve = NULL;
  3034.         const mbedtls_ecp_group_id *gid;
  3035.         int ret;
  3036.         size_t len = 0;
  3037.  
  3038.         /* Match our preference list against the offered curves */
  3039.         for( gid = ssl->conf->curve_list; *gid != MBEDTLS_ECP_DP_NONE; gid++ )
  3040.             for( curve = ssl->handshake->curves; *curve != NULL; curve++ )
  3041.                 if( (*curve)->grp_id == *gid )
  3042.                     goto curve_matching_done;
  3043.  
  3044. curve_matching_done:
  3045.         if( curve == NULL || *curve == NULL )
  3046.         {
  3047.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "no matching curve for ECDHE" ) );
  3048.             return( MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN );
  3049.         }
  3050.  
  3051.         MBEDTLS_SSL_DEBUG_MSG( 2, ( "ECDHE curve: %s", (*curve)->name ) );
  3052.  
  3053.         if( ( ret = mbedtls_ecdh_setup( &ssl->handshake->ecdh_ctx,
  3054.                                         (*curve)->grp_id ) ) != 0 )
  3055.         {
  3056.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecp_group_load", ret );
  3057.             return( ret );
  3058.         }
  3059.  
  3060.         if( ( ret = mbedtls_ecdh_make_params(
  3061.                   &ssl->handshake->ecdh_ctx, &len,
  3062.                   ssl->out_msg + ssl->out_msglen,
  3063.                   MBEDTLS_SSL_OUT_CONTENT_LEN - ssl->out_msglen,
  3064.                   ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
  3065.         {
  3066.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_make_params", ret );
  3067.             return( ret );
  3068.         }
  3069.  
  3070. #if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED)
  3071.         dig_signed = ssl->out_msg + ssl->out_msglen;
  3072. #endif
  3073.  
  3074.         ssl->out_msglen += len;
  3075.  
  3076.         MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx,
  3077.                                 MBEDTLS_DEBUG_ECDH_Q );
  3078.     }
  3079. #endif /* MBEDTLS_KEY_EXCHANGE__SOME__ECDHE_ENABLED */
  3080.  
  3081.     /*
  3082.      *
  3083.      * Part 2: For key exchanges involving the server signing the
  3084.      *         exchange parameters, compute and add the signature here.
  3085.      *
  3086.      */
  3087. #if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED)
  3088.     if( mbedtls_ssl_ciphersuite_uses_server_signature( ciphersuite_info ) )
  3089.     {
  3090.         size_t dig_signed_len = ssl->out_msg + ssl->out_msglen - dig_signed;
  3091.         size_t hashlen = 0;
  3092.         unsigned char hash[MBEDTLS_MD_MAX_SIZE];
  3093.         int ret;
  3094.  
  3095.         /*
  3096.          * 2.1: Choose hash algorithm:
  3097.          * A: For TLS 1.2, obey signature-hash-algorithm extension
  3098.          *    to choose appropriate hash.
  3099.          * B: For SSL3, TLS1.0, TLS1.1 and ECDHE_ECDSA, use SHA1
  3100.          *    (RFC 4492, Sec. 5.4)
  3101.          * C: Otherwise, use MD5 + SHA1 (RFC 4346, Sec. 7.4.3)
  3102.          */
  3103.  
  3104.         mbedtls_md_type_t md_alg;
  3105.  
  3106. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  3107.         mbedtls_pk_type_t sig_alg =
  3108.             mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info );
  3109.         if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
  3110.         {
  3111.             /* A: For TLS 1.2, obey signature-hash-algorithm extension
  3112.              *    (RFC 5246, Sec. 7.4.1.4.1). */
  3113.             if( sig_alg == MBEDTLS_PK_NONE ||
  3114.                 ( md_alg = mbedtls_ssl_sig_hash_set_find( &ssl->handshake->hash_algs,
  3115.                                                           sig_alg ) ) == MBEDTLS_MD_NONE )
  3116.             {
  3117.                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  3118.                 /* (... because we choose a cipher suite
  3119.                  *      only if there is a matching hash.) */
  3120.                 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  3121.             }
  3122.         }
  3123.         else
  3124. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  3125. #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
  3126.     defined(MBEDTLS_SSL_PROTO_TLS1_1)
  3127.         if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA )
  3128.         {
  3129.             /* B: Default hash SHA1 */
  3130.             md_alg = MBEDTLS_MD_SHA1;
  3131.         }
  3132.         else
  3133. #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
  3134.           MBEDTLS_SSL_PROTO_TLS1_1 */
  3135.         {
  3136.             /* C: MD5 + SHA1 */
  3137.             md_alg = MBEDTLS_MD_NONE;
  3138.         }
  3139.  
  3140.         MBEDTLS_SSL_DEBUG_MSG( 3, ( "pick hash algorithm %d for signing", md_alg ) );
  3141.  
  3142.         /*
  3143.          * 2.2: Compute the hash to be signed
  3144.          */
  3145. #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
  3146.     defined(MBEDTLS_SSL_PROTO_TLS1_1)
  3147.         if( md_alg == MBEDTLS_MD_NONE )
  3148.         {
  3149.             hashlen = 36;
  3150.             ret = mbedtls_ssl_get_key_exchange_md_ssl_tls( ssl, hash,
  3151.                                                            dig_signed,
  3152.                                                            dig_signed_len );
  3153.             if( ret != 0 )
  3154.                 return( ret );
  3155.         }
  3156.         else
  3157. #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
  3158.           MBEDTLS_SSL_PROTO_TLS1_1 */
  3159. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
  3160.     defined(MBEDTLS_SSL_PROTO_TLS1_2)
  3161.         if( md_alg != MBEDTLS_MD_NONE )
  3162.         {
  3163.             ret = mbedtls_ssl_get_key_exchange_md_tls1_2( ssl, hash, &hashlen,
  3164.                                                           dig_signed,
  3165.                                                           dig_signed_len,
  3166.                                                           md_alg );
  3167.             if( ret != 0 )
  3168.                 return( ret );
  3169.         }
  3170.         else
  3171. #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
  3172.           MBEDTLS_SSL_PROTO_TLS1_2 */
  3173.         {
  3174.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  3175.             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  3176.         }
  3177.  
  3178.         MBEDTLS_SSL_DEBUG_BUF( 3, "parameters hash", hash, hashlen );
  3179.  
  3180.         /*
  3181.          * 2.3: Compute and add the signature
  3182.          */
  3183. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  3184.         if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
  3185.         {
  3186.             /*
  3187.              * For TLS 1.2, we need to specify signature and hash algorithm
  3188.              * explicitly through a prefix to the signature.
  3189.              *
  3190.              * struct {
  3191.              *    HashAlgorithm hash;
  3192.              *    SignatureAlgorithm signature;
  3193.              * } SignatureAndHashAlgorithm;
  3194.              *
  3195.              * struct {
  3196.              *    SignatureAndHashAlgorithm algorithm;
  3197.              *    opaque signature<0..2^16-1>;
  3198.              * } DigitallySigned;
  3199.              *
  3200.              */
  3201.  
  3202.             ssl->out_msg[ssl->out_msglen++] =
  3203.                 mbedtls_ssl_hash_from_md_alg( md_alg );
  3204.             ssl->out_msg[ssl->out_msglen++] =
  3205.                 mbedtls_ssl_sig_from_pk_alg( sig_alg );
  3206.         }
  3207. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  3208.  
  3209. #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
  3210.         if( ssl->conf->f_async_sign_start != NULL )
  3211.         {
  3212.             ret = ssl->conf->f_async_sign_start( ssl,
  3213.                                                  mbedtls_ssl_own_cert( ssl ),
  3214.                                                  md_alg, hash, hashlen );
  3215.             switch( ret )
  3216.             {
  3217.             case MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH:
  3218.                 /* act as if f_async_sign was null */
  3219.                 break;
  3220.             case 0:
  3221.                 ssl->handshake->async_in_progress = 1;
  3222.                 return( ssl_resume_server_key_exchange( ssl, signature_len ) );
  3223.             case MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS:
  3224.                 ssl->handshake->async_in_progress = 1;
  3225.                 return( MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS );
  3226.             default:
  3227.                 MBEDTLS_SSL_DEBUG_RET( 1, "f_async_sign_start", ret );
  3228.                 return( ret );
  3229.             }
  3230.         }
  3231. #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
  3232.  
  3233.         if( mbedtls_ssl_own_key( ssl ) == NULL )
  3234.         {
  3235.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no private key" ) );
  3236.             return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );
  3237.         }
  3238.  
  3239.         /* Append the signature to ssl->out_msg, leaving 2 bytes for the
  3240.          * signature length which will be added in ssl_write_server_key_exchange
  3241.          * after the call to ssl_prepare_server_key_exchange.
  3242.          * ssl_write_server_key_exchange also takes care of incrementing
  3243.          * ssl->out_msglen. */
  3244.         if( ( ret = mbedtls_pk_sign( mbedtls_ssl_own_key( ssl ),
  3245.                                      md_alg, hash, hashlen,
  3246.                                      ssl->out_msg + ssl->out_msglen + 2,
  3247.                                      signature_len,
  3248.                                      ssl->conf->f_rng,
  3249.                                      ssl->conf->p_rng ) ) != 0 )
  3250.         {
  3251.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_sign", ret );
  3252.             return( ret );
  3253.         }
  3254.     }
  3255. #endif /* MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED */
  3256.  
  3257.     return( 0 );
  3258. }
  3259.  
  3260. /* Prepare the ServerKeyExchange message and send it. For ciphersuites
  3261.  * that do not include a ServerKeyExchange message, do nothing. Either
  3262.  * way, if successful, move on to the next step in the SSL state
  3263.  * machine. */
  3264. static int ssl_write_server_key_exchange( mbedtls_ssl_context *ssl )
  3265. {
  3266.     int ret;
  3267.     size_t signature_len = 0;
  3268. #if defined(MBEDTLS_KEY_EXCHANGE__SOME_NON_PFS__ENABLED)
  3269.     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
  3270.                             ssl->transform_negotiate->ciphersuite_info;
  3271. #endif /* MBEDTLS_KEY_EXCHANGE__SOME_NON_PFS__ENABLED */
  3272.  
  3273.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write server key exchange" ) );
  3274.  
  3275. #if defined(MBEDTLS_KEY_EXCHANGE__SOME_NON_PFS__ENABLED)
  3276.     /* Extract static ECDH parameters and abort if ServerKeyExchange
  3277.      * is not needed. */
  3278.     if( mbedtls_ssl_ciphersuite_no_pfs( ciphersuite_info ) )
  3279.     {
  3280.         /* For suites involving ECDH, extract DH parameters
  3281.          * from certificate at this point. */
  3282. #if defined(MBEDTLS_KEY_EXCHANGE__SOME__ECDH_ENABLED)
  3283.         if( mbedtls_ssl_ciphersuite_uses_ecdh( ciphersuite_info ) )
  3284.         {
  3285.             ssl_get_ecdh_params_from_cert( ssl );
  3286.         }
  3287. #endif /* MBEDTLS_KEY_EXCHANGE__SOME__ECDH_ENABLED */
  3288.  
  3289.         /* Key exchanges not involving ephemeral keys don't use
  3290.          * ServerKeyExchange, so end here. */
  3291.         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write server key exchange" ) );
  3292.         ssl->state++;
  3293.         return( 0 );
  3294.     }
  3295. #endif /* MBEDTLS_KEY_EXCHANGE__SOME_NON_PFS__ENABLED */
  3296.  
  3297. #if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED) && \
  3298.     defined(MBEDTLS_SSL_ASYNC_PRIVATE)
  3299.     /* If we have already prepared the message and there is an ongoing
  3300.      * signature operation, resume signing. */
  3301.     if( ssl->handshake->async_in_progress != 0 )
  3302.     {
  3303.         MBEDTLS_SSL_DEBUG_MSG( 2, ( "resuming signature operation" ) );
  3304.         ret = ssl_resume_server_key_exchange( ssl, &signature_len );
  3305.     }
  3306.     else
  3307. #endif /* defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED) &&
  3308.           defined(MBEDTLS_SSL_ASYNC_PRIVATE) */
  3309.     {
  3310.         /* ServerKeyExchange is needed. Prepare the message. */
  3311.         ret = ssl_prepare_server_key_exchange( ssl, &signature_len );
  3312.     }
  3313.  
  3314.     if( ret != 0 )
  3315.     {
  3316.         /* If we're starting to write a new message, set ssl->out_msglen
  3317.          * to 0. But if we're resuming after an asynchronous message,
  3318.          * out_msglen is the amount of data written so far and mst be
  3319.          * preserved. */
  3320.         if( ret == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS )
  3321.             MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write server key exchange (pending)" ) );
  3322.         else
  3323.             ssl->out_msglen = 0;
  3324.         return( ret );
  3325.     }
  3326.  
  3327.     /* If there is a signature, write its length.
  3328.      * ssl_prepare_server_key_exchange already wrote the signature
  3329.      * itself at its proper place in the output buffer. */
  3330. #if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED)
  3331.     if( signature_len != 0 )
  3332.     {
  3333.         ssl->out_msg[ssl->out_msglen++] = (unsigned char)( signature_len >> 8 );
  3334.         ssl->out_msg[ssl->out_msglen++] = (unsigned char)( signature_len      );
  3335.  
  3336.         MBEDTLS_SSL_DEBUG_BUF( 3, "my signature",
  3337.                                ssl->out_msg + ssl->out_msglen,
  3338.                                signature_len );
  3339.  
  3340.         /* Skip over the already-written signature */
  3341.         ssl->out_msglen += signature_len;
  3342.     }
  3343. #endif /* MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED */
  3344.  
  3345.     /* Add header and send. */
  3346.     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
  3347.     ssl->out_msg[0]  = MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE;
  3348.  
  3349.     ssl->state++;
  3350.  
  3351.     if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
  3352.     {
  3353.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
  3354.         return( ret );
  3355.     }
  3356.  
  3357.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write server key exchange" ) );
  3358.     return( 0 );
  3359. }
  3360.  
  3361. static int ssl_write_server_hello_done( mbedtls_ssl_context *ssl )
  3362. {
  3363.     int ret;
  3364.  
  3365.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write server hello done" ) );
  3366.  
  3367.     ssl->out_msglen  = 4;
  3368.     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
  3369.     ssl->out_msg[0]  = MBEDTLS_SSL_HS_SERVER_HELLO_DONE;
  3370.  
  3371.     ssl->state++;
  3372.  
  3373. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  3374.     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  3375.         mbedtls_ssl_send_flight_completed( ssl );
  3376. #endif
  3377.  
  3378.     if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
  3379.     {
  3380.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
  3381.         return( ret );
  3382.     }
  3383.  
  3384. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  3385.     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  3386.         ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 )
  3387.     {
  3388.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flight_transmit", ret );
  3389.         return( ret );
  3390.     }
  3391. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  3392.  
  3393.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write server hello done" ) );
  3394.  
  3395.     return( 0 );
  3396. }
  3397.  
  3398. #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) ||                       \
  3399.     defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
  3400. static int ssl_parse_client_dh_public( mbedtls_ssl_context *ssl, unsigned char **p,
  3401.                                        const unsigned char *end )
  3402. {
  3403.     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
  3404.     size_t n;
  3405.  
  3406.     /*
  3407.      * Receive G^Y mod P, premaster = (G^Y)^X mod P
  3408.      */
  3409.     if( *p + 2 > end )
  3410.     {
  3411.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
  3412.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
  3413.     }
  3414.  
  3415.     n = ( (*p)[0] << 8 ) | (*p)[1];
  3416.     *p += 2;
  3417.  
  3418.     if( *p + n > end )
  3419.     {
  3420.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
  3421.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
  3422.     }
  3423.  
  3424.     if( ( ret = mbedtls_dhm_read_public( &ssl->handshake->dhm_ctx, *p, n ) ) != 0 )
  3425.     {
  3426.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_read_public", ret );
  3427.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP );
  3428.     }
  3429.  
  3430.     *p += n;
  3431.  
  3432.     MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: GY", &ssl->handshake->dhm_ctx.GY );
  3433.  
  3434.     return( ret );
  3435. }
  3436. #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
  3437.           MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
  3438.  
  3439. #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) ||                           \
  3440.     defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
  3441.  
  3442. #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
  3443. static int ssl_resume_decrypt_pms( mbedtls_ssl_context *ssl,
  3444.                                    unsigned char *peer_pms,
  3445.                                    size_t *peer_pmslen,
  3446.                                    size_t peer_pmssize )
  3447. {
  3448.     int ret = ssl->conf->f_async_resume( ssl,
  3449.                                          peer_pms, peer_pmslen, peer_pmssize );
  3450.     if( ret != MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS )
  3451.     {
  3452.         ssl->handshake->async_in_progress = 0;
  3453.         mbedtls_ssl_set_async_operation_data( ssl, NULL );
  3454.     }
  3455.     MBEDTLS_SSL_DEBUG_RET( 2, "ssl_decrypt_encrypted_pms", ret );
  3456.     return( ret );
  3457. }
  3458. #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
  3459.  
  3460. static int ssl_decrypt_encrypted_pms( mbedtls_ssl_context *ssl,
  3461.                                       const unsigned char *p,
  3462.                                       const unsigned char *end,
  3463.                                       unsigned char *peer_pms,
  3464.                                       size_t *peer_pmslen,
  3465.                                       size_t peer_pmssize )
  3466. {
  3467.     int ret;
  3468.     mbedtls_pk_context *private_key = mbedtls_ssl_own_key( ssl );
  3469.     mbedtls_pk_context *public_key = &mbedtls_ssl_own_cert( ssl )->pk;
  3470.     size_t len = mbedtls_pk_get_len( public_key );
  3471.  
  3472. #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
  3473.     /* If we have already started decoding the message and there is an ongoing
  3474.      * decryption operation, resume signing. */
  3475.     if( ssl->handshake->async_in_progress != 0 )
  3476.     {
  3477.         MBEDTLS_SSL_DEBUG_MSG( 2, ( "resuming decryption operation" ) );
  3478.         return( ssl_resume_decrypt_pms( ssl,
  3479.                                         peer_pms, peer_pmslen, peer_pmssize ) );
  3480.     }
  3481. #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
  3482.  
  3483.     /*
  3484.      * Prepare to decrypt the premaster using own private RSA key
  3485.      */
  3486. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
  3487.     defined(MBEDTLS_SSL_PROTO_TLS1_2)
  3488.     if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_0 )
  3489.     {
  3490.         if ( p + 2 > end ) {
  3491.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
  3492.             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
  3493.         }
  3494.         if( *p++ != ( ( len >> 8 ) & 0xFF ) ||
  3495.             *p++ != ( ( len      ) & 0xFF ) )
  3496.         {
  3497.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
  3498.             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
  3499.         }
  3500.     }
  3501. #endif
  3502.  
  3503.     if( p + len != end )
  3504.     {
  3505.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
  3506.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
  3507.     }
  3508.  
  3509.     /*
  3510.      * Decrypt the premaster secret
  3511.      */
  3512. #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
  3513.     if( ssl->conf->f_async_decrypt_start != NULL )
  3514.     {
  3515.         ret = ssl->conf->f_async_decrypt_start( ssl,
  3516.                                                 mbedtls_ssl_own_cert( ssl ),
  3517.                                                 p, len );
  3518.         switch( ret )
  3519.         {
  3520.         case MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH:
  3521.             /* act as if f_async_decrypt_start was null */
  3522.             break;
  3523.         case 0:
  3524.             ssl->handshake->async_in_progress = 1;
  3525.             return( ssl_resume_decrypt_pms( ssl,
  3526.                                             peer_pms,
  3527.                                             peer_pmslen,
  3528.                                             peer_pmssize ) );
  3529.         case MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS:
  3530.             ssl->handshake->async_in_progress = 1;
  3531.             return( MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS );
  3532.         default:
  3533.             MBEDTLS_SSL_DEBUG_RET( 1, "f_async_decrypt_start", ret );
  3534.             return( ret );
  3535.         }
  3536.     }
  3537. #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
  3538.  
  3539.     if( ! mbedtls_pk_can_do( private_key, MBEDTLS_PK_RSA ) )
  3540.     {
  3541.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no RSA private key" ) );
  3542.         return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );
  3543.     }
  3544.  
  3545.     ret = mbedtls_pk_decrypt( private_key, p, len,
  3546.                               peer_pms, peer_pmslen, peer_pmssize,
  3547.                               ssl->conf->f_rng, ssl->conf->p_rng );
  3548.     return( ret );
  3549. }
  3550.  
  3551. static int ssl_parse_encrypted_pms( mbedtls_ssl_context *ssl,
  3552.                                     const unsigned char *p,
  3553.                                     const unsigned char *end,
  3554.                                     size_t pms_offset )
  3555. {
  3556.     int ret;
  3557.     unsigned char *pms = ssl->handshake->premaster + pms_offset;
  3558.     unsigned char ver[2];
  3559.     unsigned char fake_pms[48], peer_pms[48];
  3560.     unsigned char mask;
  3561.     size_t i, peer_pmslen;
  3562.     unsigned int diff;
  3563.  
  3564.     /* In case of a failure in decryption, the decryption may write less than
  3565.      * 2 bytes of output, but we always read the first two bytes. It doesn't
  3566.      * matter in the end because diff will be nonzero in that case due to
  3567.      * peer_pmslen being less than 48, and we only care whether diff is 0.
  3568.      * But do initialize peer_pms for robustness anyway. This also makes
  3569.      * memory analyzers happy (don't access uninitialized memory, even
  3570.      * if it's an unsigned char). */
  3571.     peer_pms[0] = peer_pms[1] = ~0;
  3572.  
  3573.     ret = ssl_decrypt_encrypted_pms( ssl, p, end,
  3574.                                      peer_pms,
  3575.                                      &peer_pmslen,
  3576.                                      sizeof( peer_pms ) );
  3577.  
  3578. #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
  3579.     if ( ret == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS )
  3580.         return( ret );
  3581. #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
  3582.  
  3583.     mbedtls_ssl_write_version( ssl->handshake->max_major_ver,
  3584.                                ssl->handshake->max_minor_ver,
  3585.                                ssl->conf->transport, ver );
  3586.  
  3587.     /* Avoid data-dependent branches while checking for invalid
  3588.      * padding, to protect against timing-based Bleichenbacher-type
  3589.      * attacks. */
  3590.     diff  = (unsigned int) ret;
  3591.     diff |= peer_pmslen ^ 48;
  3592.     diff |= peer_pms[0] ^ ver[0];
  3593.     diff |= peer_pms[1] ^ ver[1];
  3594.  
  3595.     /* mask = diff ? 0xff : 0x00 using bit operations to avoid branches */
  3596.     /* MSVC has a warning about unary minus on unsigned, but this is
  3597.      * well-defined and precisely what we want to do here */
  3598. #if defined(_MSC_VER)
  3599. #pragma warning( push )
  3600. #pragma warning( disable : 4146 )
  3601. #endif
  3602.     mask = - ( ( diff | - diff ) >> ( sizeof( unsigned int ) * 8 - 1 ) );
  3603. #if defined(_MSC_VER)
  3604. #pragma warning( pop )
  3605. #endif
  3606.  
  3607.     /*
  3608.      * Protection against Bleichenbacher's attack: invalid PKCS#1 v1.5 padding
  3609.      * must not cause the connection to end immediately; instead, send a
  3610.      * bad_record_mac later in the handshake.
  3611.      * To protect against timing-based variants of the attack, we must
  3612.      * not have any branch that depends on whether the decryption was
  3613.      * successful. In particular, always generate the fake premaster secret,
  3614.      * regardless of whether it will ultimately influence the output or not.
  3615.      */
  3616.     ret = ssl->conf->f_rng( ssl->conf->p_rng, fake_pms, sizeof( fake_pms ) );
  3617.     if( ret != 0 )
  3618.     {
  3619.         /* It's ok to abort on an RNG failure, since this does not reveal
  3620.          * anything about the RSA decryption. */
  3621.         return( ret );
  3622.     }
  3623.  
  3624. #if defined(MBEDTLS_SSL_DEBUG_ALL)
  3625.     if( diff != 0 )
  3626.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
  3627. #endif
  3628.  
  3629.     if( sizeof( ssl->handshake->premaster ) < pms_offset ||
  3630.         sizeof( ssl->handshake->premaster ) - pms_offset < 48 )
  3631.     {
  3632.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  3633.         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  3634.     }
  3635.     ssl->handshake->pmslen = 48;
  3636.  
  3637.     /* Set pms to either the true or the fake PMS, without
  3638.      * data-dependent branches. */
  3639.     for( i = 0; i < ssl->handshake->pmslen; i++ )
  3640.         pms[i] = ( mask & fake_pms[i] ) | ( (~mask) & peer_pms[i] );
  3641.  
  3642.     return( 0 );
  3643. }
  3644. #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED ||
  3645.           MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
  3646.  
  3647. #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
  3648. static int ssl_parse_client_psk_identity( mbedtls_ssl_context *ssl, unsigned char **p,
  3649.                                           const unsigned char *end )
  3650. {
  3651.     int ret = 0;
  3652.     size_t n;
  3653.  
  3654.     if( ssl->conf->f_psk == NULL &&
  3655.         ( ssl->conf->psk == NULL || ssl->conf->psk_identity == NULL ||
  3656.           ssl->conf->psk_identity_len == 0 || ssl->conf->psk_len == 0 ) )
  3657.     {
  3658.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no pre-shared key" ) );
  3659.         return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );
  3660.     }
  3661.  
  3662.     /*
  3663.      * Receive client pre-shared key identity name
  3664.      */
  3665.     if( end - *p < 2 )
  3666.     {
  3667.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
  3668.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
  3669.     }
  3670.  
  3671.     n = ( (*p)[0] << 8 ) | (*p)[1];
  3672.     *p += 2;
  3673.  
  3674.     if( n < 1 || n > 65535 || n > (size_t) ( end - *p ) )
  3675.     {
  3676.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
  3677.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
  3678.     }
  3679.  
  3680.     if( ssl->conf->f_psk != NULL )
  3681.     {
  3682.         if( ssl->conf->f_psk( ssl->conf->p_psk, ssl, *p, n ) != 0 )
  3683.             ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;
  3684.     }
  3685.     else
  3686.     {
  3687.         /* Identity is not a big secret since clients send it in the clear,
  3688.          * but treat it carefully anyway, just in case */
  3689.         if( n != ssl->conf->psk_identity_len ||
  3690.             mbedtls_ssl_safer_memcmp( ssl->conf->psk_identity, *p, n ) != 0 )
  3691.         {
  3692.             ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;
  3693.         }
  3694.     }
  3695.  
  3696.     if( ret == MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY )
  3697.     {
  3698.         MBEDTLS_SSL_DEBUG_BUF( 3, "Unknown PSK identity", *p, n );
  3699.         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  3700.                                         MBEDTLS_SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY );
  3701.         return( MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY );
  3702.     }
  3703.  
  3704.     *p += n;
  3705.  
  3706.     return( 0 );
  3707. }
  3708. #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
  3709.  
  3710. static int ssl_parse_client_key_exchange( mbedtls_ssl_context *ssl )
  3711. {
  3712.     int ret;
  3713.     const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
  3714.     unsigned char *p, *end;
  3715.  
  3716.     ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
  3717.  
  3718.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse client key exchange" ) );
  3719.  
  3720. #if defined(MBEDTLS_SSL_ASYNC_PRIVATE) && \
  3721.     ( defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \
  3722.       defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) )
  3723.     if( ( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
  3724.           ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA ) &&
  3725.         ( ssl->handshake->async_in_progress != 0 ) )
  3726.     {
  3727.         /* We've already read a record and there is an asynchronous
  3728.          * operation in progress to decrypt it. So skip reading the
  3729.          * record. */
  3730.         MBEDTLS_SSL_DEBUG_MSG( 3, ( "will resume decryption of previously-read record" ) );
  3731.     }
  3732.     else
  3733. #endif
  3734.     if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
  3735.     {
  3736.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
  3737.         return( ret );
  3738.     }
  3739.  
  3740.     p = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
  3741.     end = ssl->in_msg + ssl->in_hslen;
  3742.  
  3743.     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
  3744.     {
  3745.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
  3746.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
  3747.     }
  3748.  
  3749.     if( ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_KEY_EXCHANGE )
  3750.     {
  3751.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
  3752.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
  3753.     }
  3754.  
  3755. #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)
  3756.     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA )
  3757.     {
  3758.         if( ( ret = ssl_parse_client_dh_public( ssl, &p, end ) ) != 0 )
  3759.         {
  3760.             MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_dh_public" ), ret );
  3761.             return( ret );
  3762.         }
  3763.  
  3764.         if( p != end )
  3765.         {
  3766.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange" ) );
  3767.             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
  3768.         }
  3769.  
  3770.         if( ( ret = mbedtls_dhm_calc_secret( &ssl->handshake->dhm_ctx,
  3771.                                       ssl->handshake->premaster,
  3772.                                       MBEDTLS_PREMASTER_SIZE,
  3773.                                      &ssl->handshake->pmslen,
  3774.                                       ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
  3775.         {
  3776.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_calc_secret", ret );
  3777.             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_CS );
  3778.         }
  3779.  
  3780.         MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: K ", &ssl->handshake->dhm_ctx.K  );
  3781.     }
  3782.     else
  3783. #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED */
  3784. #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||                     \
  3785.     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) ||                   \
  3786.     defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||                      \
  3787.     defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
  3788.     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
  3789.         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA ||
  3790.         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||
  3791.         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA )
  3792.     {
  3793.         if( ( ret = mbedtls_ecdh_read_public( &ssl->handshake->ecdh_ctx,
  3794.                                       p, end - p) ) != 0 )
  3795.         {
  3796.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_read_public", ret );
  3797.             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP );
  3798.         }
  3799.  
  3800.         MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx,
  3801.                                 MBEDTLS_DEBUG_ECDH_QP );
  3802.  
  3803.         if( ( ret = mbedtls_ecdh_calc_secret( &ssl->handshake->ecdh_ctx,
  3804.                                       &ssl->handshake->pmslen,
  3805.                                        ssl->handshake->premaster,
  3806.                                        MBEDTLS_MPI_MAX_SIZE,
  3807.                                        ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
  3808.         {
  3809.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_calc_secret", ret );
  3810.             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_CS );
  3811.         }
  3812.  
  3813.         MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx,
  3814.                                 MBEDTLS_DEBUG_ECDH_Z );
  3815.     }
  3816.     else
  3817. #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
  3818.           MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
  3819.           MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
  3820.           MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
  3821. #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
  3822.     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK )
  3823.     {
  3824.         if( ( ret = ssl_parse_client_psk_identity( ssl, &p, end ) ) != 0 )
  3825.         {
  3826.             MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_psk_identity" ), ret );
  3827.             return( ret );
  3828.         }
  3829.  
  3830.         if( p != end )
  3831.         {
  3832.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange" ) );
  3833.             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
  3834.         }
  3835.  
  3836.         if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl,
  3837.                         ciphersuite_info->key_exchange ) ) != 0 )
  3838.         {
  3839.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_psk_derive_premaster", ret );
  3840.             return( ret );
  3841.         }
  3842.     }
  3843.     else
  3844. #endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */
  3845. #if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
  3846.     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
  3847.     {
  3848. #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
  3849.         if ( ssl->handshake->async_in_progress != 0 )
  3850.         {
  3851.             /* There is an asynchronous operation in progress to
  3852.              * decrypt the encrypted premaster secret, so skip
  3853.              * directly to resuming this operation. */
  3854.             MBEDTLS_SSL_DEBUG_MSG( 3, ( "PSK identity already parsed" ) );
  3855.             /* Update p to skip the PSK identity. ssl_parse_encrypted_pms
  3856.              * won't actually use it, but maintain p anyway for robustness. */
  3857.             p += ssl->conf->psk_identity_len + 2;
  3858.         }
  3859.         else
  3860. #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
  3861.         if( ( ret = ssl_parse_client_psk_identity( ssl, &p, end ) ) != 0 )
  3862.         {
  3863.             MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_psk_identity" ), ret );
  3864.             return( ret );
  3865.         }
  3866.  
  3867.         if( ( ret = ssl_parse_encrypted_pms( ssl, p, end, 2 ) ) != 0 )
  3868.         {
  3869.             MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_encrypted_pms" ), ret );
  3870.             return( ret );
  3871.         }
  3872.  
  3873.         if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl,
  3874.                         ciphersuite_info->key_exchange ) ) != 0 )
  3875.         {
  3876.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_psk_derive_premaster", ret );
  3877.             return( ret );
  3878.         }
  3879.     }
  3880.     else
  3881. #endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
  3882. #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
  3883.     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
  3884.     {
  3885.         if( ( ret = ssl_parse_client_psk_identity( ssl, &p, end ) ) != 0 )
  3886.         {
  3887.             MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_psk_identity" ), ret );
  3888.             return( ret );
  3889.         }
  3890.         if( ( ret = ssl_parse_client_dh_public( ssl, &p, end ) ) != 0 )
  3891.         {
  3892.             MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_dh_public" ), ret );
  3893.             return( ret );
  3894.         }
  3895.  
  3896.         if( p != end )
  3897.         {
  3898.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange" ) );
  3899.             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
  3900.         }
  3901.  
  3902.         if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl,
  3903.                         ciphersuite_info->key_exchange ) ) != 0 )
  3904.         {
  3905.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_psk_derive_premaster", ret );
  3906.             return( ret );
  3907.         }
  3908.     }
  3909.     else
  3910. #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
  3911. #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
  3912.     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
  3913.     {
  3914.         if( ( ret = ssl_parse_client_psk_identity( ssl, &p, end ) ) != 0 )
  3915.         {
  3916.             MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_psk_identity" ), ret );
  3917.             return( ret );
  3918.         }
  3919.  
  3920.         if( ( ret = mbedtls_ecdh_read_public( &ssl->handshake->ecdh_ctx,
  3921.                                        p, end - p ) ) != 0 )
  3922.         {
  3923.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_read_public", ret );
  3924.             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP );
  3925.         }
  3926.  
  3927.         MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx,
  3928.                                 MBEDTLS_DEBUG_ECDH_QP );
  3929.  
  3930.         if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl,
  3931.                         ciphersuite_info->key_exchange ) ) != 0 )
  3932.         {
  3933.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_psk_derive_premaster", ret );
  3934.             return( ret );
  3935.         }
  3936.     }
  3937.     else
  3938. #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
  3939. #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
  3940.     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA )
  3941.     {
  3942.         if( ( ret = ssl_parse_encrypted_pms( ssl, p, end, 0 ) ) != 0 )
  3943.         {
  3944.             MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_parse_encrypted_pms_secret" ), ret );
  3945.             return( ret );
  3946.         }
  3947.     }
  3948.     else
  3949. #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */
  3950. #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
  3951.     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
  3952.     {
  3953.         ret = mbedtls_ecjpake_read_round_two( &ssl->handshake->ecjpake_ctx,
  3954.                                               p, end - p );
  3955.         if( ret != 0 )
  3956.         {
  3957.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_two", ret );
  3958.             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
  3959.         }
  3960.  
  3961.         ret = mbedtls_ecjpake_derive_secret( &ssl->handshake->ecjpake_ctx,
  3962.                 ssl->handshake->premaster, 32, &ssl->handshake->pmslen,
  3963.                 ssl->conf->f_rng, ssl->conf->p_rng );
  3964.         if( ret != 0 )
  3965.         {
  3966.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_derive_secret", ret );
  3967.             return( ret );
  3968.         }
  3969.     }
  3970.     else
  3971. #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
  3972.     {
  3973.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  3974.         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  3975.     }
  3976.  
  3977.     if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )
  3978.     {
  3979.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret );
  3980.         return( ret );
  3981.     }
  3982.  
  3983.     ssl->state++;
  3984.  
  3985.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse client key exchange" ) );
  3986.  
  3987.     return( 0 );
  3988. }
  3989.  
  3990. #if !defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)       && \
  3991.     !defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)   && \
  3992.     !defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED)  && \
  3993.     !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) && \
  3994.     !defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)&& \
  3995.     !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
  3996. static int ssl_parse_certificate_verify( mbedtls_ssl_context *ssl )
  3997. {
  3998.     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
  3999.         ssl->transform_negotiate->ciphersuite_info;
  4000.  
  4001.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate verify" ) );
  4002.  
  4003.     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
  4004.         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
  4005.         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
  4006.         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
  4007.         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
  4008.     {
  4009.         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate verify" ) );
  4010.         ssl->state++;
  4011.         return( 0 );
  4012.     }
  4013.  
  4014.     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  4015.     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  4016. }
  4017. #else
  4018. static int ssl_parse_certificate_verify( mbedtls_ssl_context *ssl )
  4019. {
  4020.     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
  4021.     size_t i, sig_len;
  4022.     unsigned char hash[48];
  4023.     unsigned char *hash_start = hash;
  4024.     size_t hashlen;
  4025. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  4026.     mbedtls_pk_type_t pk_alg;
  4027. #endif
  4028.     mbedtls_md_type_t md_alg;
  4029.     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
  4030.         ssl->transform_negotiate->ciphersuite_info;
  4031.  
  4032.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate verify" ) );
  4033.  
  4034.     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
  4035.         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
  4036.         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
  4037.         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
  4038.         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE ||
  4039.         ssl->session_negotiate->peer_cert == NULL )
  4040.     {
  4041.         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate verify" ) );
  4042.         ssl->state++;
  4043.         return( 0 );
  4044.     }
  4045.  
  4046.     /* Read the message without adding it to the checksum */
  4047.     ret = mbedtls_ssl_read_record( ssl, 0 /* no checksum update */ );
  4048.     if( 0 != ret )
  4049.     {
  4050.         MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ssl_read_record" ), ret );
  4051.         return( ret );
  4052.     }
  4053.  
  4054.     ssl->state++;
  4055.  
  4056.     /* Process the message contents */
  4057.     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ||
  4058.         ssl->in_msg[0] != MBEDTLS_SSL_HS_CERTIFICATE_VERIFY )
  4059.     {
  4060.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate verify message" ) );
  4061.         return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY );
  4062.     }
  4063.  
  4064.     i = mbedtls_ssl_hs_hdr_len( ssl );
  4065.  
  4066.     /*
  4067.      *  struct {
  4068.      *     SignatureAndHashAlgorithm algorithm; -- TLS 1.2 only
  4069.      *     opaque signature<0..2^16-1>;
  4070.      *  } DigitallySigned;
  4071.      */
  4072. #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
  4073.     defined(MBEDTLS_SSL_PROTO_TLS1_1)
  4074.     if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
  4075.     {
  4076.         md_alg = MBEDTLS_MD_NONE;
  4077.         hashlen = 36;
  4078.  
  4079.         /* For ECDSA, use SHA-1, not MD-5 + SHA-1 */
  4080.         if( mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk,
  4081.                         MBEDTLS_PK_ECDSA ) )
  4082.         {
  4083.             hash_start += 16;
  4084.             hashlen -= 16;
  4085.             md_alg = MBEDTLS_MD_SHA1;
  4086.         }
  4087.     }
  4088.     else
  4089. #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 ||
  4090.           MBEDTLS_SSL_PROTO_TLS1_1 */
  4091. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  4092.     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
  4093.     {
  4094.         if( i + 2 > ssl->in_hslen )
  4095.         {
  4096.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate verify message" ) );
  4097.             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY );
  4098.         }
  4099.  
  4100.         /*
  4101.          * Hash
  4102.          */
  4103.         md_alg = mbedtls_ssl_md_alg_from_hash( ssl->in_msg[i] );
  4104.  
  4105.         if( md_alg == MBEDTLS_MD_NONE || mbedtls_ssl_set_calc_verify_md( ssl, ssl->in_msg[i] ) )
  4106.         {
  4107.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "peer not adhering to requested sig_alg"
  4108.                                 " for verify message" ) );
  4109.             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY );
  4110.         }
  4111.  
  4112. #if !defined(MBEDTLS_MD_SHA1)
  4113.         if( MBEDTLS_MD_SHA1 == md_alg )
  4114.             hash_start += 16;
  4115. #endif
  4116.  
  4117.         /* Info from md_alg will be used instead */
  4118.         hashlen = 0;
  4119.  
  4120.         i++;
  4121.  
  4122.         /*
  4123.          * Signature
  4124.          */
  4125.         if( ( pk_alg = mbedtls_ssl_pk_alg_from_sig( ssl->in_msg[i] ) )
  4126.                         == MBEDTLS_PK_NONE )
  4127.         {
  4128.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "peer not adhering to requested sig_alg"
  4129.                                 " for verify message" ) );
  4130.             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY );
  4131.         }
  4132.  
  4133.         /*
  4134.          * Check the certificate's key type matches the signature alg
  4135.          */
  4136.         if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk, pk_alg ) )
  4137.         {
  4138.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "sig_alg doesn't match cert key" ) );
  4139.             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY );
  4140.         }
  4141.  
  4142.         i++;
  4143.     }
  4144.     else
  4145. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  4146.     {
  4147.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  4148.         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  4149.     }
  4150.  
  4151.     if( i + 2 > ssl->in_hslen )
  4152.     {
  4153.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate verify message" ) );
  4154.         return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY );
  4155.     }
  4156.  
  4157.     sig_len = ( ssl->in_msg[i] << 8 ) | ssl->in_msg[i+1];
  4158.     i += 2;
  4159.  
  4160.     if( i + sig_len != ssl->in_hslen )
  4161.     {
  4162.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate verify message" ) );
  4163.         return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY );
  4164.     }
  4165.  
  4166.     /* Calculate hash and verify signature */
  4167.     ssl->handshake->calc_verify( ssl, hash );
  4168.  
  4169.     if( ( ret = mbedtls_pk_verify( &ssl->session_negotiate->peer_cert->pk,
  4170.                            md_alg, hash_start, hashlen,
  4171.                            ssl->in_msg + i, sig_len ) ) != 0 )
  4172.     {
  4173.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_verify", ret );
  4174.         return( ret );
  4175.     }
  4176.  
  4177.     mbedtls_ssl_update_handshake_status( ssl );
  4178.  
  4179.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse certificate verify" ) );
  4180.  
  4181.     return( ret );
  4182. }
  4183. #endif /* !MBEDTLS_KEY_EXCHANGE_RSA_ENABLED &&
  4184.           !MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED &&
  4185.           !MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED &&
  4186.           !MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED &&
  4187.           !MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED &&
  4188.           !MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
  4189.  
  4190. #if defined(MBEDTLS_SSL_SESSION_TICKETS)
  4191. static int ssl_write_new_session_ticket( mbedtls_ssl_context *ssl )
  4192. {
  4193.     int ret;
  4194.     size_t tlen;
  4195.     uint32_t lifetime;
  4196.  
  4197.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write new session ticket" ) );
  4198.  
  4199.     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
  4200.     ssl->out_msg[0]  = MBEDTLS_SSL_HS_NEW_SESSION_TICKET;
  4201.  
  4202.     /*
  4203.      * struct {
  4204.      *     uint32 ticket_lifetime_hint;
  4205.      *     opaque ticket<0..2^16-1>;
  4206.      * } NewSessionTicket;
  4207.      *
  4208.      * 4  .  7   ticket_lifetime_hint (0 = unspecified)
  4209.      * 8  .  9   ticket_len (n)
  4210.      * 10 .  9+n ticket content
  4211.      */
  4212.  
  4213.     if( ( ret = ssl->conf->f_ticket_write( ssl->conf->p_ticket,
  4214.                                 ssl->session_negotiate,
  4215.                                 ssl->out_msg + 10,
  4216.                                 ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN,
  4217.                                 &tlen, &lifetime ) ) != 0 )
  4218.     {
  4219.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_ticket_write", ret );
  4220.         tlen = 0;
  4221.     }
  4222.  
  4223.     ssl->out_msg[4] = ( lifetime >> 24 ) & 0xFF;
  4224.     ssl->out_msg[5] = ( lifetime >> 16 ) & 0xFF;
  4225.     ssl->out_msg[6] = ( lifetime >>  8 ) & 0xFF;
  4226.     ssl->out_msg[7] = ( lifetime       ) & 0xFF;
  4227.  
  4228.     ssl->out_msg[8] = (unsigned char)( ( tlen >> 8 ) & 0xFF );
  4229.     ssl->out_msg[9] = (unsigned char)( ( tlen      ) & 0xFF );
  4230.  
  4231.     ssl->out_msglen = 10 + tlen;
  4232.  
  4233.     /*
  4234.      * Morally equivalent to updating ssl->state, but NewSessionTicket and
  4235.      * ChangeCipherSpec share the same state.
  4236.      */
  4237.     ssl->handshake->new_session_ticket = 0;
  4238.  
  4239.     if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
  4240.     {
  4241.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
  4242.         return( ret );
  4243.     }
  4244.  
  4245.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write new session ticket" ) );
  4246.  
  4247.     return( 0 );
  4248. }
  4249. #endif /* MBEDTLS_SSL_SESSION_TICKETS */
  4250.  
  4251. /*
  4252.  * SSL handshake -- server side -- single step
  4253.  */
  4254. int mbedtls_ssl_handshake_server_step( mbedtls_ssl_context *ssl )
  4255. {
  4256.     int ret = 0;
  4257.  
  4258.     if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER || ssl->handshake == NULL )
  4259.         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  4260.  
  4261.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "server state: %d", ssl->state ) );
  4262.  
  4263.     if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
  4264.         return( ret );
  4265.  
  4266. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4267.     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  4268.         ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING )
  4269.     {
  4270.         if( ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 )
  4271.             return( ret );
  4272.     }
  4273. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  4274.  
  4275.     switch( ssl->state )
  4276.     {
  4277.         case MBEDTLS_SSL_HELLO_REQUEST:
  4278.             ssl->state = MBEDTLS_SSL_CLIENT_HELLO;
  4279.             break;
  4280.  
  4281.         /*
  4282.          *  <==   ClientHello
  4283.          */
  4284.         case MBEDTLS_SSL_CLIENT_HELLO:
  4285.             ret = ssl_parse_client_hello( ssl );
  4286.             break;
  4287.  
  4288. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4289.         case MBEDTLS_SSL_SERVER_HELLO_VERIFY_REQUEST_SENT:
  4290.             return( MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED );
  4291. #endif
  4292.  
  4293.         /*
  4294.          *  ==>   ServerHello
  4295.          *        Certificate
  4296.          *      ( ServerKeyExchange  )
  4297.          *      ( CertificateRequest )
  4298.          *        ServerHelloDone
  4299.          */
  4300.         case MBEDTLS_SSL_SERVER_HELLO:
  4301.             ret = ssl_write_server_hello( ssl );
  4302.             break;
  4303.  
  4304.         case MBEDTLS_SSL_SERVER_CERTIFICATE:
  4305.             ret = mbedtls_ssl_write_certificate( ssl );
  4306.             break;
  4307.  
  4308.         case MBEDTLS_SSL_SERVER_KEY_EXCHANGE:
  4309.             ret = ssl_write_server_key_exchange( ssl );
  4310.             break;
  4311.  
  4312.         case MBEDTLS_SSL_CERTIFICATE_REQUEST:
  4313.             ret = ssl_write_certificate_request( ssl );
  4314.             break;
  4315.  
  4316.         case MBEDTLS_SSL_SERVER_HELLO_DONE:
  4317.             ret = ssl_write_server_hello_done( ssl );
  4318.             break;
  4319.  
  4320.         /*
  4321.          *  <== ( Certificate/Alert  )
  4322.          *        ClientKeyExchange
  4323.          *      ( CertificateVerify  )
  4324.          *        ChangeCipherSpec
  4325.          *        Finished
  4326.          */
  4327.         case MBEDTLS_SSL_CLIENT_CERTIFICATE:
  4328.             ret = mbedtls_ssl_parse_certificate( ssl );
  4329.             break;
  4330.  
  4331.         case MBEDTLS_SSL_CLIENT_KEY_EXCHANGE:
  4332.             ret = ssl_parse_client_key_exchange( ssl );
  4333.             break;
  4334.  
  4335.         case MBEDTLS_SSL_CERTIFICATE_VERIFY:
  4336.             ret = ssl_parse_certificate_verify( ssl );
  4337.             break;
  4338.  
  4339.         case MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC:
  4340.             ret = mbedtls_ssl_parse_change_cipher_spec( ssl );
  4341.             break;
  4342.  
  4343.         case MBEDTLS_SSL_CLIENT_FINISHED:
  4344.             ret = mbedtls_ssl_parse_finished( ssl );
  4345.             break;
  4346.  
  4347.         /*
  4348.          *  ==> ( NewSessionTicket )
  4349.          *        ChangeCipherSpec
  4350.          *        Finished
  4351.          */
  4352.         case MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC:
  4353. #if defined(MBEDTLS_SSL_SESSION_TICKETS)
  4354.             if( ssl->handshake->new_session_ticket != 0 )
  4355.                 ret = ssl_write_new_session_ticket( ssl );
  4356.             else
  4357. #endif
  4358.                 ret = mbedtls_ssl_write_change_cipher_spec( ssl );
  4359.             break;
  4360.  
  4361.         case MBEDTLS_SSL_SERVER_FINISHED:
  4362.             ret = mbedtls_ssl_write_finished( ssl );
  4363.             break;
  4364.  
  4365.         case MBEDTLS_SSL_FLUSH_BUFFERS:
  4366.             MBEDTLS_SSL_DEBUG_MSG( 2, ( "handshake: done" ) );
  4367.             ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
  4368.             break;
  4369.  
  4370.         case MBEDTLS_SSL_HANDSHAKE_WRAPUP:
  4371.             mbedtls_ssl_handshake_wrapup( ssl );
  4372.             break;
  4373.  
  4374.         default:
  4375.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid state %d", ssl->state ) );
  4376.             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  4377.     }
  4378.  
  4379.     return( ret );
  4380. }
  4381. #endif /* MBEDTLS_SSL_SRV_C */
  4382.