takashi kadono / Mbed OS Nucleo446_SSD1331

Dependencies:   ssd1331

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers ssl_srv.c Source File

ssl_srv.c

00001 /*
00002  *  SSLv3/TLSv1 server-side functions
00003  *
00004  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
00005  *  SPDX-License-Identifier: Apache-2.0
00006  *
00007  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
00008  *  not use this file except in compliance with the License.
00009  *  You may obtain a copy of the License at
00010  *
00011  *  http://www.apache.org/licenses/LICENSE-2.0
00012  *
00013  *  Unless required by applicable law or agreed to in writing, software
00014  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
00015  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00016  *  See the License for the specific language governing permissions and
00017  *  limitations under the License.
00018  *
00019  *  This file is part of mbed TLS (https://tls.mbed.org)
00020  */
00021 
00022 #if !defined(MBEDTLS_CONFIG_FILE)
00023 #include "mbedtls/config.h"
00024 #else
00025 #include MBEDTLS_CONFIG_FILE
00026 #endif
00027 
00028 #if defined(MBEDTLS_SSL_SRV_C)
00029 
00030 #if defined(MBEDTLS_PLATFORM_C)
00031 #include "mbedtls/platform.h"
00032 #else
00033 #include <stdlib.h>
00034 #define mbedtls_calloc    calloc
00035 #define mbedtls_free      free
00036 #endif
00037 
00038 #include "mbedtls/debug.h"
00039 #include "mbedtls/ssl.h"
00040 #include "mbedtls/ssl_internal.h"
00041 #include "mbedtls/platform_util.h"
00042 
00043 #include <string.h>
00044 
00045 #if defined(MBEDTLS_ECP_C)
00046 #include "mbedtls/ecp.h"
00047 #endif
00048 
00049 #if defined(MBEDTLS_HAVE_TIME)
00050 #include "mbedtls/platform_time.h"
00051 #endif
00052 
00053 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY)
00054 int mbedtls_ssl_set_client_transport_id( mbedtls_ssl_context *ssl,
00055                                  const unsigned char *info,
00056                                  size_t ilen )
00057 {
00058     if( ssl->conf->endpoint != MBEDTLS_SSL_IS_SERVER )
00059         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
00060 
00061     mbedtls_free( ssl->cli_id );
00062 
00063     if( ( ssl->cli_id = mbedtls_calloc( 1, ilen ) ) == NULL )
00064         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
00065 
00066     memcpy( ssl->cli_id, info, ilen );
00067     ssl->cli_id_len = ilen;
00068 
00069     return( 0 );
00070 }
00071 
00072 void mbedtls_ssl_conf_dtls_cookies( mbedtls_ssl_config *conf,
00073                            mbedtls_ssl_cookie_write_t *f_cookie_write,
00074                            mbedtls_ssl_cookie_check_t *f_cookie_check,
00075                            void *p_cookie )
00076 {
00077     conf->f_cookie_write = f_cookie_write;
00078     conf->f_cookie_check = f_cookie_check;
00079     conf->p_cookie        = p_cookie;
00080 }
00081 #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */
00082 
00083 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
00084 static int ssl_parse_servername_ext( mbedtls_ssl_context *ssl,
00085                                      const unsigned char *buf,
00086                                      size_t len )
00087 {
00088     int ret;
00089     size_t servername_list_size, hostname_len;
00090     const unsigned char *p;
00091 
00092     MBEDTLS_SSL_DEBUG_MSG( 3, ( "parse ServerName extension" ) );
00093 
00094     if( len < 2 )
00095     {
00096         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
00097         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
00098                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
00099         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
00100     }
00101     servername_list_size = ( ( buf[0] << 8 ) | ( buf[1] ) );
00102     if( servername_list_size + 2 != len )
00103     {
00104         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
00105         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
00106                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
00107         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
00108     }
00109 
00110     p = buf + 2;
00111     while( servername_list_size > 2 )
00112     {
00113         hostname_len = ( ( p[1] << 8 ) | p[2] );
00114         if( hostname_len + 3 > servername_list_size )
00115         {
00116             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
00117             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
00118                                             MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
00119             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
00120         }
00121 
00122         if( p[0] == MBEDTLS_TLS_EXT_SERVERNAME_HOSTNAME )
00123         {
00124             ret = ssl->conf->f_sni( ssl->conf->p_sni,
00125                                     ssl, p + 3, hostname_len );
00126             if( ret != 0 )
00127             {
00128                 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_sni_wrapper", ret );
00129                 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
00130                         MBEDTLS_SSL_ALERT_MSG_UNRECOGNIZED_NAME );
00131                 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
00132             }
00133             return( 0 );
00134         }
00135 
00136         servername_list_size -= hostname_len + 3;
00137         p += hostname_len + 3;
00138     }
00139 
00140     if( servername_list_size != 0 )
00141     {
00142         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
00143         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
00144                                         MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
00145         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
00146     }
00147 
00148     return( 0 );
00149 }
00150 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
00151 
00152 static int ssl_parse_renegotiation_info( mbedtls_ssl_context *ssl,
00153                                          const unsigned char *buf,
00154                                          size_t len )
00155 {
00156 #if defined(MBEDTLS_SSL_RENEGOTIATION)
00157     if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE )
00158     {
00159         /* Check verify-data in constant-time. The length OTOH is no secret */
00160         if( len    != 1 + ssl->verify_data_len ||
00161             buf[0] !=     ssl->verify_data_len ||
00162             mbedtls_ssl_safer_memcmp( buf + 1, ssl->peer_verify_data,
00163                           ssl->verify_data_len ) != 0 )
00164         {
00165             MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching renegotiation info" ) );
00166             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
00167                                             MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
00168             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
00169         }
00170     }
00171     else
00172 #endif /* MBEDTLS_SSL_RENEGOTIATION */
00173     {
00174         if( len != 1 || buf[0] != 0x0 )
00175         {
00176             MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-zero length renegotiation info" ) );
00177             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
00178                                             MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
00179             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
00180         }
00181 
00182         ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION;
00183     }
00184 
00185     return( 0 );
00186 }
00187 
00188 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
00189     defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
00190 
00191 /*
00192  * Status of the implementation of signature-algorithms extension:
00193  *
00194  * Currently, we are only considering the signature-algorithm extension
00195  * to pick a ciphersuite which allows us to send the ServerKeyExchange
00196  * message with a signature-hash combination that the user allows.
00197  *
00198  * We do *not* check whether all certificates in our certificate
00199  * chain are signed with an allowed signature-hash pair.
00200  * This needs to be done at a later stage.
00201  *
00202  */
00203 static int ssl_parse_signature_algorithms_ext( mbedtls_ssl_context *ssl,
00204                                                const unsigned char *buf,
00205                                                size_t len )
00206 {
00207     size_t sig_alg_list_size;
00208 
00209     const unsigned char *p;
00210     const unsigned char *end = buf + len;
00211 
00212     mbedtls_md_type_t md_cur;
00213     mbedtls_pk_type_t sig_cur;
00214 
00215     if ( len < 2 ) {
00216         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
00217         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
00218                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
00219         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
00220     }
00221     sig_alg_list_size = ( ( buf[0] << 8 ) | ( buf[1] ) );
00222     if( sig_alg_list_size + 2 != len ||
00223         sig_alg_list_size % 2 != 0 )
00224     {
00225         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
00226         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
00227                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
00228         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
00229     }
00230 
00231     /* Currently we only guarantee signing the ServerKeyExchange message according
00232      * to the constraints specified in this extension (see above), so it suffices
00233      * to remember only one suitable hash for each possible signature algorithm.
00234      *
00235      * This will change when we also consider certificate signatures,
00236      * in which case we will need to remember the whole signature-hash
00237      * pair list from the extension.
00238      */
00239 
00240     for( p = buf + 2; p < end; p += 2 )
00241     {
00242         /* Silently ignore unknown signature or hash algorithms. */
00243 
00244         if( ( sig_cur = mbedtls_ssl_pk_alg_from_sig( p[1] ) ) == MBEDTLS_PK_NONE )
00245         {
00246             MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext"
00247                                         " unknown sig alg encoding %d", p[1] ) );
00248             continue;
00249         }
00250 
00251         /* Check if we support the hash the user proposes */
00252         md_cur = mbedtls_ssl_md_alg_from_hash( p[0] );
00253         if( md_cur == MBEDTLS_MD_NONE )
00254         {
00255             MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext:"
00256                                         " unknown hash alg encoding %d", p[0] ) );
00257             continue;
00258         }
00259 
00260         if( mbedtls_ssl_check_sig_hash( ssl, md_cur ) == 0 )
00261         {
00262             mbedtls_ssl_sig_hash_set_add( &ssl->handshake->hash_algs, sig_cur, md_cur );
00263             MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext:"
00264                                         " match sig %d and hash %d",
00265                                         sig_cur, md_cur ) );
00266         }
00267         else
00268         {
00269             MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext: "
00270                                         "hash alg %d not supported", md_cur ) );
00271         }
00272     }
00273 
00274     return( 0 );
00275 }
00276 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&
00277           MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
00278 
00279 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
00280     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
00281 static int ssl_parse_supported_elliptic_curves( mbedtls_ssl_context *ssl,
00282                                                 const unsigned char *buf,
00283                                                 size_t len )
00284 {
00285     size_t list_size, our_size;
00286     const unsigned char *p;
00287     const mbedtls_ecp_curve_info *curve_info, **curves;
00288 
00289     if ( len < 2 ) {
00290         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
00291         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
00292                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
00293         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
00294     }
00295     list_size = ( ( buf[0] << 8 ) | ( buf[1] ) );
00296     if( list_size + 2 != len ||
00297         list_size % 2 != 0 )
00298     {
00299         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
00300         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
00301                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
00302         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
00303     }
00304 
00305     /* Should never happen unless client duplicates the extension */
00306     if( ssl->handshake->curves != NULL )
00307     {
00308         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
00309         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
00310                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
00311         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
00312     }
00313 
00314     /* Don't allow our peer to make us allocate too much memory,
00315      * and leave room for a final 0 */
00316     our_size = list_size / 2 + 1;
00317     if( our_size > MBEDTLS_ECP_DP_MAX )
00318         our_size = MBEDTLS_ECP_DP_MAX;
00319 
00320     if( ( curves = mbedtls_calloc( our_size, sizeof( *curves ) ) ) == NULL )
00321     {
00322         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
00323                                         MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
00324         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
00325     }
00326 
00327     ssl->handshake->curves = curves;
00328 
00329     p = buf + 2;
00330     while( list_size > 0 && our_size > 1 )
00331     {
00332         curve_info = mbedtls_ecp_curve_info_from_tls_id( ( p[0] << 8 ) | p[1] );
00333 
00334         if( curve_info != NULL )
00335         {
00336             *curves++ = curve_info;
00337             our_size--;
00338         }
00339 
00340         list_size -= 2;
00341         p += 2;
00342     }
00343 
00344     return( 0 );
00345 }
00346 
00347 static int ssl_parse_supported_point_formats( mbedtls_ssl_context *ssl,
00348                                               const unsigned char *buf,
00349                                               size_t len )
00350 {
00351     size_t list_size;
00352     const unsigned char *p;
00353 
00354     if( len == 0 || (size_t)( buf[0] + 1 ) != len )
00355     {
00356         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
00357         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
00358                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
00359         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
00360     }
00361     list_size = buf[0];
00362 
00363     p = buf + 1;
00364     while( list_size > 0 )
00365     {
00366         if( p[0] == MBEDTLS_ECP_PF_UNCOMPRESSED ||
00367             p[0] == MBEDTLS_ECP_PF_COMPRESSED )
00368         {
00369 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C)
00370             ssl->handshake->ecdh_ctx.point_format = p[0];
00371 #endif
00372 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
00373             ssl->handshake->ecjpake_ctx.point_format = p[0];
00374 #endif
00375             MBEDTLS_SSL_DEBUG_MSG( 4, ( "point format selected: %d", p[0] ) );
00376             return( 0 );
00377         }
00378 
00379         list_size--;
00380         p++;
00381     }
00382 
00383     return( 0 );
00384 }
00385 #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
00386           MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
00387 
00388 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
00389 static int ssl_parse_ecjpake_kkpp( mbedtls_ssl_context *ssl,
00390                                    const unsigned char *buf,
00391                                    size_t len )
00392 {
00393     int ret;
00394 
00395     if( mbedtls_ecjpake_check( &ssl->handshake->ecjpake_ctx ) != 0 )
00396     {
00397         MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip ecjpake kkpp extension" ) );
00398         return( 0 );
00399     }
00400 
00401     if( ( ret = mbedtls_ecjpake_read_round_one( &ssl->handshake->ecjpake_ctx,
00402                                                 buf, len ) ) != 0 )
00403     {
00404         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_one", ret );
00405         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
00406                                         MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
00407         return( ret );
00408     }
00409 
00410     /* Only mark the extension as OK when we're sure it is */
00411     ssl->handshake->cli_exts |= MBEDTLS_TLS_EXT_ECJPAKE_KKPP_OK;
00412 
00413     return( 0 );
00414 }
00415 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
00416 
00417 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
00418 static int ssl_parse_max_fragment_length_ext( mbedtls_ssl_context *ssl,
00419                                               const unsigned char *buf,
00420                                               size_t len )
00421 {
00422     if( len != 1 || buf[0] >= MBEDTLS_SSL_MAX_FRAG_LEN_INVALID )
00423     {
00424         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
00425         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
00426                                         MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
00427         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
00428     }
00429 
00430     ssl->session_negotiate->mfl_code = buf[0];
00431 
00432     return( 0 );
00433 }
00434 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
00435 
00436 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
00437 static int ssl_parse_truncated_hmac_ext( mbedtls_ssl_context *ssl,
00438                                          const unsigned char *buf,
00439                                          size_t len )
00440 {
00441     if( len != 0 )
00442     {
00443         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
00444         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
00445                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
00446         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
00447     }
00448 
00449     ((void) buf);
00450 
00451     if( ssl->conf->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_ENABLED )
00452         ssl->session_negotiate->trunc_hmac = MBEDTLS_SSL_TRUNC_HMAC_ENABLED;
00453 
00454     return( 0 );
00455 }
00456 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
00457 
00458 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
00459 static int ssl_parse_encrypt_then_mac_ext( mbedtls_ssl_context *ssl,
00460                                       const unsigned char *buf,
00461                                       size_t len )
00462 {
00463     if( len != 0 )
00464     {
00465         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
00466         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
00467                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
00468         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
00469     }
00470 
00471     ((void) buf);
00472 
00473     if( ssl->conf->encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED &&
00474         ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_0 )
00475     {
00476         ssl->session_negotiate->encrypt_then_mac = MBEDTLS_SSL_ETM_ENABLED;
00477     }
00478 
00479     return( 0 );
00480 }
00481 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
00482 
00483 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
00484 static int ssl_parse_extended_ms_ext( mbedtls_ssl_context *ssl,
00485                                       const unsigned char *buf,
00486                                       size_t len )
00487 {
00488     if( len != 0 )
00489     {
00490         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
00491         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
00492                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
00493         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
00494     }
00495 
00496     ((void) buf);
00497 
00498     if( ssl->conf->extended_ms == MBEDTLS_SSL_EXTENDED_MS_ENABLED &&
00499         ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_0 )
00500     {
00501         ssl->handshake->extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED;
00502     }
00503 
00504     return( 0 );
00505 }
00506 #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
00507 
00508 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
00509 static int ssl_parse_session_ticket_ext( mbedtls_ssl_context *ssl,
00510                                          unsigned char *buf,
00511                                          size_t len )
00512 {
00513     int ret;
00514     mbedtls_ssl_session session;
00515 
00516     mbedtls_ssl_session_init( &session );
00517 
00518     if( ssl->conf->f_ticket_parse == NULL ||
00519         ssl->conf->f_ticket_write == NULL )
00520     {
00521         return( 0 );
00522     }
00523 
00524     /* Remember the client asked us to send a new ticket */
00525     ssl->handshake->new_session_ticket = 1;
00526 
00527     MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket length: %d", len ) );
00528 
00529     if( len == 0 )
00530         return( 0 );
00531 
00532 #if defined(MBEDTLS_SSL_RENEGOTIATION)
00533     if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE )
00534     {
00535         MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket rejected: renegotiating" ) );
00536         return( 0 );
00537     }
00538 #endif /* MBEDTLS_SSL_RENEGOTIATION */
00539 
00540     /*
00541      * Failures are ok: just ignore the ticket and proceed.
00542      */
00543     if( ( ret = ssl->conf->f_ticket_parse( ssl->conf->p_ticket, &session,
00544                                            buf, len ) ) != 0 )
00545     {
00546         mbedtls_ssl_session_free( &session );
00547 
00548         if( ret == MBEDTLS_ERR_SSL_INVALID_MAC )
00549             MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket is not authentic" ) );
00550         else if( ret == MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED )
00551             MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket is expired" ) );
00552         else
00553             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_ticket_parse", ret );
00554 
00555         return( 0 );
00556     }
00557 
00558     /*
00559      * Keep the session ID sent by the client, since we MUST send it back to
00560      * inform them we're accepting the ticket  (RFC 5077 section 3.4)
00561      */
00562     session.id_len = ssl->session_negotiate->id_len;
00563     memcpy( &session.id, ssl->session_negotiate->id, session.id_len );
00564 
00565     mbedtls_ssl_session_free( ssl->session_negotiate );
00566     memcpy( ssl->session_negotiate, &session, sizeof( mbedtls_ssl_session ) );
00567 
00568     /* Zeroize instead of free as we copied the content */
00569     mbedtls_platform_zeroize( &session, sizeof( mbedtls_ssl_session ) );
00570 
00571     MBEDTLS_SSL_DEBUG_MSG( 3, ( "session successfully restored from ticket" ) );
00572 
00573     ssl->handshake->resume = 1;
00574 
00575     /* Don't send a new ticket after all, this one is OK */
00576     ssl->handshake->new_session_ticket = 0;
00577 
00578     return( 0 );
00579 }
00580 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
00581 
00582 #if defined(MBEDTLS_SSL_ALPN)
00583 static int ssl_parse_alpn_ext( mbedtls_ssl_context *ssl,
00584                                const unsigned char *buf, size_t len )
00585 {
00586     size_t list_len, cur_len, ours_len;
00587     const unsigned char *theirs, *start, *end;
00588     const char **ours;
00589 
00590     /* If ALPN not configured, just ignore the extension */
00591     if( ssl->conf->alpn_list == NULL )
00592         return( 0 );
00593 
00594     /*
00595      * opaque ProtocolName<1..2^8-1>;
00596      *
00597      * struct {
00598      *     ProtocolName protocol_name_list<2..2^16-1>
00599      * } ProtocolNameList;
00600      */
00601 
00602     /* Min length is 2 (list_len) + 1 (name_len) + 1 (name) */
00603     if( len < 4 )
00604     {
00605         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
00606                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
00607         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
00608     }
00609 
00610     list_len = ( buf[0] << 8 ) | buf[1];
00611     if( list_len != len - 2 )
00612     {
00613         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
00614                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
00615         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
00616     }
00617 
00618     /*
00619      * Validate peer's list (lengths)
00620      */
00621     start = buf + 2;
00622     end = buf + len;
00623     for( theirs = start; theirs != end; theirs += cur_len )
00624     {
00625         cur_len = *theirs++;
00626 
00627         /* Current identifier must fit in list */
00628         if( cur_len > (size_t)( end - theirs ) )
00629         {
00630             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
00631                                             MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
00632             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
00633         }
00634 
00635         /* Empty strings MUST NOT be included */
00636         if( cur_len == 0 )
00637         {
00638             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
00639                                             MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
00640             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
00641         }
00642     }
00643 
00644     /*
00645      * Use our order of preference
00646      */
00647     for( ours = ssl->conf->alpn_list; *ours != NULL; ours++ )
00648     {
00649         ours_len = strlen( *ours );
00650         for( theirs = start; theirs != end; theirs += cur_len )
00651         {
00652             cur_len = *theirs++;
00653 
00654             if( cur_len == ours_len &&
00655                 memcmp( theirs, *ours, cur_len ) == 0 )
00656             {
00657                 ssl->alpn_chosen = *ours;
00658                 return( 0 );
00659             }
00660         }
00661     }
00662 
00663     /* If we get there, no match was found */
00664     mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
00665                             MBEDTLS_SSL_ALERT_MSG_NO_APPLICATION_PROTOCOL );
00666     return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
00667 }
00668 #endif /* MBEDTLS_SSL_ALPN */
00669 
00670 /*
00671  * Auxiliary functions for ServerHello parsing and related actions
00672  */
00673 
00674 #if defined(MBEDTLS_X509_CRT_PARSE_C)
00675 /*
00676  * Return 0 if the given key uses one of the acceptable curves, -1 otherwise
00677  */
00678 #if defined(MBEDTLS_ECDSA_C)
00679 static int ssl_check_key_curve( mbedtls_pk_context *pk,
00680                                 const mbedtls_ecp_curve_info **curves )
00681 {
00682     const mbedtls_ecp_curve_info **crv = curves;
00683     mbedtls_ecp_group_id grp_id = mbedtls_pk_ec( *pk )->grp .id ;
00684 
00685     while( *crv != NULL )
00686     {
00687         if( (*crv)->grp_id == grp_id )
00688             return( 0 );
00689         crv++;
00690     }
00691 
00692     return( -1 );
00693 }
00694 #endif /* MBEDTLS_ECDSA_C */
00695 
00696 /*
00697  * Try picking a certificate for this ciphersuite,
00698  * return 0 on success and -1 on failure.
00699  */
00700 static int ssl_pick_cert( mbedtls_ssl_context *ssl,
00701                           const mbedtls_ssl_ciphersuite_t * ciphersuite_info )
00702 {
00703     mbedtls_ssl_key_cert *cur, *list, *fallback = NULL;
00704     mbedtls_pk_type_t pk_alg =
00705         mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info );
00706     uint32_t flags;
00707 
00708 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
00709     if( ssl->handshake->sni_key_cert != NULL )
00710         list = ssl->handshake->sni_key_cert;
00711     else
00712 #endif
00713         list = ssl->conf->key_cert;
00714 
00715     if( pk_alg == MBEDTLS_PK_NONE )
00716         return( 0 );
00717 
00718     MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite requires certificate" ) );
00719 
00720     if( list == NULL )
00721     {
00722         MBEDTLS_SSL_DEBUG_MSG( 3, ( "server has no certificate" ) );
00723         return( -1 );
00724     }
00725 
00726     for( cur = list; cur != NULL; cur = cur->next )
00727     {
00728         MBEDTLS_SSL_DEBUG_CRT( 3, "candidate certificate chain, certificate",
00729                           cur->cert );
00730 
00731         if( ! mbedtls_pk_can_do( &cur->cert->pk, pk_alg ) )
00732         {
00733             MBEDTLS_SSL_DEBUG_MSG( 3, ( "certificate mismatch: key type" ) );
00734             continue;
00735         }
00736 
00737         /*
00738          * This avoids sending the client a cert it'll reject based on
00739          * keyUsage or other extensions.
00740          *
00741          * It also allows the user to provision different certificates for
00742          * different uses based on keyUsage, eg if they want to avoid signing
00743          * and decrypting with the same RSA key.
00744          */
00745         if( mbedtls_ssl_check_cert_usage( cur->cert, ciphersuite_info,
00746                                   MBEDTLS_SSL_IS_SERVER, &flags ) != 0 )
00747         {
00748             MBEDTLS_SSL_DEBUG_MSG( 3, ( "certificate mismatch: "
00749                                 "(extended) key usage extension" ) );
00750             continue;
00751         }
00752 
00753 #if defined(MBEDTLS_ECDSA_C)
00754         if( pk_alg == MBEDTLS_PK_ECDSA &&
00755             ssl_check_key_curve( &cur->cert->pk, ssl->handshake->curves ) != 0 )
00756         {
00757             MBEDTLS_SSL_DEBUG_MSG( 3, ( "certificate mismatch: elliptic curve" ) );
00758             continue;
00759         }
00760 #endif
00761 
00762         /*
00763          * Try to select a SHA-1 certificate for pre-1.2 clients, but still
00764          * present them a SHA-higher cert rather than failing if it's the only
00765          * one we got that satisfies the other conditions.
00766          */
00767         if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 &&
00768             cur->cert->sig_md != MBEDTLS_MD_SHA1 )
00769         {
00770             if( fallback == NULL )
00771                 fallback = cur;
00772             {
00773                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "certificate not preferred: "
00774                                     "sha-2 with pre-TLS 1.2 client" ) );
00775             continue;
00776             }
00777         }
00778 
00779         /* If we get there, we got a winner */
00780         break;
00781     }
00782 
00783     if( cur == NULL )
00784         cur = fallback;
00785 
00786     /* Do not update ssl->handshake->key_cert unless there is a match */
00787     if( cur != NULL )
00788     {
00789         ssl->handshake->key_cert = cur;
00790         MBEDTLS_SSL_DEBUG_CRT( 3, "selected certificate chain, certificate",
00791                           ssl->handshake->key_cert->cert );
00792         return( 0 );
00793     }
00794 
00795     return( -1 );
00796 }
00797 #endif /* MBEDTLS_X509_CRT_PARSE_C */
00798 
00799 /*
00800  * Check if a given ciphersuite is suitable for use with our config/keys/etc
00801  * Sets ciphersuite_info only if the suite matches.
00802  */
00803 static int ssl_ciphersuite_match( mbedtls_ssl_context *ssl, int suite_id,
00804                                   const mbedtls_ssl_ciphersuite_t **ciphersuite_info )
00805 {
00806     const mbedtls_ssl_ciphersuite_t *suite_info;
00807 
00808 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
00809     defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
00810     mbedtls_pk_type_t sig_type;
00811 #endif
00812 
00813     suite_info = mbedtls_ssl_ciphersuite_from_id( suite_id );
00814     if( suite_info == NULL )
00815     {
00816         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
00817         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
00818     }
00819 
00820     MBEDTLS_SSL_DEBUG_MSG( 3, ( "trying ciphersuite: %s", suite_info->name ) );
00821 
00822     if( suite_info->min_minor_ver > ssl->minor_ver ||
00823         suite_info->max_minor_ver < ssl->minor_ver )
00824     {
00825         MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: version" ) );
00826         return( 0 );
00827     }
00828 
00829 #if defined(MBEDTLS_SSL_PROTO_DTLS)
00830     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
00831         ( suite_info->flags & MBEDTLS_CIPHERSUITE_NODTLS ) )
00832         return( 0 );
00833 #endif
00834 
00835 #if defined(MBEDTLS_ARC4_C)
00836     if( ssl->conf->arc4_disabled == MBEDTLS_SSL_ARC4_DISABLED &&
00837             suite_info->cipher == MBEDTLS_CIPHER_ARC4_128 )
00838     {
00839         MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: rc4" ) );
00840         return( 0 );
00841     }
00842 #endif
00843 
00844 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
00845     if( suite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE &&
00846         ( ssl->handshake->cli_exts & MBEDTLS_TLS_EXT_ECJPAKE_KKPP_OK ) == 0 )
00847     {
00848         MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: ecjpake "
00849                                     "not configured or ext missing" ) );
00850         return( 0 );
00851     }
00852 #endif
00853 
00854 
00855 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C)
00856     if( mbedtls_ssl_ciphersuite_uses_ec( suite_info ) &&
00857         ( ssl->handshake->curves == NULL ||
00858           ssl->handshake->curves[0] == NULL ) )
00859     {
00860         MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: "
00861                             "no common elliptic curve" ) );
00862         return( 0 );
00863     }
00864 #endif
00865 
00866 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
00867     /* If the ciphersuite requires a pre-shared key and we don't
00868      * have one, skip it now rather than failing later */
00869     if( mbedtls_ssl_ciphersuite_uses_psk( suite_info ) &&
00870         ssl->conf->f_psk == NULL &&
00871         ( ssl->conf->psk == NULL || ssl->conf->psk_identity == NULL ||
00872           ssl->conf->psk_identity_len == 0 || ssl->conf->psk_len == 0 ) )
00873     {
00874         MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: no pre-shared key" ) );
00875         return( 0 );
00876     }
00877 #endif
00878 
00879 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
00880     defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
00881     /* If the ciphersuite requires signing, check whether
00882      * a suitable hash algorithm is present. */
00883     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
00884     {
00885         sig_type = mbedtls_ssl_get_ciphersuite_sig_alg( suite_info );
00886         if( sig_type != MBEDTLS_PK_NONE &&
00887             mbedtls_ssl_sig_hash_set_find( &ssl->handshake->hash_algs, sig_type ) == MBEDTLS_MD_NONE )
00888         {
00889             MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: no suitable hash algorithm "
00890                                         "for signature algorithm %d", sig_type ) );
00891             return( 0 );
00892         }
00893     }
00894 
00895 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&
00896           MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
00897 
00898 #if defined(MBEDTLS_X509_CRT_PARSE_C)
00899     /*
00900      * Final check: if ciphersuite requires us to have a
00901      * certificate/key of a particular type:
00902      * - select the appropriate certificate if we have one, or
00903      * - try the next ciphersuite if we don't
00904      * This must be done last since we modify the key_cert list.
00905      */
00906     if( ssl_pick_cert( ssl, suite_info ) != 0 )
00907     {
00908         MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: "
00909                             "no suitable certificate" ) );
00910         return( 0 );
00911     }
00912 #endif
00913 
00914     *ciphersuite_info = suite_info;
00915     return( 0 );
00916 }
00917 
00918 #if defined(MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO)
00919 static int ssl_parse_client_hello_v2( mbedtls_ssl_context *ssl )
00920 {
00921     int ret, got_common_suite;
00922     unsigned int i, j;
00923     size_t n;
00924     unsigned int ciph_len, sess_len, chal_len;
00925     unsigned char *buf, *p;
00926     const int *ciphersuites;
00927     const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
00928 
00929     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse client hello v2" ) );
00930 
00931 #if defined(MBEDTLS_SSL_RENEGOTIATION)
00932     if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE )
00933     {
00934         MBEDTLS_SSL_DEBUG_MSG( 1, ( "client hello v2 illegal for renegotiation" ) );
00935         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
00936                                         MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
00937         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
00938     }
00939 #endif /* MBEDTLS_SSL_RENEGOTIATION */
00940 
00941     buf = ssl->in_hdr;
00942 
00943     MBEDTLS_SSL_DEBUG_BUF( 4, "record header", buf, 5 );
00944 
00945     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v2, message type: %d",
00946                    buf[2] ) );
00947     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v2, message len.: %d",
00948                    ( ( buf[0] & 0x7F ) << 8 ) | buf[1] ) );
00949     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v2, max. version: [%d:%d]",
00950                    buf[3], buf[4] ) );
00951 
00952     /*
00953      * SSLv2 Client Hello
00954      *
00955      * Record layer:
00956      *     0  .   1   message length
00957      *
00958      * SSL layer:
00959      *     2  .   2   message type
00960      *     3  .   4   protocol version
00961      */
00962     if( buf[2] != MBEDTLS_SSL_HS_CLIENT_HELLO ||
00963         buf[3] != MBEDTLS_SSL_MAJOR_VERSION_3 )
00964     {
00965         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
00966         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
00967     }
00968 
00969     n = ( ( buf[0] << 8 ) | buf[1] ) & 0x7FFF;
00970 
00971     if( n < 17 || n > 512 )
00972     {
00973         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
00974         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
00975     }
00976 
00977     ssl->major_ver = MBEDTLS_SSL_MAJOR_VERSION_3;
00978     ssl->minor_ver = ( buf[4] <= ssl->conf->max_minor_ver )
00979                      ? buf[4]  : ssl->conf->max_minor_ver;
00980 
00981     if( ssl->minor_ver < ssl->conf->min_minor_ver )
00982     {
00983         MBEDTLS_SSL_DEBUG_MSG( 1, ( "client only supports ssl smaller than minimum"
00984                             " [%d:%d] < [%d:%d]",
00985                             ssl->major_ver, ssl->minor_ver,
00986                             ssl->conf->min_major_ver, ssl->conf->min_minor_ver ) );
00987 
00988         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
00989                                      MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION );
00990         return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION );
00991     }
00992 
00993     ssl->handshake->max_major_ver = buf[3];
00994     ssl->handshake->max_minor_ver = buf[4];
00995 
00996     if( ( ret = mbedtls_ssl_fetch_input( ssl, 2 + n ) ) != 0 )
00997     {
00998         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret );
00999         return( ret );
01000     }
01001 
01002     ssl->handshake->update_checksum( ssl, buf + 2, n );
01003 
01004     buf = ssl->in_msg;
01005     n = ssl->in_left - 5;
01006 
01007     /*
01008      *    0  .   1   ciphersuitelist length
01009      *    2  .   3   session id length
01010      *    4  .   5   challenge length
01011      *    6  .  ..   ciphersuitelist
01012      *   ..  .  ..   session id
01013      *   ..  .  ..   challenge
01014      */
01015     MBEDTLS_SSL_DEBUG_BUF( 4, "record contents", buf, n );
01016 
01017     ciph_len = ( buf[0] << 8 ) | buf[1];
01018     sess_len = ( buf[2] << 8 ) | buf[3];
01019     chal_len = ( buf[4] << 8 ) | buf[5];
01020 
01021     MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciph_len: %d, sess_len: %d, chal_len: %d",
01022                    ciph_len, sess_len, chal_len ) );
01023 
01024     /*
01025      * Make sure each parameter length is valid
01026      */
01027     if( ciph_len < 3 || ( ciph_len % 3 ) != 0 )
01028     {
01029         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
01030         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
01031     }
01032 
01033     if( sess_len > 32 )
01034     {
01035         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
01036         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
01037     }
01038 
01039     if( chal_len < 8 || chal_len > 32 )
01040     {
01041         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
01042         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
01043     }
01044 
01045     if( n != 6 + ciph_len + sess_len + chal_len )
01046     {
01047         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
01048         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
01049     }
01050 
01051     MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, ciphersuitelist",
01052                    buf + 6, ciph_len );
01053     MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, session id",
01054                    buf + 6 + ciph_len, sess_len );
01055     MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, challenge",
01056                    buf + 6 + ciph_len + sess_len, chal_len );
01057 
01058     p = buf + 6 + ciph_len;
01059     ssl->session_negotiate->id_len = sess_len;
01060     memset( ssl->session_negotiate->id, 0,
01061             sizeof( ssl->session_negotiate->id ) );
01062     memcpy( ssl->session_negotiate->id, p, ssl->session_negotiate->id_len );
01063 
01064     p += sess_len;
01065     memset( ssl->handshake->randbytes, 0, 64 );
01066     memcpy( ssl->handshake->randbytes + 32 - chal_len, p, chal_len );
01067 
01068     /*
01069      * Check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV
01070      */
01071     for( i = 0, p = buf + 6; i < ciph_len; i += 3, p += 3 )
01072     {
01073         if( p[0] == 0 && p[1] == 0 && p[2] == MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO )
01074         {
01075             MBEDTLS_SSL_DEBUG_MSG( 3, ( "received TLS_EMPTY_RENEGOTIATION_INFO " ) );
01076 #if defined(MBEDTLS_SSL_RENEGOTIATION)
01077             if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
01078             {
01079                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "received RENEGOTIATION SCSV "
01080                                     "during renegotiation" ) );
01081 
01082                 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
01083                                                 MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
01084                 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
01085             }
01086 #endif /* MBEDTLS_SSL_RENEGOTIATION */
01087             ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION;
01088             break;
01089         }
01090     }
01091 
01092 #if defined(MBEDTLS_SSL_FALLBACK_SCSV)
01093     for( i = 0, p = buf + 6; i < ciph_len; i += 3, p += 3 )
01094     {
01095         if( p[0] == 0 &&
01096             p[1] == (unsigned char)( ( MBEDTLS_SSL_FALLBACK_SCSV_VALUE >> 8 ) & 0xff ) &&
01097             p[2] == (unsigned char)( ( MBEDTLS_SSL_FALLBACK_SCSV_VALUE      ) & 0xff ) )
01098         {
01099             MBEDTLS_SSL_DEBUG_MSG( 3, ( "received FALLBACK_SCSV" ) );
01100 
01101             if( ssl->minor_ver < ssl->conf->max_minor_ver )
01102             {
01103                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "inapropriate fallback" ) );
01104 
01105                 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
01106                                         MBEDTLS_SSL_ALERT_MSG_INAPROPRIATE_FALLBACK );
01107 
01108                 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
01109             }
01110 
01111             break;
01112         }
01113     }
01114 #endif /* MBEDTLS_SSL_FALLBACK_SCSV */
01115 
01116     got_common_suite = 0;
01117     ciphersuites = ssl->conf->ciphersuite_list[ssl->minor_ver];
01118     ciphersuite_info = NULL;
01119 #if defined(MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE)
01120     for( j = 0, p = buf + 6; j < ciph_len; j += 3, p += 3 )
01121         for( i = 0; ciphersuites[i] != 0; i++ )
01122 #else
01123     for( i = 0; ciphersuites[i] != 0; i++ )
01124         for( j = 0, p = buf + 6; j < ciph_len; j += 3, p += 3 )
01125 #endif
01126         {
01127             if( p[0] != 0 ||
01128                 p[1] != ( ( ciphersuites[i] >> 8 ) & 0xFF ) ||
01129                 p[2] != ( ( ciphersuites[i]      ) & 0xFF ) )
01130                 continue;
01131 
01132             got_common_suite = 1;
01133 
01134             if( ( ret = ssl_ciphersuite_match( ssl, ciphersuites[i],
01135                                                &ciphersuite_info ) ) != 0 )
01136                 return( ret );
01137 
01138             if( ciphersuite_info != NULL )
01139                 goto have_ciphersuite_v2;
01140         }
01141 
01142     if( got_common_suite )
01143     {
01144         MBEDTLS_SSL_DEBUG_MSG( 1, ( "got ciphersuites in common, "
01145                             "but none of them usable" ) );
01146         return( MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE );
01147     }
01148     else
01149     {
01150         MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no ciphersuites in common" ) );
01151         return( MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN );
01152     }
01153 
01154 have_ciphersuite_v2:
01155     MBEDTLS_SSL_DEBUG_MSG( 2, ( "selected ciphersuite: %s", ciphersuite_info->name ) );
01156 
01157     ssl->session_negotiate->ciphersuite = ciphersuites[i];
01158     ssl->transform_negotiate->ciphersuite_info = ciphersuite_info;
01159 
01160     /*
01161      * SSLv2 Client Hello relevant renegotiation security checks
01162      */
01163     if( ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
01164         ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE )
01165     {
01166         MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation, breaking off handshake" ) );
01167         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
01168                                         MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
01169         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
01170     }
01171 
01172     ssl->in_left = 0;
01173     ssl->state++;
01174 
01175     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse client hello v2" ) );
01176 
01177     return( 0 );
01178 }
01179 #endif /* MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO */
01180 
01181 /* This function doesn't alert on errors that happen early during
01182    ClientHello parsing because they might indicate that the client is
01183    not talking SSL/TLS at all and would not understand our alert. */
01184 static int ssl_parse_client_hello( mbedtls_ssl_context *ssl )
01185 {
01186     int ret, got_common_suite;
01187     size_t i, j;
01188     size_t ciph_offset, comp_offset, ext_offset;
01189     size_t msg_len, ciph_len, sess_len, comp_len, ext_len;
01190 #if defined(MBEDTLS_SSL_PROTO_DTLS)
01191     size_t cookie_offset, cookie_len;
01192 #endif
01193     unsigned char *buf, *p, *ext;
01194 #if defined(MBEDTLS_SSL_RENEGOTIATION)
01195     int renegotiation_info_seen = 0;
01196 #endif
01197     int handshake_failure = 0;
01198     const int *ciphersuites;
01199     const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
01200     int major, minor;
01201 
01202     /* If there is no signature-algorithm extension present,
01203      * we need to fall back to the default values for allowed
01204      * signature-hash pairs. */
01205 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
01206     defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
01207     int sig_hash_alg_ext_present = 0;
01208 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&
01209           MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
01210 
01211     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse client hello" ) );
01212 
01213 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
01214 read_record_header:
01215 #endif
01216     /*
01217      * If renegotiating, then the input was read with mbedtls_ssl_read_record(),
01218      * otherwise read it ourselves manually in order to support SSLv2
01219      * ClientHello, which doesn't use the same record layer format.
01220      */
01221 #if defined(MBEDTLS_SSL_RENEGOTIATION)
01222     if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE )
01223 #endif
01224     {
01225         if( ( ret = mbedtls_ssl_fetch_input( ssl, 5 ) ) != 0 )
01226         {
01227             /* No alert on a read error. */
01228             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret );
01229             return( ret );
01230         }
01231     }
01232 
01233     buf = ssl->in_hdr;
01234 
01235 #if defined(MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO)
01236 #if defined(MBEDTLS_SSL_PROTO_DTLS)
01237     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_STREAM )
01238 #endif
01239         if( ( buf[0] & 0x80 ) != 0 )
01240             return( ssl_parse_client_hello_v2( ssl ) );
01241 #endif
01242 
01243     MBEDTLS_SSL_DEBUG_BUF( 4, "record header", buf, mbedtls_ssl_hdr_len( ssl ) );
01244 
01245     /*
01246      * SSLv3/TLS Client Hello
01247      *
01248      * Record layer:
01249      *     0  .   0   message type
01250      *     1  .   2   protocol version
01251      *     3  .   11  DTLS: epoch + record sequence number
01252      *     3  .   4   message length
01253      */
01254     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, message type: %d",
01255                    buf[0] ) );
01256 
01257     if( buf[0] != MBEDTLS_SSL_MSG_HANDSHAKE )
01258     {
01259         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
01260         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
01261     }
01262 
01263     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, message len.: %d",
01264                    ( ssl->in_len[0] << 8 ) | ssl->in_len[1] ) );
01265 
01266     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, protocol version: [%d:%d]",
01267                    buf[1], buf[2] ) );
01268 
01269     mbedtls_ssl_read_version( &major, &minor, ssl->conf->transport, buf + 1 );
01270 
01271     /* According to RFC 5246 Appendix E.1, the version here is typically
01272      * "{03,00}, the lowest version number supported by the client, [or] the
01273      * value of ClientHello.client_version", so the only meaningful check here
01274      * is the major version shouldn't be less than 3 */
01275     if( major < MBEDTLS_SSL_MAJOR_VERSION_3 )
01276     {
01277         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
01278         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
01279     }
01280 
01281     /* For DTLS if this is the initial handshake, remember the client sequence
01282      * number to use it in our next message (RFC 6347 4.2.1) */
01283 #if defined(MBEDTLS_SSL_PROTO_DTLS)
01284     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM
01285 #if defined(MBEDTLS_SSL_RENEGOTIATION)
01286         && ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE
01287 #endif
01288         )
01289     {
01290         /* Epoch should be 0 for initial handshakes */
01291         if( ssl->in_ctr[0] != 0 || ssl->in_ctr[1] != 0 )
01292         {
01293             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
01294             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
01295         }
01296 
01297         memcpy( ssl->cur_out_ctr + 2, ssl->in_ctr + 2, 6 );
01298 
01299 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
01300         if( mbedtls_ssl_dtls_replay_check( ssl ) != 0 )
01301         {
01302             MBEDTLS_SSL_DEBUG_MSG( 1, ( "replayed record, discarding" ) );
01303             ssl->next_record_offset = 0;
01304             ssl->in_left = 0;
01305             goto read_record_header;
01306         }
01307 
01308         /* No MAC to check yet, so we can update right now */
01309         mbedtls_ssl_dtls_replay_update( ssl );
01310 #endif
01311     }
01312 #endif /* MBEDTLS_SSL_PROTO_DTLS */
01313 
01314     msg_len = ( ssl->in_len[0] << 8 ) | ssl->in_len[1];
01315 
01316 #if defined(MBEDTLS_SSL_RENEGOTIATION)
01317     if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE )
01318     {
01319         /* Set by mbedtls_ssl_read_record() */
01320         msg_len = ssl->in_hslen;
01321     }
01322     else
01323 #endif
01324     {
01325         if( msg_len > MBEDTLS_SSL_IN_CONTENT_LEN )
01326         {
01327             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
01328             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
01329         }
01330 
01331         if( ( ret = mbedtls_ssl_fetch_input( ssl,
01332                        mbedtls_ssl_hdr_len( ssl ) + msg_len ) ) != 0 )
01333         {
01334             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret );
01335             return( ret );
01336         }
01337 
01338     /* Done reading this record, get ready for the next one */
01339 #if defined(MBEDTLS_SSL_PROTO_DTLS)
01340         if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
01341             ssl->next_record_offset = msg_len + mbedtls_ssl_hdr_len( ssl );
01342         else
01343 #endif
01344             ssl->in_left = 0;
01345     }
01346 
01347     buf = ssl->in_msg;
01348 
01349     MBEDTLS_SSL_DEBUG_BUF( 4, "record contents", buf, msg_len );
01350 
01351     ssl->handshake->update_checksum( ssl, buf, msg_len );
01352 
01353     /*
01354      * Handshake layer:
01355      *     0  .   0   handshake type
01356      *     1  .   3   handshake length
01357      *     4  .   5   DTLS only: message seqence number
01358      *     6  .   8   DTLS only: fragment offset
01359      *     9  .  11   DTLS only: fragment length
01360      */
01361     if( msg_len < mbedtls_ssl_hs_hdr_len( ssl ) )
01362     {
01363         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
01364         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
01365     }
01366 
01367     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, handshake type: %d", buf[0] ) );
01368 
01369     if( buf[0] != MBEDTLS_SSL_HS_CLIENT_HELLO )
01370     {
01371         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
01372         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
01373     }
01374 
01375     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, handshake len.: %d",
01376                    ( buf[1] << 16 ) | ( buf[2] << 8 ) | buf[3] ) );
01377 
01378     /* We don't support fragmentation of ClientHello (yet?) */
01379     if( buf[1] != 0 ||
01380         msg_len != mbedtls_ssl_hs_hdr_len( ssl ) + ( ( buf[2] << 8 ) | buf[3] ) )
01381     {
01382         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
01383         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
01384     }
01385 
01386 #if defined(MBEDTLS_SSL_PROTO_DTLS)
01387     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
01388     {
01389         /*
01390          * Copy the client's handshake message_seq on initial handshakes,
01391          * check sequence number on renego.
01392          */
01393 #if defined(MBEDTLS_SSL_RENEGOTIATION)
01394         if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
01395         {
01396             /* This couldn't be done in ssl_prepare_handshake_record() */
01397             unsigned int cli_msg_seq = ( ssl->in_msg[4] << 8 ) |
01398                                          ssl->in_msg[5];
01399 
01400             if( cli_msg_seq != ssl->handshake->in_msg_seq )
01401             {
01402                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message_seq: "
01403                                     "%d (expected %d)", cli_msg_seq,
01404                                     ssl->handshake->in_msg_seq ) );
01405                 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
01406             }
01407 
01408             ssl->handshake->in_msg_seq++;
01409         }
01410         else
01411 #endif
01412         {
01413             unsigned int cli_msg_seq = ( ssl->in_msg[4] << 8 ) |
01414                                          ssl->in_msg[5];
01415             ssl->handshake->out_msg_seq = cli_msg_seq;
01416             ssl->handshake->in_msg_seq  = cli_msg_seq + 1;
01417         }
01418 
01419         /*
01420          * For now we don't support fragmentation, so make sure
01421          * fragment_offset == 0 and fragment_length == length
01422          */
01423         if( ssl->in_msg[6] != 0 || ssl->in_msg[7] != 0 || ssl->in_msg[8] != 0 ||
01424             memcmp( ssl->in_msg + 1, ssl->in_msg + 9, 3 ) != 0 )
01425         {
01426             MBEDTLS_SSL_DEBUG_MSG( 1, ( "ClientHello fragmentation not supported" ) );
01427             return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
01428         }
01429     }
01430 #endif /* MBEDTLS_SSL_PROTO_DTLS */
01431 
01432     buf += mbedtls_ssl_hs_hdr_len( ssl );
01433     msg_len -= mbedtls_ssl_hs_hdr_len( ssl );
01434 
01435     /*
01436      * ClientHello layer:
01437      *     0  .   1   protocol version
01438      *     2  .  33   random bytes (starting with 4 bytes of Unix time)
01439      *    34  .  35   session id length (1 byte)
01440      *    35  . 34+x  session id
01441      *   35+x . 35+x  DTLS only: cookie length (1 byte)
01442      *   36+x .  ..   DTLS only: cookie
01443      *    ..  .  ..   ciphersuite list length (2 bytes)
01444      *    ..  .  ..   ciphersuite list
01445      *    ..  .  ..   compression alg. list length (1 byte)
01446      *    ..  .  ..   compression alg. list
01447      *    ..  .  ..   extensions length (2 bytes, optional)
01448      *    ..  .  ..   extensions (optional)
01449      */
01450 
01451     /*
01452      * Minimal length (with everything empty and extensions ommitted) is
01453      * 2 + 32 + 1 + 2 + 1 = 38 bytes. Check that first, so that we can
01454      * read at least up to session id length without worrying.
01455      */
01456     if( msg_len < 38 )
01457     {
01458         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
01459         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
01460     }
01461 
01462     /*
01463      * Check and save the protocol version
01464      */
01465     MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, version", buf, 2 );
01466 
01467     mbedtls_ssl_read_version( &ssl->major_ver, &ssl->minor_ver,
01468                       ssl->conf->transport, buf );
01469 
01470     ssl->handshake->max_major_ver = ssl->major_ver;
01471     ssl->handshake->max_minor_ver = ssl->minor_ver;
01472 
01473     if( ssl->major_ver < ssl->conf->min_major_ver ||
01474         ssl->minor_ver < ssl->conf->min_minor_ver )
01475     {
01476         MBEDTLS_SSL_DEBUG_MSG( 1, ( "client only supports ssl smaller than minimum"
01477                             " [%d:%d] < [%d:%d]",
01478                             ssl->major_ver, ssl->minor_ver,
01479                             ssl->conf->min_major_ver, ssl->conf->min_minor_ver ) );
01480         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
01481                                      MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION );
01482         return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION );
01483     }
01484 
01485     if( ssl->major_ver > ssl->conf->max_major_ver )
01486     {
01487         ssl->major_ver = ssl->conf->max_major_ver;
01488         ssl->minor_ver = ssl->conf->max_minor_ver;
01489     }
01490     else if( ssl->minor_ver > ssl->conf->max_minor_ver )
01491         ssl->minor_ver = ssl->conf->max_minor_ver;
01492 
01493     /*
01494      * Save client random (inc. Unix time)
01495      */
01496     MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, random bytes", buf + 2, 32 );
01497 
01498     memcpy( ssl->handshake->randbytes, buf + 2, 32 );
01499 
01500     /*
01501      * Check the session ID length and save session ID
01502      */
01503     sess_len = buf[34];
01504 
01505     if( sess_len > sizeof( ssl->session_negotiate->id ) ||
01506         sess_len + 34 + 2 > msg_len ) /* 2 for cipherlist length field */
01507     {
01508         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
01509         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
01510                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
01511         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
01512     }
01513 
01514     MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, session id", buf + 35, sess_len );
01515 
01516     ssl->session_negotiate->id_len = sess_len;
01517     memset( ssl->session_negotiate->id, 0,
01518             sizeof( ssl->session_negotiate->id ) );
01519     memcpy( ssl->session_negotiate->id, buf + 35,
01520             ssl->session_negotiate->id_len );
01521 
01522     /*
01523      * Check the cookie length and content
01524      */
01525 #if defined(MBEDTLS_SSL_PROTO_DTLS)
01526     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
01527     {
01528         cookie_offset = 35 + sess_len;
01529         cookie_len = buf[cookie_offset];
01530 
01531         if( cookie_offset + 1 + cookie_len + 2 > msg_len )
01532         {
01533             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
01534             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
01535                                             MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION );
01536             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
01537         }
01538 
01539         MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, cookie",
01540                        buf + cookie_offset + 1, cookie_len );
01541 
01542 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY)
01543         if( ssl->conf->f_cookie_check != NULL
01544 #if defined(MBEDTLS_SSL_RENEGOTIATION)
01545             && ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE
01546 #endif
01547             )
01548         {
01549             if( ssl->conf->f_cookie_check( ssl->conf->p_cookie,
01550                                      buf + cookie_offset + 1, cookie_len,
01551                                      ssl->cli_id, ssl->cli_id_len ) != 0 )
01552             {
01553                 MBEDTLS_SSL_DEBUG_MSG( 2, ( "cookie verification failed" ) );
01554                 ssl->handshake->verify_cookie_len = 1;
01555             }
01556             else
01557             {
01558                 MBEDTLS_SSL_DEBUG_MSG( 2, ( "cookie verification passed" ) );
01559                 ssl->handshake->verify_cookie_len = 0;
01560             }
01561         }
01562         else
01563 #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */
01564         {
01565             /* We know we didn't send a cookie, so it should be empty */
01566             if( cookie_len != 0 )
01567             {
01568                 /* This may be an attacker's probe, so don't send an alert */
01569                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
01570                 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
01571             }
01572 
01573             MBEDTLS_SSL_DEBUG_MSG( 2, ( "cookie verification skipped" ) );
01574         }
01575 
01576     /*
01577      * Check the ciphersuitelist length (will be parsed later)
01578      */
01579         ciph_offset = cookie_offset + 1 + cookie_len;
01580     }
01581     else
01582 #endif /* MBEDTLS_SSL_PROTO_DTLS */
01583         ciph_offset = 35 + sess_len;
01584 
01585     ciph_len = ( buf[ciph_offset + 0] << 8 )
01586              | ( buf[ciph_offset + 1]      );
01587 
01588     if( ciph_len < 2 ||
01589         ciph_len + 2 + ciph_offset + 1 > msg_len || /* 1 for comp. alg. len */
01590         ( ciph_len % 2 ) != 0 )
01591     {
01592         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
01593         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
01594                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
01595         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
01596     }
01597 
01598     MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, ciphersuitelist",
01599                    buf + ciph_offset + 2,  ciph_len );
01600 
01601     /*
01602      * Check the compression algorithms length and pick one
01603      */
01604     comp_offset = ciph_offset + 2 + ciph_len;
01605 
01606     comp_len = buf[comp_offset];
01607 
01608     if( comp_len < 1 ||
01609         comp_len > 16 ||
01610         comp_len + comp_offset + 1 > msg_len )
01611     {
01612         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
01613         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
01614                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
01615         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
01616     }
01617 
01618     MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, compression",
01619                       buf + comp_offset + 1, comp_len );
01620 
01621     ssl->session_negotiate->compression = MBEDTLS_SSL_COMPRESS_NULL;
01622 #if defined(MBEDTLS_ZLIB_SUPPORT)
01623     for( i = 0; i < comp_len; ++i )
01624     {
01625         if( buf[comp_offset + 1 + i] == MBEDTLS_SSL_COMPRESS_DEFLATE )
01626         {
01627             ssl->session_negotiate->compression = MBEDTLS_SSL_COMPRESS_DEFLATE;
01628             break;
01629         }
01630     }
01631 #endif
01632 
01633     /* See comments in ssl_write_client_hello() */
01634 #if defined(MBEDTLS_SSL_PROTO_DTLS)
01635     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
01636         ssl->session_negotiate->compression = MBEDTLS_SSL_COMPRESS_NULL;
01637 #endif
01638 
01639     /* Do not parse the extensions if the protocol is SSLv3 */
01640 #if defined(MBEDTLS_SSL_PROTO_SSL3)
01641     if( ( ssl->major_ver != 3 ) || ( ssl->minor_ver != 0 ) )
01642     {
01643 #endif
01644         /*
01645          * Check the extension length
01646          */
01647         ext_offset = comp_offset + 1 + comp_len;
01648         if( msg_len > ext_offset )
01649         {
01650             if( msg_len < ext_offset + 2 )
01651             {
01652                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
01653                 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
01654                                                 MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
01655                 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
01656             }
01657 
01658             ext_len = ( buf[ext_offset + 0] << 8 )
01659                     | ( buf[ext_offset + 1]      );
01660 
01661             if( ( ext_len > 0 && ext_len < 4 ) ||
01662                 msg_len != ext_offset + 2 + ext_len )
01663             {
01664                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
01665                 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
01666                                                 MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
01667                 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
01668             }
01669         }
01670         else
01671             ext_len = 0;
01672 
01673         ext = buf + ext_offset + 2;
01674         MBEDTLS_SSL_DEBUG_BUF( 3, "client hello extensions", ext, ext_len );
01675 
01676         while( ext_len != 0 )
01677         {
01678             unsigned int ext_id;
01679             unsigned int ext_size;
01680             if ( ext_len < 4 ) {
01681                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
01682                 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
01683                                                MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
01684                 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
01685             }
01686             ext_id   = ( ( ext[0] <<  8 ) | ( ext[1] ) );
01687             ext_size = ( ( ext[2] <<  8 ) | ( ext[3] ) );
01688 
01689             if( ext_size + 4 > ext_len )
01690             {
01691                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
01692                 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
01693                                                 MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
01694                 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
01695             }
01696             switch( ext_id )
01697             {
01698 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
01699             case MBEDTLS_TLS_EXT_SERVERNAME:
01700                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found ServerName extension" ) );
01701                 if( ssl->conf->f_sni == NULL )
01702                     break;
01703 
01704                 ret = ssl_parse_servername_ext( ssl, ext + 4, ext_size );
01705                 if( ret != 0 )
01706                     return( ret );
01707                 break;
01708 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
01709 
01710             case MBEDTLS_TLS_EXT_RENEGOTIATION_INFO:
01711                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found renegotiation extension" ) );
01712 #if defined(MBEDTLS_SSL_RENEGOTIATION)
01713                 renegotiation_info_seen = 1;
01714 #endif
01715 
01716                 ret = ssl_parse_renegotiation_info( ssl, ext + 4, ext_size );
01717                 if( ret != 0 )
01718                     return( ret );
01719                 break;
01720 
01721 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
01722     defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
01723             case MBEDTLS_TLS_EXT_SIG_ALG:
01724                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found signature_algorithms extension" ) );
01725 
01726                 ret = ssl_parse_signature_algorithms_ext( ssl, ext + 4, ext_size );
01727                 if( ret != 0 )
01728                     return( ret );
01729 
01730                 sig_hash_alg_ext_present = 1;
01731                 break;
01732 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&
01733           MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
01734 
01735 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
01736     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
01737             case MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES:
01738                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found supported elliptic curves extension" ) );
01739 
01740                 ret = ssl_parse_supported_elliptic_curves( ssl, ext + 4, ext_size );
01741                 if( ret != 0 )
01742                     return( ret );
01743                 break;
01744 
01745             case MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS:
01746                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found supported point formats extension" ) );
01747                 ssl->handshake->cli_exts |= MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT;
01748 
01749                 ret = ssl_parse_supported_point_formats( ssl, ext + 4, ext_size );
01750                 if( ret != 0 )
01751                     return( ret );
01752                 break;
01753 #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
01754           MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
01755 
01756 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
01757             case MBEDTLS_TLS_EXT_ECJPAKE_KKPP:
01758                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found ecjpake kkpp extension" ) );
01759 
01760                 ret = ssl_parse_ecjpake_kkpp( ssl, ext + 4, ext_size );
01761                 if( ret != 0 )
01762                     return( ret );
01763                 break;
01764 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
01765 
01766 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
01767             case MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH:
01768                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found max fragment length extension" ) );
01769 
01770                 ret = ssl_parse_max_fragment_length_ext( ssl, ext + 4, ext_size );
01771                 if( ret != 0 )
01772                     return( ret );
01773                 break;
01774 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
01775 
01776 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
01777             case MBEDTLS_TLS_EXT_TRUNCATED_HMAC:
01778                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found truncated hmac extension" ) );
01779 
01780                 ret = ssl_parse_truncated_hmac_ext( ssl, ext + 4, ext_size );
01781                 if( ret != 0 )
01782                     return( ret );
01783                 break;
01784 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
01785 
01786 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
01787             case MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC:
01788                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found encrypt then mac extension" ) );
01789 
01790                 ret = ssl_parse_encrypt_then_mac_ext( ssl, ext + 4, ext_size );
01791                 if( ret != 0 )
01792                     return( ret );
01793                 break;
01794 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
01795 
01796 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
01797             case MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET:
01798                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found extended master secret extension" ) );
01799 
01800                 ret = ssl_parse_extended_ms_ext( ssl, ext + 4, ext_size );
01801                 if( ret != 0 )
01802                     return( ret );
01803                 break;
01804 #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
01805 
01806 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
01807             case MBEDTLS_TLS_EXT_SESSION_TICKET:
01808                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found session ticket extension" ) );
01809 
01810                 ret = ssl_parse_session_ticket_ext( ssl, ext + 4, ext_size );
01811                 if( ret != 0 )
01812                     return( ret );
01813                 break;
01814 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
01815 
01816 #if defined(MBEDTLS_SSL_ALPN)
01817             case MBEDTLS_TLS_EXT_ALPN:
01818                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found alpn extension" ) );
01819 
01820                 ret = ssl_parse_alpn_ext( ssl, ext + 4, ext_size );
01821                 if( ret != 0 )
01822                     return( ret );
01823                 break;
01824 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
01825 
01826             default:
01827                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "unknown extension found: %d (ignoring)",
01828                                ext_id ) );
01829             }
01830 
01831             ext_len -= 4 + ext_size;
01832             ext += 4 + ext_size;
01833 
01834             if( ext_len > 0 && ext_len < 4 )
01835             {
01836                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
01837                 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
01838                                                 MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
01839                 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
01840             }
01841         }
01842 #if defined(MBEDTLS_SSL_PROTO_SSL3)
01843     }
01844 #endif
01845 
01846 #if defined(MBEDTLS_SSL_FALLBACK_SCSV)
01847     for( i = 0, p = buf + ciph_offset + 2; i < ciph_len; i += 2, p += 2 )
01848     {
01849         if( p[0] == (unsigned char)( ( MBEDTLS_SSL_FALLBACK_SCSV_VALUE >> 8 ) & 0xff ) &&
01850             p[1] == (unsigned char)( ( MBEDTLS_SSL_FALLBACK_SCSV_VALUE      ) & 0xff ) )
01851         {
01852             MBEDTLS_SSL_DEBUG_MSG( 2, ( "received FALLBACK_SCSV" ) );
01853 
01854             if( ssl->minor_ver < ssl->conf->max_minor_ver )
01855             {
01856                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "inapropriate fallback" ) );
01857 
01858                 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
01859                                         MBEDTLS_SSL_ALERT_MSG_INAPROPRIATE_FALLBACK );
01860 
01861                 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
01862             }
01863 
01864             break;
01865         }
01866     }
01867 #endif /* MBEDTLS_SSL_FALLBACK_SCSV */
01868 
01869 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
01870     defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
01871 
01872     /*
01873      * Try to fall back to default hash SHA1 if the client
01874      * hasn't provided any preferred signature-hash combinations.
01875      */
01876     if( sig_hash_alg_ext_present == 0 )
01877     {
01878         mbedtls_md_type_t md_default = MBEDTLS_MD_SHA1;
01879 
01880         if( mbedtls_ssl_check_sig_hash( ssl, md_default ) != 0 )
01881             md_default = MBEDTLS_MD_NONE;
01882 
01883         mbedtls_ssl_sig_hash_set_const_hash( &ssl->handshake->hash_algs, md_default );
01884     }
01885 
01886 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&
01887           MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
01888 
01889     /*
01890      * Check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV
01891      */
01892     for( i = 0, p = buf + ciph_offset + 2; i < ciph_len; i += 2, p += 2 )
01893     {
01894         if( p[0] == 0 && p[1] == MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO )
01895         {
01896             MBEDTLS_SSL_DEBUG_MSG( 3, ( "received TLS_EMPTY_RENEGOTIATION_INFO " ) );
01897 #if defined(MBEDTLS_SSL_RENEGOTIATION)
01898             if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
01899             {
01900                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "received RENEGOTIATION SCSV "
01901                                             "during renegotiation" ) );
01902                 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
01903                                                 MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
01904                 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
01905             }
01906 #endif
01907             ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION;
01908             break;
01909         }
01910     }
01911 
01912     /*
01913      * Renegotiation security checks
01914      */
01915     if( ssl->secure_renegotiation != MBEDTLS_SSL_SECURE_RENEGOTIATION &&
01916         ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE )
01917     {
01918         MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation, breaking off handshake" ) );
01919         handshake_failure = 1;
01920     }
01921 #if defined(MBEDTLS_SSL_RENEGOTIATION)
01922     else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
01923              ssl->secure_renegotiation == MBEDTLS_SSL_SECURE_RENEGOTIATION &&
01924              renegotiation_info_seen == 0 )
01925     {
01926         MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation_info extension missing (secure)" ) );
01927         handshake_failure = 1;
01928     }
01929     else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
01930              ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
01931              ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION )
01932     {
01933         MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation not allowed" ) );
01934         handshake_failure = 1;
01935     }
01936     else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
01937              ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
01938              renegotiation_info_seen == 1 )
01939     {
01940         MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation_info extension present (legacy)" ) );
01941         handshake_failure = 1;
01942     }
01943 #endif /* MBEDTLS_SSL_RENEGOTIATION */
01944 
01945     if( handshake_failure == 1 )
01946     {
01947         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
01948                                         MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
01949         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
01950     }
01951 
01952     /*
01953      * Search for a matching ciphersuite
01954      * (At the end because we need information from the EC-based extensions
01955      * and certificate from the SNI callback triggered by the SNI extension.)
01956      */
01957     got_common_suite = 0;
01958     ciphersuites = ssl->conf->ciphersuite_list[ssl->minor_ver];
01959     ciphersuite_info = NULL;
01960 #if defined(MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE)
01961     for( j = 0, p = buf + ciph_offset + 2; j < ciph_len; j += 2, p += 2 )
01962         for( i = 0; ciphersuites[i] != 0; i++ )
01963 #else
01964     for( i = 0; ciphersuites[i] != 0; i++ )
01965         for( j = 0, p = buf + ciph_offset + 2; j < ciph_len; j += 2, p += 2 )
01966 #endif
01967         {
01968             if( p[0] != ( ( ciphersuites[i] >> 8 ) & 0xFF ) ||
01969                 p[1] != ( ( ciphersuites[i]      ) & 0xFF ) )
01970                 continue;
01971 
01972             got_common_suite = 1;
01973 
01974             if( ( ret = ssl_ciphersuite_match( ssl, ciphersuites[i],
01975                                                &ciphersuite_info ) ) != 0 )
01976                 return( ret );
01977 
01978             if( ciphersuite_info != NULL )
01979                 goto have_ciphersuite;
01980         }
01981 
01982     if( got_common_suite )
01983     {
01984         MBEDTLS_SSL_DEBUG_MSG( 1, ( "got ciphersuites in common, "
01985                             "but none of them usable" ) );
01986         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
01987                                         MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
01988         return( MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE );
01989     }
01990     else
01991     {
01992         MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no ciphersuites in common" ) );
01993         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
01994                                         MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
01995         return( MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN );
01996     }
01997 
01998 have_ciphersuite:
01999     MBEDTLS_SSL_DEBUG_MSG( 2, ( "selected ciphersuite: %s", ciphersuite_info->name ) );
02000 
02001     ssl->session_negotiate->ciphersuite = ciphersuites[i];
02002     ssl->transform_negotiate->ciphersuite_info = ciphersuite_info;
02003 
02004     ssl->state++;
02005 
02006 #if defined(MBEDTLS_SSL_PROTO_DTLS)
02007     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
02008         mbedtls_ssl_recv_flight_completed( ssl );
02009 #endif
02010 
02011     /* Debugging-only output for testsuite */
02012 #if defined(MBEDTLS_DEBUG_C)                         && \
02013     defined(MBEDTLS_SSL_PROTO_TLS1_2)                && \
02014     defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
02015     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
02016     {
02017         mbedtls_pk_type_t sig_alg = mbedtls_ssl_get_ciphersuite_sig_alg( ciphersuite_info );
02018         if( sig_alg != MBEDTLS_PK_NONE )
02019         {
02020             mbedtls_md_type_t md_alg = mbedtls_ssl_sig_hash_set_find( &ssl->handshake->hash_algs,
02021                                                                   sig_alg );
02022             MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext: %d",
02023                                         mbedtls_ssl_hash_from_md_alg( md_alg ) ) );
02024         }
02025         else
02026         {
02027             MBEDTLS_SSL_DEBUG_MSG( 3, ( "no hash algorithm for signature algorithm "
02028                                         "%d - should not happen", sig_alg ) );
02029         }
02030     }
02031 #endif
02032 
02033     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse client hello" ) );
02034 
02035     return( 0 );
02036 }
02037 
02038 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
02039 static void ssl_write_truncated_hmac_ext( mbedtls_ssl_context *ssl,
02040                                           unsigned char *buf,
02041                                           size_t *olen )
02042 {
02043     unsigned char *p = buf;
02044 
02045     if( ssl->session_negotiate->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_DISABLED )
02046     {
02047         *olen = 0;
02048         return;
02049     }
02050 
02051     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding truncated hmac extension" ) );
02052 
02053     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_TRUNCATED_HMAC >> 8 ) & 0xFF );
02054     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_TRUNCATED_HMAC      ) & 0xFF );
02055 
02056     *p++ = 0x00;
02057     *p++ = 0x00;
02058 
02059     *olen = 4;
02060 }
02061 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
02062 
02063 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
02064 static void ssl_write_encrypt_then_mac_ext( mbedtls_ssl_context *ssl,
02065                                             unsigned char *buf,
02066                                             size_t *olen )
02067 {
02068     unsigned char *p = buf;
02069     const mbedtls_ssl_ciphersuite_t *suite = NULL;
02070     const mbedtls_cipher_info_t *cipher = NULL;
02071 
02072     if( ssl->session_negotiate->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED ||
02073         ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
02074     {
02075         *olen = 0;
02076         return;
02077     }
02078 
02079     /*
02080      * RFC 7366: "If a server receives an encrypt-then-MAC request extension
02081      * from a client and then selects a stream or Authenticated Encryption
02082      * with Associated Data (AEAD) ciphersuite, it MUST NOT send an
02083      * encrypt-then-MAC response extension back to the client."
02084      */
02085     if( ( suite = mbedtls_ssl_ciphersuite_from_id(
02086                     ssl->session_negotiate->ciphersuite ) ) == NULL ||
02087         ( cipher = mbedtls_cipher_info_from_type( suite->cipher ) ) == NULL ||
02088         cipher->mode != MBEDTLS_MODE_CBC )
02089     {
02090         *olen = 0;
02091         return;
02092     }
02093 
02094     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding encrypt then mac extension" ) );
02095 
02096     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC >> 8 ) & 0xFF );
02097     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC      ) & 0xFF );
02098 
02099     *p++ = 0x00;
02100     *p++ = 0x00;
02101 
02102     *olen = 4;
02103 }
02104 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
02105 
02106 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
02107 static void ssl_write_extended_ms_ext( mbedtls_ssl_context *ssl,
02108                                        unsigned char *buf,
02109                                        size_t *olen )
02110 {
02111     unsigned char *p = buf;
02112 
02113     if( ssl->handshake->extended_ms == MBEDTLS_SSL_EXTENDED_MS_DISABLED ||
02114         ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
02115     {
02116         *olen = 0;
02117         return;
02118     }
02119 
02120     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding extended master secret "
02121                         "extension" ) );
02122 
02123     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET >> 8 ) & 0xFF );
02124     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET      ) & 0xFF );
02125 
02126     *p++ = 0x00;
02127     *p++ = 0x00;
02128 
02129     *olen = 4;
02130 }
02131 #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
02132 
02133 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
02134 static void ssl_write_session_ticket_ext( mbedtls_ssl_context *ssl,
02135                                           unsigned char *buf,
02136                                           size_t *olen )
02137 {
02138     unsigned char *p = buf;
02139 
02140     if( ssl->handshake->new_session_ticket == 0 )
02141     {
02142         *olen = 0;
02143         return;
02144     }
02145 
02146     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding session ticket extension" ) );
02147 
02148     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SESSION_TICKET >> 8 ) & 0xFF );
02149     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SESSION_TICKET      ) & 0xFF );
02150 
02151     *p++ = 0x00;
02152     *p++ = 0x00;
02153 
02154     *olen = 4;
02155 }
02156 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
02157 
02158 static void ssl_write_renegotiation_ext( mbedtls_ssl_context *ssl,
02159                                          unsigned char *buf,
02160                                          size_t *olen )
02161 {
02162     unsigned char *p = buf;
02163 
02164     if( ssl->secure_renegotiation != MBEDTLS_SSL_SECURE_RENEGOTIATION )
02165     {
02166         *olen = 0;
02167         return;
02168     }
02169 
02170     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, secure renegotiation extension" ) );
02171 
02172     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO >> 8 ) & 0xFF );
02173     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO      ) & 0xFF );
02174 
02175 #if defined(MBEDTLS_SSL_RENEGOTIATION)
02176     if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE )
02177     {
02178         *p++ = 0x00;
02179         *p++ = ( ssl->verify_data_len * 2 + 1 ) & 0xFF;
02180         *p++ = ssl->verify_data_len * 2 & 0xFF;
02181 
02182         memcpy( p, ssl->peer_verify_data, ssl->verify_data_len );
02183         p += ssl->verify_data_len;
02184         memcpy( p, ssl->own_verify_data, ssl->verify_data_len );
02185         p += ssl->verify_data_len;
02186     }
02187     else
02188 #endif /* MBEDTLS_SSL_RENEGOTIATION */
02189     {
02190         *p++ = 0x00;
02191         *p++ = 0x01;
02192         *p++ = 0x00;
02193     }
02194 
02195     *olen = p - buf;
02196 }
02197 
02198 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
02199 static void ssl_write_max_fragment_length_ext( mbedtls_ssl_context *ssl,
02200                                                unsigned char *buf,
02201                                                size_t *olen )
02202 {
02203     unsigned char *p = buf;
02204 
02205     if( ssl->session_negotiate->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE )
02206     {
02207         *olen = 0;
02208         return;
02209     }
02210 
02211     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, max_fragment_length extension" ) );
02212 
02213     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH >> 8 ) & 0xFF );
02214     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH      ) & 0xFF );
02215 
02216     *p++ = 0x00;
02217     *p++ = 1;
02218 
02219     *p++ = ssl->session_negotiate->mfl_code;
02220 
02221     *olen = 5;
02222 }
02223 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
02224 
02225 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
02226     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
02227 static void ssl_write_supported_point_formats_ext( mbedtls_ssl_context *ssl,
02228                                                    unsigned char *buf,
02229                                                    size_t *olen )
02230 {
02231     unsigned char *p = buf;
02232     ((void) ssl);
02233 
02234     if( ( ssl->handshake->cli_exts &
02235           MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT ) == 0 )
02236     {
02237         *olen = 0;
02238         return;
02239     }
02240 
02241     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, supported_point_formats extension" ) );
02242 
02243     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS >> 8 ) & 0xFF );
02244     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS      ) & 0xFF );
02245 
02246     *p++ = 0x00;
02247     *p++ = 2;
02248 
02249     *p++ = 1;
02250     *p++ = MBEDTLS_ECP_PF_UNCOMPRESSED;
02251 
02252     *olen = 6;
02253 }
02254 #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C || MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
02255 
02256 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
02257 static void ssl_write_ecjpake_kkpp_ext( mbedtls_ssl_context *ssl,
02258                                         unsigned char *buf,
02259                                         size_t *olen )
02260 {
02261     int ret;
02262     unsigned char *p = buf;
02263     const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;
02264     size_t kkpp_len;
02265 
02266     *olen = 0;
02267 
02268     /* Skip costly computation if not needed */
02269     if( ssl->transform_negotiate->ciphersuite_info->key_exchange !=
02270         MBEDTLS_KEY_EXCHANGE_ECJPAKE )
02271         return;
02272 
02273     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, ecjpake kkpp extension" ) );
02274 
02275     if( end - p < 4 )
02276     {
02277         MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
02278         return;
02279     }
02280 
02281     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ECJPAKE_KKPP >> 8 ) & 0xFF );
02282     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ECJPAKE_KKPP      ) & 0xFF );
02283 
02284     ret = mbedtls_ecjpake_write_round_one( &ssl->handshake->ecjpake_ctx,
02285                                         p + 2, end - p - 2, &kkpp_len,
02286                                         ssl->conf->f_rng, ssl->conf->p_rng );
02287     if( ret != 0 )
02288     {
02289         MBEDTLS_SSL_DEBUG_RET( 1 , "mbedtls_ecjpake_write_round_one", ret );
02290         return;
02291     }
02292 
02293     *p++ = (unsigned char)( ( kkpp_len >> 8 ) & 0xFF );
02294     *p++ = (unsigned char)( ( kkpp_len      ) & 0xFF );
02295 
02296     *olen = kkpp_len + 4;
02297 }
02298 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
02299 
02300 #if defined(MBEDTLS_SSL_ALPN )
02301 static void ssl_write_alpn_ext( mbedtls_ssl_context *ssl,
02302                                 unsigned char *buf, size_t *olen )
02303 {
02304     if( ssl->alpn_chosen == NULL )
02305     {
02306         *olen = 0;
02307         return;
02308     }
02309 
02310     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding alpn extension" ) );
02311 
02312     /*
02313      * 0 . 1    ext identifier
02314      * 2 . 3    ext length
02315      * 4 . 5    protocol list length
02316      * 6 . 6    protocol name length
02317      * 7 . 7+n  protocol name
02318      */
02319     buf[0] = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN >> 8 ) & 0xFF );
02320     buf[1] = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN      ) & 0xFF );
02321 
02322     *olen = 7 + strlen( ssl->alpn_chosen );
02323 
02324     buf[2] = (unsigned char)( ( ( *olen - 4 ) >> 8 ) & 0xFF );
02325     buf[3] = (unsigned char)( ( ( *olen - 4 )      ) & 0xFF );
02326 
02327     buf[4] = (unsigned char)( ( ( *olen - 6 ) >> 8 ) & 0xFF );
02328     buf[5] = (unsigned char)( ( ( *olen - 6 )      ) & 0xFF );
02329 
02330     buf[6] = (unsigned char)( ( ( *olen - 7 )      ) & 0xFF );
02331 
02332     memcpy( buf + 7, ssl->alpn_chosen, *olen - 7 );
02333 }
02334 #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C */
02335 
02336 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY)
02337 static int ssl_write_hello_verify_request( mbedtls_ssl_context *ssl )
02338 {
02339     int ret;
02340     unsigned char *p = ssl->out_msg + 4;
02341     unsigned char *cookie_len_byte;
02342 
02343     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write hello verify request" ) );
02344 
02345     /*
02346      * struct {
02347      *   ProtocolVersion server_version;
02348      *   opaque cookie<0..2^8-1>;
02349      * } HelloVerifyRequest;
02350      */
02351 
02352     /* The RFC is not clear on this point, but sending the actual negotiated
02353      * version looks like the most interoperable thing to do. */
02354     mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,
02355                        ssl->conf->transport, p );
02356     MBEDTLS_SSL_DEBUG_BUF( 3, "server version", p, 2 );
02357     p += 2;
02358 
02359     /* If we get here, f_cookie_check is not null */
02360     if( ssl->conf->f_cookie_write == NULL )
02361     {
02362         MBEDTLS_SSL_DEBUG_MSG( 1, ( "inconsistent cookie callbacks" ) );
02363         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
02364     }
02365 
02366     /* Skip length byte until we know the length */
02367     cookie_len_byte = p++;
02368 
02369     if( ( ret = ssl->conf->f_cookie_write( ssl->conf->p_cookie,
02370                                      &p, ssl->out_buf + MBEDTLS_SSL_OUT_BUFFER_LEN,
02371                                      ssl->cli_id, ssl->cli_id_len ) ) != 0 )
02372     {
02373         MBEDTLS_SSL_DEBUG_RET( 1, "f_cookie_write", ret );
02374         return( ret );
02375     }
02376 
02377     *cookie_len_byte = (unsigned char)( p - ( cookie_len_byte + 1 ) );
02378 
02379     MBEDTLS_SSL_DEBUG_BUF( 3, "cookie sent", cookie_len_byte + 1, *cookie_len_byte );
02380 
02381     ssl->out_msglen  = p - ssl->out_msg;
02382     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
02383     ssl->out_msg[0]  = MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST;
02384 
02385     ssl->state = MBEDTLS_SSL_SERVER_HELLO_VERIFY_REQUEST_SENT;
02386 
02387     if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
02388     {
02389         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
02390         return( ret );
02391     }
02392 
02393 #if defined(MBEDTLS_SSL_PROTO_DTLS)
02394     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
02395         ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 )
02396     {
02397         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flight_transmit", ret );
02398         return( ret );
02399     }
02400 #endif /* MBEDTLS_SSL_PROTO_DTLS */
02401 
02402     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write hello verify request" ) );
02403 
02404     return( 0 );
02405 }
02406 #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */
02407 
02408 static int ssl_write_server_hello( mbedtls_ssl_context *ssl )
02409 {
02410 #if defined(MBEDTLS_HAVE_TIME)
02411     mbedtls_time_t t;
02412 #endif
02413     int ret;
02414     size_t olen, ext_len = 0, n;
02415     unsigned char *buf, *p;
02416 
02417     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write server hello" ) );
02418 
02419 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY)
02420     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
02421         ssl->handshake->verify_cookie_len != 0 )
02422     {
02423         MBEDTLS_SSL_DEBUG_MSG( 2, ( "client hello was not authenticated" ) );
02424         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write server hello" ) );
02425 
02426         return( ssl_write_hello_verify_request( ssl ) );
02427     }
02428 #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */
02429 
02430     if( ssl->conf->f_rng == NULL )
02431     {
02432         MBEDTLS_SSL_DEBUG_MSG( 1, ( "no RNG provided") );
02433         return( MBEDTLS_ERR_SSL_NO_RNG );
02434     }
02435 
02436     /*
02437      *     0  .   0   handshake type
02438      *     1  .   3   handshake length
02439      *     4  .   5   protocol version
02440      *     6  .   9   UNIX time()
02441      *    10  .  37   random bytes
02442      */
02443     buf = ssl->out_msg;
02444     p = buf + 4;
02445 
02446     mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,
02447                        ssl->conf->transport, p );
02448     p += 2;
02449 
02450     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen version: [%d:%d]",
02451                         buf[4], buf[5] ) );
02452 
02453 #if defined(MBEDTLS_HAVE_TIME)
02454     t = mbedtls_time( NULL );
02455     *p++ = (unsigned char)( t >> 24 );
02456     *p++ = (unsigned char)( t >> 16 );
02457     *p++ = (unsigned char)( t >>  8 );
02458     *p++ = (unsigned char)( t       );
02459 
02460     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, current time: %lu", t ) );
02461 #else
02462     if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p, 4 ) ) != 0 )
02463         return( ret );
02464 
02465     p += 4;
02466 #endif /* MBEDTLS_HAVE_TIME */
02467 
02468     if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p, 28 ) ) != 0 )
02469         return( ret );
02470 
02471     p += 28;
02472 
02473     memcpy( ssl->handshake->randbytes + 32, buf + 6, 32 );
02474 
02475     MBEDTLS_SSL_DEBUG_BUF( 3, "server hello, random bytes", buf + 6, 32 );
02476 
02477     /*
02478      * Resume is 0  by default, see ssl_handshake_init().
02479      * It may be already set to 1 by ssl_parse_session_ticket_ext().
02480      * If not, try looking up session ID in our cache.
02481      */
02482     if( ssl->handshake->resume == 0 &&
02483 #if defined(MBEDTLS_SSL_RENEGOTIATION)
02484         ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE &&
02485 #endif
02486         ssl->session_negotiate->id_len != 0 &&
02487         ssl->conf->f_get_cache != NULL &&
02488         ssl->conf->f_get_cache( ssl->conf->p_cache, ssl->session_negotiate ) == 0 )
02489     {
02490         MBEDTLS_SSL_DEBUG_MSG( 3, ( "session successfully restored from cache" ) );
02491         ssl->handshake->resume = 1;
02492     }
02493 
02494     if( ssl->handshake->resume == 0 )
02495     {
02496         /*
02497          * New session, create a new session id,
02498          * unless we're about to issue a session ticket
02499          */
02500         ssl->state++;
02501 
02502 #if defined(MBEDTLS_HAVE_TIME)
02503         ssl->session_negotiate->start = mbedtls_time( NULL );
02504 #endif
02505 
02506 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
02507         if( ssl->handshake->new_session_ticket != 0 )
02508         {
02509             ssl->session_negotiate->id_len = n = 0;
02510             memset( ssl->session_negotiate->id, 0, 32 );
02511         }
02512         else
02513 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
02514         {
02515             ssl->session_negotiate->id_len = n = 32;
02516             if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, ssl->session_negotiate->id,
02517                                     n ) ) != 0 )
02518                 return( ret );
02519         }
02520     }
02521     else
02522     {
02523         /*
02524          * Resuming a session
02525          */
02526         n = ssl->session_negotiate->id_len;
02527         ssl->state = MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC;
02528 
02529         if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )
02530         {
02531             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret );
02532             return( ret );
02533         }
02534     }
02535 
02536     /*
02537      *    38  .  38     session id length
02538      *    39  . 38+n    session id
02539      *   39+n . 40+n    chosen ciphersuite
02540      *   41+n . 41+n    chosen compression alg.
02541      *   42+n . 43+n    extensions length
02542      *   44+n . 43+n+m  extensions
02543      */
02544     *p++ = (unsigned char) ssl->session_negotiate->id_len;
02545     memcpy( p, ssl->session_negotiate->id, ssl->session_negotiate->id_len );
02546     p += ssl->session_negotiate->id_len;
02547 
02548     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, session id len.: %d", n ) );
02549     MBEDTLS_SSL_DEBUG_BUF( 3,   "server hello, session id", buf + 39, n );
02550     MBEDTLS_SSL_DEBUG_MSG( 3, ( "%s session has been resumed",
02551                    ssl->handshake->resume ? "a" : "no" ) );
02552 
02553     *p++ = (unsigned char)( ssl->session_negotiate->ciphersuite >> 8 );
02554     *p++ = (unsigned char)( ssl->session_negotiate->ciphersuite      );
02555     *p++ = (unsigned char)( ssl->session_negotiate->compression      );
02556 
02557     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen ciphersuite: %s",
02558            mbedtls_ssl_get_ciphersuite_name( ssl->session_negotiate->ciphersuite ) ) );
02559     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, compress alg.: 0x%02X",
02560                    ssl->session_negotiate->compression ) );
02561 
02562     /* Do not write the extensions if the protocol is SSLv3 */
02563 #if defined(MBEDTLS_SSL_PROTO_SSL3)
02564     if( ( ssl->major_ver != 3 ) || ( ssl->minor_ver != 0 ) )
02565     {
02566 #endif
02567 
02568     /*
02569      *  First write extensions, then the total length
02570      */
02571     ssl_write_renegotiation_ext( ssl, p + 2 + ext_len, &olen );
02572     ext_len += olen;
02573 
02574 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
02575     ssl_write_max_fragment_length_ext( ssl, p + 2 + ext_len, &olen );
02576     ext_len += olen;
02577 #endif
02578 
02579 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
02580     ssl_write_truncated_hmac_ext( ssl, p + 2 + ext_len, &olen );
02581     ext_len += olen;
02582 #endif
02583 
02584 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
02585     ssl_write_encrypt_then_mac_ext( ssl, p + 2 + ext_len, &olen );
02586     ext_len += olen;
02587 #endif
02588 
02589 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
02590     ssl_write_extended_ms_ext( ssl, p + 2 + ext_len, &olen );
02591     ext_len += olen;
02592 #endif
02593 
02594 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
02595     ssl_write_session_ticket_ext( ssl, p + 2 + ext_len, &olen );
02596     ext_len += olen;
02597 #endif
02598 
02599 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
02600     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
02601     if ( mbedtls_ssl_ciphersuite_uses_ec(
02602          mbedtls_ssl_ciphersuite_from_id( ssl->session_negotiate->ciphersuite ) ) )
02603     {
02604         ssl_write_supported_point_formats_ext( ssl, p + 2 + ext_len, &olen );
02605         ext_len += olen;
02606     }
02607 #endif
02608 
02609 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
02610     ssl_write_ecjpake_kkpp_ext( ssl, p + 2 + ext_len, &olen );
02611     ext_len += olen;
02612 #endif
02613 
02614 #if defined(MBEDTLS_SSL_ALPN)
02615     ssl_write_alpn_ext( ssl, p + 2 + ext_len, &olen );
02616     ext_len += olen;
02617 #endif
02618 
02619     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, total extension length: %d", ext_len ) );
02620 
02621     if( ext_len > 0 )
02622     {
02623         *p++ = (unsigned char)( ( ext_len >> 8 ) & 0xFF );
02624         *p++ = (unsigned char)( ( ext_len      ) & 0xFF );
02625         p += ext_len;
02626     }
02627 
02628 #if defined(MBEDTLS_SSL_PROTO_SSL3)
02629     }
02630 #endif
02631 
02632     ssl->out_msglen  = p - buf;
02633     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
02634     ssl->out_msg[0]  = MBEDTLS_SSL_HS_SERVER_HELLO;
02635 
02636     ret = mbedtls_ssl_write_handshake_msg( ssl );
02637 
02638     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write server hello" ) );
02639 
02640     return( ret );
02641 }
02642 
02643 #if !defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)       && \
02644     !defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)   && \
02645     !defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED)  && \
02646     !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) && \
02647     !defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)&& \
02648     !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
02649 static int ssl_write_certificate_request( mbedtls_ssl_context *ssl )
02650 {
02651     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
02652         ssl->transform_negotiate->ciphersuite_info;
02653 
02654     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate request" ) );
02655 
02656     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
02657         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
02658         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
02659         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
02660         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
02661     {
02662         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate request" ) );
02663         ssl->state++;
02664         return( 0 );
02665     }
02666 
02667     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
02668     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
02669 }
02670 #else
02671 static int ssl_write_certificate_request( mbedtls_ssl_context *ssl )
02672 {
02673     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
02674     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
02675         ssl->transform_negotiate->ciphersuite_info;
02676     size_t dn_size, total_dn_size; /* excluding length bytes */
02677     size_t ct_len, sa_len; /* including length bytes */
02678     unsigned char *buf, *p;
02679     const unsigned char * const end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;
02680     const mbedtls_x509_crt *crt;
02681     int authmode;
02682 
02683     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate request" ) );
02684 
02685     ssl->state++;
02686 
02687 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
02688     if( ssl->handshake->sni_authmode != MBEDTLS_SSL_VERIFY_UNSET )
02689         authmode = ssl->handshake->sni_authmode;
02690     else
02691 #endif
02692         authmode = ssl->conf->authmode;
02693 
02694     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
02695         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
02696         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
02697         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
02698         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE ||
02699         authmode == MBEDTLS_SSL_VERIFY_NONE )
02700     {
02701         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate request" ) );
02702         return( 0 );
02703     }
02704 
02705     /*
02706      *     0  .   0   handshake type
02707      *     1  .   3   handshake length
02708      *     4  .   4   cert type count
02709      *     5  .. m-1  cert types
02710      *     m  .. m+1  sig alg length (TLS 1.2 only)
02711      *    m+1 .. n-1  SignatureAndHashAlgorithms (TLS 1.2 only)
02712      *     n  .. n+1  length of all DNs
02713      *    n+2 .. n+3  length of DN 1
02714      *    n+4 .. ...  Distinguished Name #1
02715      *    ... .. ...  length of DN 2, etc.
02716      */
02717     buf = ssl->out_msg;
02718     p = buf + 4;
02719 
02720     /*
02721      * Supported certificate types
02722      *
02723      *     ClientCertificateType certificate_types<1..2^8-1>;
02724      *     enum { (255) } ClientCertificateType;
02725      */
02726     ct_len = 0;
02727 
02728 #if defined(MBEDTLS_RSA_C)
02729     p[1 + ct_len++] = MBEDTLS_SSL_CERT_TYPE_RSA_SIGN;
02730 #endif
02731 #if defined(MBEDTLS_ECDSA_C)
02732     p[1 + ct_len++] = MBEDTLS_SSL_CERT_TYPE_ECDSA_SIGN;
02733 #endif
02734 
02735     p[0] = (unsigned char) ct_len++;
02736     p += ct_len;
02737 
02738     sa_len = 0;
02739 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
02740     /*
02741      * Add signature_algorithms for verify (TLS 1.2)
02742      *
02743      *     SignatureAndHashAlgorithm supported_signature_algorithms<2..2^16-2>;
02744      *
02745      *     struct {
02746      *           HashAlgorithm hash;
02747      *           SignatureAlgorithm signature;
02748      *     } SignatureAndHashAlgorithm;
02749      *
02750      *     enum { (255) } HashAlgorithm;
02751      *     enum { (255) } SignatureAlgorithm;
02752      */
02753     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
02754     {
02755         const int *cur;
02756 
02757         /*
02758          * Supported signature algorithms
02759          */
02760         for( cur = ssl->conf->sig_hashes; *cur != MBEDTLS_MD_NONE; cur++ )
02761         {
02762             unsigned char hash = mbedtls_ssl_hash_from_md_alg( *cur );
02763 
02764             if( MBEDTLS_SSL_HASH_NONE == hash || mbedtls_ssl_set_calc_verify_md( ssl, hash ) )
02765                 continue;
02766 
02767 #if defined(MBEDTLS_RSA_C)
02768             p[2 + sa_len++] = hash;
02769             p[2 + sa_len++] = MBEDTLS_SSL_SIG_RSA;
02770 #endif
02771 #if defined(MBEDTLS_ECDSA_C)
02772             p[2 + sa_len++] = hash;
02773             p[2 + sa_len++] = MBEDTLS_SSL_SIG_ECDSA;
02774 #endif
02775         }
02776 
02777         p[0] = (unsigned char)( sa_len >> 8 );
02778         p[1] = (unsigned char)( sa_len      );
02779         sa_len += 2;
02780         p += sa_len;
02781     }
02782 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
02783 
02784     /*
02785      * DistinguishedName certificate_authorities<0..2^16-1>;
02786      * opaque DistinguishedName<1..2^16-1>;
02787      */
02788     p += 2;
02789 
02790     total_dn_size = 0;
02791 
02792     if( ssl->conf->cert_req_ca_list ==  MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED )
02793     {
02794 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
02795         if( ssl->handshake->sni_ca_chain != NULL )
02796             crt = ssl->handshake->sni_ca_chain;
02797         else
02798 #endif
02799             crt = ssl->conf->ca_chain;
02800 
02801         while( crt != NULL && crt->version != 0 )
02802         {
02803             dn_size = crt->subject_raw.len;
02804 
02805             if( end < p ||
02806                 (size_t)( end - p ) < dn_size ||
02807                 (size_t)( end - p ) < 2 + dn_size )
02808             {
02809                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "skipping CAs: buffer too short" ) );
02810                 break;
02811             }
02812 
02813             *p++ = (unsigned char)( dn_size >> 8 );
02814             *p++ = (unsigned char)( dn_size      );
02815             memcpy( p, crt->subject_raw.p, dn_size );
02816             p += dn_size;
02817 
02818             MBEDTLS_SSL_DEBUG_BUF( 3, "requested DN", p - dn_size, dn_size );
02819 
02820             total_dn_size += 2 + dn_size;
02821             crt = crt->next;
02822         }
02823     }
02824 
02825     ssl->out_msglen  = p - buf;
02826     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
02827     ssl->out_msg[0]  = MBEDTLS_SSL_HS_CERTIFICATE_REQUEST;
02828     ssl->out_msg[4 + ct_len + sa_len] = (unsigned char)( total_dn_size  >> 8 );
02829     ssl->out_msg[5 + ct_len + sa_len] = (unsigned char)( total_dn_size       );
02830 
02831     ret = mbedtls_ssl_write_handshake_msg( ssl );
02832 
02833     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write certificate request" ) );
02834 
02835     return( ret );
02836 }
02837 #endif /* !MBEDTLS_KEY_EXCHANGE_RSA_ENABLED &&
02838           !MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED &&
02839           !MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED &&
02840           !MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED &&
02841           !MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED &&
02842           !MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
02843 
02844 #if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
02845     defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
02846 static int ssl_get_ecdh_params_from_cert( mbedtls_ssl_context *ssl )
02847 {
02848     int ret;
02849 
02850     if( ! mbedtls_pk_can_do( mbedtls_ssl_own_key( ssl ), MBEDTLS_PK_ECKEY ) )
02851     {
02852         MBEDTLS_SSL_DEBUG_MSG( 1, ( "server key not ECDH capable" ) );
02853         return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
02854     }
02855 
02856     if( ( ret = mbedtls_ecdh_get_params( &ssl->handshake->ecdh_ctx,
02857                                  mbedtls_pk_ec( *mbedtls_ssl_own_key( ssl ) ),
02858                                  MBEDTLS_ECDH_OURS ) ) != 0 )
02859     {
02860         MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ecdh_get_params" ), ret );
02861         return( ret );
02862     }
02863 
02864     return( 0 );
02865 }
02866 #endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||
02867           MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
02868 
02869 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED) && \
02870     defined(MBEDTLS_SSL_ASYNC_PRIVATE)
02871 static int ssl_resume_server_key_exchange( mbedtls_ssl_context *ssl,
02872                                            size_t *signature_len )
02873 {
02874     /* Append the signature to ssl->out_msg, leaving 2 bytes for the
02875      * signature length which will be added in ssl_write_server_key_exchange
02876      * after the call to ssl_prepare_server_key_exchange.
02877      * ssl_write_server_key_exchange also takes care of incrementing
02878      * ssl->out_msglen. */
02879     unsigned char *sig_start = ssl->out_msg + ssl->out_msglen + 2;
02880     size_t sig_max_len = ( ssl->out_buf + MBEDTLS_SSL_OUT_CONTENT_LEN
02881                            - sig_start );
02882     int ret = ssl->conf->f_async_resume( ssl,
02883                                          sig_start, signature_len, sig_max_len );
02884     if( ret != MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS )
02885     {
02886         ssl->handshake->async_in_progress = 0;
02887         mbedtls_ssl_set_async_operation_data( ssl, NULL );
02888     }
02889     MBEDTLS_SSL_DEBUG_RET( 2, "ssl_resume_server_key_exchange", ret );
02890     return( ret );
02891 }
02892 #endif /* defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED) &&
02893           defined(MBEDTLS_SSL_ASYNC_PRIVATE) */
02894 
02895 /* Prepare the ServerKeyExchange message, up to and including
02896  * calculating the signature if any, but excluding formatting the
02897  * signature and sending the message. */
02898 static int ssl_prepare_server_key_exchange( mbedtls_ssl_context *ssl,
02899                                             size_t *signature_len )
02900 {
02901     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
02902                             ssl->transform_negotiate->ciphersuite_info;
02903 #if defined(MBEDTLS_KEY_EXCHANGE__SOME_PFS__ENABLED)
02904 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED)
02905     unsigned char *dig_signed = NULL;
02906 #endif /* MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED */
02907 #endif /* MBEDTLS_KEY_EXCHANGE__SOME_PFS__ENABLED */
02908 
02909     (void) ciphersuite_info; /* unused in some configurations */
02910 #if !defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED)
02911     (void) signature_len;
02912 #endif /* MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED */
02913 
02914     ssl->out_msglen = 4; /* header (type:1, length:3) to be written later */
02915 
02916     /*
02917      *
02918      * Part 1: Provide key exchange parameters for chosen ciphersuite.
02919      *
02920      */
02921 
02922     /*
02923      * - ECJPAKE key exchanges
02924      */
02925 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
02926     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
02927     {
02928         int ret;
02929         size_t len = 0;
02930 
02931         ret = mbedtls_ecjpake_write_round_two(
02932             &ssl->handshake->ecjpake_ctx,
02933             ssl->out_msg + ssl->out_msglen,
02934             MBEDTLS_SSL_OUT_CONTENT_LEN - ssl->out_msglen, &len,
02935             ssl->conf->f_rng, ssl->conf->p_rng );
02936         if( ret != 0 )
02937         {
02938             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_write_round_two", ret );
02939             return( ret );
02940         }
02941 
02942         ssl->out_msglen += len;
02943     }
02944 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
02945 
02946     /*
02947      * For (EC)DHE key exchanges with PSK, parameters are prefixed by support
02948      * identity hint (RFC 4279, Sec. 3). Until someone needs this feature,
02949      * we use empty support identity hints here.
02950      **/
02951 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)   || \
02952     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
02953     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
02954         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
02955     {
02956         ssl->out_msg[ssl->out_msglen++] = 0x00;
02957         ssl->out_msg[ssl->out_msglen++] = 0x00;
02958     }
02959 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED ||
02960           MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
02961 
02962     /*
02963      * - DHE key exchanges
02964      */
02965 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__DHE_ENABLED)
02966     if( mbedtls_ssl_ciphersuite_uses_dhe( ciphersuite_info ) )
02967     {
02968         int ret;
02969         size_t len = 0;
02970 
02971         if( ssl->conf->dhm_P.p == NULL || ssl->conf->dhm_G.p == NULL )
02972         {
02973             MBEDTLS_SSL_DEBUG_MSG( 1, ( "no DH parameters set" ) );
02974             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
02975         }
02976 
02977         /*
02978          * Ephemeral DH parameters:
02979          *
02980          * struct {
02981          *     opaque dh_p<1..2^16-1>;
02982          *     opaque dh_g<1..2^16-1>;
02983          *     opaque dh_Ys<1..2^16-1>;
02984          * } ServerDHParams;
02985          */
02986         if( ( ret = mbedtls_dhm_set_group( &ssl->handshake->dhm_ctx,
02987                                            &ssl->conf->dhm_P,
02988                                            &ssl->conf->dhm_G ) ) != 0 )
02989         {
02990             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_set_group", ret );
02991             return( ret );
02992         }
02993 
02994         if( ( ret = mbedtls_dhm_make_params(
02995                   &ssl->handshake->dhm_ctx,
02996                   (int) mbedtls_mpi_size( &ssl->handshake->dhm_ctx.P ),
02997                   ssl->out_msg + ssl->out_msglen, &len,
02998                   ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
02999         {
03000             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_make_params", ret );
03001             return( ret );
03002         }
03003 
03004 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED)
03005         dig_signed = ssl->out_msg + ssl->out_msglen;
03006 #endif
03007 
03008         ssl->out_msglen += len;
03009 
03010         MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: X ", &ssl->handshake->dhm_ctx.X  );
03011         MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: P ", &ssl->handshake->dhm_ctx.P  );
03012         MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: G ", &ssl->handshake->dhm_ctx.G  );
03013         MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: GX", &ssl->handshake->dhm_ctx.GX );
03014     }
03015 #endif /* MBEDTLS_KEY_EXCHANGE__SOME__DHE_ENABLED */
03016 
03017     /*
03018      * - ECDHE key exchanges
03019      */
03020 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__ECDHE_ENABLED)
03021     if( mbedtls_ssl_ciphersuite_uses_ecdhe( ciphersuite_info ) )
03022     {
03023         /*
03024          * Ephemeral ECDH parameters:
03025          *
03026          * struct {
03027          *     ECParameters curve_params;
03028          *     ECPoint      public;
03029          * } ServerECDHParams;
03030          */
03031         const mbedtls_ecp_curve_info **curve = NULL;
03032         const mbedtls_ecp_group_id *gid;
03033         int ret;
03034         size_t len = 0;
03035 
03036         /* Match our preference list against the offered curves */
03037         for( gid = ssl->conf->curve_list; *gid != MBEDTLS_ECP_DP_NONE; gid++ )
03038             for( curve = ssl->handshake->curves; *curve != NULL; curve++ )
03039                 if( (*curve)->grp_id == *gid )
03040                     goto curve_matching_done;
03041 
03042 curve_matching_done:
03043         if( curve == NULL || *curve == NULL )
03044         {
03045             MBEDTLS_SSL_DEBUG_MSG( 1, ( "no matching curve for ECDHE" ) );
03046             return( MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN );
03047         }
03048 
03049         MBEDTLS_SSL_DEBUG_MSG( 2, ( "ECDHE curve: %s", (*curve)->name ) );
03050 
03051         if( ( ret = mbedtls_ecp_group_load( &ssl->handshake->ecdh_ctx.grp,
03052                                        (*curve)->grp_id ) ) != 0 )
03053         {
03054             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecp_group_load", ret );
03055             return( ret );
03056         }
03057 
03058         if( ( ret = mbedtls_ecdh_make_params(
03059                   &ssl->handshake->ecdh_ctx, &len,
03060                   ssl->out_msg + ssl->out_msglen,
03061                   MBEDTLS_SSL_OUT_CONTENT_LEN - ssl->out_msglen,
03062                   ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
03063         {
03064             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_make_params", ret );
03065             return( ret );
03066         }
03067 
03068 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED)
03069         dig_signed = ssl->out_msg + ssl->out_msglen;
03070 #endif
03071 
03072         ssl->out_msglen += len;
03073 
03074         MBEDTLS_SSL_DEBUG_ECP( 3, "ECDH: Q ", &ssl->handshake->ecdh_ctx.Q );
03075     }
03076 #endif /* MBEDTLS_KEY_EXCHANGE__SOME__ECDHE_ENABLED */
03077 
03078     /*
03079      *
03080      * Part 2: For key exchanges involving the server signing the
03081      *         exchange parameters, compute and add the signature here.
03082      *
03083      */
03084 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED)
03085     if( mbedtls_ssl_ciphersuite_uses_server_signature( ciphersuite_info ) )
03086     {
03087         size_t dig_signed_len = ssl->out_msg + ssl->out_msglen - dig_signed;
03088         size_t hashlen = 0;
03089         unsigned char hash[MBEDTLS_MD_MAX_SIZE];
03090         int ret;
03091 
03092         /*
03093          * 2.1: Choose hash algorithm:
03094          * A: For TLS 1.2, obey signature-hash-algorithm extension
03095          *    to choose appropriate hash.
03096          * B: For SSL3, TLS1.0, TLS1.1 and ECDHE_ECDSA, use SHA1
03097          *    (RFC 4492, Sec. 5.4)
03098          * C: Otherwise, use MD5 + SHA1 (RFC 4346, Sec. 7.4.3)
03099          */
03100 
03101         mbedtls_md_type_t md_alg;
03102 
03103 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
03104         mbedtls_pk_type_t sig_alg =
03105             mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info );
03106         if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
03107         {
03108             /* A: For TLS 1.2, obey signature-hash-algorithm extension
03109              *    (RFC 5246, Sec. 7.4.1.4.1). */
03110             if( sig_alg == MBEDTLS_PK_NONE ||
03111                 ( md_alg = mbedtls_ssl_sig_hash_set_find( &ssl->handshake->hash_algs,
03112                                                           sig_alg ) ) == MBEDTLS_MD_NONE )
03113             {
03114                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
03115                 /* (... because we choose a cipher suite
03116                  *      only if there is a matching hash.) */
03117                 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
03118             }
03119         }
03120         else
03121 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
03122 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
03123     defined(MBEDTLS_SSL_PROTO_TLS1_1)
03124         if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA )
03125         {
03126             /* B: Default hash SHA1 */
03127             md_alg = MBEDTLS_MD_SHA1;
03128         }
03129         else
03130 #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
03131           MBEDTLS_SSL_PROTO_TLS1_1 */
03132         {
03133             /* C: MD5 + SHA1 */
03134             md_alg = MBEDTLS_MD_NONE;
03135         }
03136 
03137         MBEDTLS_SSL_DEBUG_MSG( 3, ( "pick hash algorithm %d for signing", md_alg ) );
03138 
03139         /*
03140          * 2.2: Compute the hash to be signed
03141          */
03142 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
03143     defined(MBEDTLS_SSL_PROTO_TLS1_1)
03144         if( md_alg == MBEDTLS_MD_NONE )
03145         {
03146             hashlen = 36;
03147             ret = mbedtls_ssl_get_key_exchange_md_ssl_tls( ssl, hash,
03148                                                            dig_signed,
03149                                                            dig_signed_len );
03150             if( ret != 0 )
03151                 return( ret );
03152         }
03153         else
03154 #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
03155           MBEDTLS_SSL_PROTO_TLS1_1 */
03156 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
03157     defined(MBEDTLS_SSL_PROTO_TLS1_2)
03158         if( md_alg != MBEDTLS_MD_NONE )
03159         {
03160             ret = mbedtls_ssl_get_key_exchange_md_tls1_2( ssl, hash, &hashlen,
03161                                                           dig_signed,
03162                                                           dig_signed_len,
03163                                                           md_alg );
03164             if( ret != 0 )
03165                 return( ret );
03166         }
03167         else
03168 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
03169           MBEDTLS_SSL_PROTO_TLS1_2 */
03170         {
03171             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
03172             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
03173         }
03174 
03175         MBEDTLS_SSL_DEBUG_BUF( 3, "parameters hash", hash, hashlen );
03176 
03177         /*
03178          * 2.3: Compute and add the signature
03179          */
03180 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
03181         if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
03182         {
03183             /*
03184              * For TLS 1.2, we need to specify signature and hash algorithm
03185              * explicitly through a prefix to the signature.
03186              *
03187              * struct {
03188              *    HashAlgorithm hash;
03189              *    SignatureAlgorithm signature;
03190              * } SignatureAndHashAlgorithm;
03191              *
03192              * struct {
03193              *    SignatureAndHashAlgorithm algorithm;
03194              *    opaque signature<0..2^16-1>;
03195              * } DigitallySigned;
03196              *
03197              */
03198 
03199             ssl->out_msg[ssl->out_msglen++] =
03200                 mbedtls_ssl_hash_from_md_alg( md_alg );
03201             ssl->out_msg[ssl->out_msglen++] =
03202                 mbedtls_ssl_sig_from_pk_alg( sig_alg );
03203         }
03204 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
03205 
03206 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
03207         if( ssl->conf->f_async_sign_start != NULL )
03208         {
03209             ret = ssl->conf->f_async_sign_start( ssl,
03210                                                  mbedtls_ssl_own_cert( ssl ),
03211                                                  md_alg, hash, hashlen );
03212             switch( ret )
03213             {
03214             case MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH:
03215                 /* act as if f_async_sign was null */
03216                 break;
03217             case 0:
03218                 ssl->handshake->async_in_progress = 1;
03219                 return( ssl_resume_server_key_exchange( ssl, signature_len ) );
03220             case MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS:
03221                 ssl->handshake->async_in_progress = 1;
03222                 return( MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS );
03223             default:
03224                 MBEDTLS_SSL_DEBUG_RET( 1, "f_async_sign_start", ret );
03225                 return( ret );
03226             }
03227         }
03228 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
03229 
03230         if( mbedtls_ssl_own_key( ssl ) == NULL )
03231         {
03232             MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no private key" ) );
03233             return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );
03234         }
03235 
03236         /* Append the signature to ssl->out_msg, leaving 2 bytes for the
03237          * signature length which will be added in ssl_write_server_key_exchange
03238          * after the call to ssl_prepare_server_key_exchange.
03239          * ssl_write_server_key_exchange also takes care of incrementing
03240          * ssl->out_msglen. */
03241         if( ( ret = mbedtls_pk_sign( mbedtls_ssl_own_key( ssl ),
03242                                      md_alg, hash, hashlen,
03243                                      ssl->out_msg + ssl->out_msglen + 2,
03244                                      signature_len,
03245                                      ssl->conf->f_rng,
03246                                      ssl->conf->p_rng ) ) != 0 )
03247         {
03248             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_sign", ret );
03249             return( ret );
03250         }
03251     }
03252 #endif /* MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED */
03253 
03254     return( 0 );
03255 }
03256 
03257 /* Prepare the ServerKeyExchange message and send it. For ciphersuites
03258  * that do not include a ServerKeyExchange message, do nothing. Either
03259  * way, if successful, move on to the next step in the SSL state
03260  * machine. */
03261 static int ssl_write_server_key_exchange( mbedtls_ssl_context *ssl )
03262 {
03263     int ret;
03264     size_t signature_len = 0;
03265 #if defined(MBEDTLS_KEY_EXCHANGE__SOME_NON_PFS__ENABLED)
03266     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
03267                             ssl->transform_negotiate->ciphersuite_info;
03268 #endif /* MBEDTLS_KEY_EXCHANGE__SOME_NON_PFS__ENABLED */
03269 
03270     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write server key exchange" ) );
03271 
03272 #if defined(MBEDTLS_KEY_EXCHANGE__SOME_NON_PFS__ENABLED)
03273     /* Extract static ECDH parameters and abort if ServerKeyExchange
03274      * is not needed. */
03275     if( mbedtls_ssl_ciphersuite_no_pfs( ciphersuite_info ) )
03276     {
03277         /* For suites involving ECDH, extract DH parameters
03278          * from certificate at this point. */
03279 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__ECDH_ENABLED)
03280         if( mbedtls_ssl_ciphersuite_uses_ecdh( ciphersuite_info ) )
03281         {
03282             ssl_get_ecdh_params_from_cert( ssl );
03283         }
03284 #endif /* MBEDTLS_KEY_EXCHANGE__SOME__ECDH_ENABLED */
03285 
03286         /* Key exchanges not involving ephemeral keys don't use
03287          * ServerKeyExchange, so end here. */
03288         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write server key exchange" ) );
03289         ssl->state++;
03290         return( 0 );
03291     }
03292 #endif /* MBEDTLS_KEY_EXCHANGE__SOME_NON_PFS__ENABLED */
03293 
03294 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED) && \
03295     defined(MBEDTLS_SSL_ASYNC_PRIVATE)
03296     /* If we have already prepared the message and there is an ongoing
03297      * signature operation, resume signing. */
03298     if( ssl->handshake->async_in_progress != 0 )
03299     {
03300         MBEDTLS_SSL_DEBUG_MSG( 2, ( "resuming signature operation" ) );
03301         ret = ssl_resume_server_key_exchange( ssl, &signature_len );
03302     }
03303     else
03304 #endif /* defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED) &&
03305           defined(MBEDTLS_SSL_ASYNC_PRIVATE) */
03306     {
03307         /* ServerKeyExchange is needed. Prepare the message. */
03308         ret = ssl_prepare_server_key_exchange( ssl, &signature_len );
03309     }
03310 
03311     if( ret != 0 )
03312     {
03313         /* If we're starting to write a new message, set ssl->out_msglen
03314          * to 0. But if we're resuming after an asynchronous message,
03315          * out_msglen is the amount of data written so far and mst be
03316          * preserved. */
03317         if( ret == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS )
03318             MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write server key exchange (pending)" ) );
03319         else
03320             ssl->out_msglen = 0;
03321         return( ret );
03322     }
03323 
03324     /* If there is a signature, write its length.
03325      * ssl_prepare_server_key_exchange already wrote the signature
03326      * itself at its proper place in the output buffer. */
03327 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED)
03328     if( signature_len != 0 )
03329     {
03330         ssl->out_msg[ssl->out_msglen++] = (unsigned char)( signature_len >> 8 );
03331         ssl->out_msg[ssl->out_msglen++] = (unsigned char)( signature_len      );
03332 
03333         MBEDTLS_SSL_DEBUG_BUF( 3, "my signature",
03334                                ssl->out_msg + ssl->out_msglen,
03335                                signature_len );
03336 
03337         /* Skip over the already-written signature */
03338         ssl->out_msglen += signature_len;
03339     }
03340 #endif /* MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED */
03341 
03342     /* Add header and send. */
03343     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
03344     ssl->out_msg[0]  = MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE;
03345 
03346     ssl->state++;
03347 
03348     if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
03349     {
03350         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
03351         return( ret );
03352     }
03353 
03354     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write server key exchange" ) );
03355     return( 0 );
03356 }
03357 
03358 static int ssl_write_server_hello_done( mbedtls_ssl_context *ssl )
03359 {
03360     int ret;
03361 
03362     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write server hello done" ) );
03363 
03364     ssl->out_msglen  = 4;
03365     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
03366     ssl->out_msg[0]  = MBEDTLS_SSL_HS_SERVER_HELLO_DONE;
03367 
03368     ssl->state++;
03369 
03370 #if defined(MBEDTLS_SSL_PROTO_DTLS)
03371     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
03372         mbedtls_ssl_send_flight_completed( ssl );
03373 #endif
03374 
03375     if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
03376     {
03377         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
03378         return( ret );
03379     }
03380 
03381 #if defined(MBEDTLS_SSL_PROTO_DTLS)
03382     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
03383         ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 )
03384     {
03385         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flight_transmit", ret );
03386         return( ret );
03387     }
03388 #endif /* MBEDTLS_SSL_PROTO_DTLS */
03389 
03390     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write server hello done" ) );
03391 
03392     return( 0 );
03393 }
03394 
03395 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) ||                       \
03396     defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
03397 static int ssl_parse_client_dh_public( mbedtls_ssl_context *ssl, unsigned char **p,
03398                                        const unsigned char *end )
03399 {
03400     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
03401     size_t n;
03402 
03403     /*
03404      * Receive G^Y mod P, premaster = (G^Y)^X mod P
03405      */
03406     if( *p + 2 > end )
03407     {
03408         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
03409         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
03410     }
03411 
03412     n = ( (*p)[0] << 8 ) | (*p)[1];
03413     *p += 2;
03414 
03415     if( *p + n > end )
03416     {
03417         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
03418         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
03419     }
03420 
03421     if( ( ret = mbedtls_dhm_read_public( &ssl->handshake->dhm_ctx, *p, n ) ) != 0 )
03422     {
03423         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_read_public", ret );
03424         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP );
03425     }
03426 
03427     *p += n;
03428 
03429     MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: GY", &ssl->handshake->dhm_ctx.GY );
03430 
03431     return( ret );
03432 }
03433 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
03434           MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
03435 
03436 #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) ||                           \
03437     defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
03438 
03439 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
03440 static int ssl_resume_decrypt_pms( mbedtls_ssl_context *ssl,
03441                                    unsigned char *peer_pms,
03442                                    size_t *peer_pmslen,
03443                                    size_t peer_pmssize )
03444 {
03445     int ret = ssl->conf->f_async_resume( ssl,
03446                                          peer_pms, peer_pmslen, peer_pmssize );
03447     if( ret != MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS )
03448     {
03449         ssl->handshake->async_in_progress = 0;
03450         mbedtls_ssl_set_async_operation_data( ssl, NULL );
03451     }
03452     MBEDTLS_SSL_DEBUG_RET( 2, "ssl_decrypt_encrypted_pms", ret );
03453     return( ret );
03454 }
03455 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
03456 
03457 static int ssl_decrypt_encrypted_pms( mbedtls_ssl_context *ssl,
03458                                       const unsigned char *p,
03459                                       const unsigned char *end,
03460                                       unsigned char *peer_pms,
03461                                       size_t *peer_pmslen,
03462                                       size_t peer_pmssize )
03463 {
03464     int ret;
03465     mbedtls_pk_context *private_key = mbedtls_ssl_own_key( ssl );
03466     mbedtls_pk_context *public_key = &mbedtls_ssl_own_cert( ssl )->pk;
03467     size_t len = mbedtls_pk_get_len( public_key );
03468 
03469 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
03470     /* If we have already started decoding the message and there is an ongoing
03471      * decryption operation, resume signing. */
03472     if( ssl->handshake->async_in_progress != 0 )
03473     {
03474         MBEDTLS_SSL_DEBUG_MSG( 2, ( "resuming decryption operation" ) );
03475         return( ssl_resume_decrypt_pms( ssl,
03476                                         peer_pms, peer_pmslen, peer_pmssize ) );
03477     }
03478 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
03479 
03480     /*
03481      * Prepare to decrypt the premaster using own private RSA key
03482      */
03483 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
03484     defined(MBEDTLS_SSL_PROTO_TLS1_2)
03485     if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_0 )
03486     {
03487         if ( p + 2 > end ) {
03488             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
03489             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
03490         }
03491         if( *p++ != ( ( len >> 8 ) & 0xFF ) ||
03492             *p++ != ( ( len      ) & 0xFF ) )
03493         {
03494             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
03495             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
03496         }
03497     }
03498 #endif
03499 
03500     if( p + len != end )
03501     {
03502         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
03503         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
03504     }
03505 
03506     /*
03507      * Decrypt the premaster secret
03508      */
03509 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
03510     if( ssl->conf->f_async_decrypt_start != NULL )
03511     {
03512         ret = ssl->conf->f_async_decrypt_start( ssl,
03513                                                 mbedtls_ssl_own_cert( ssl ),
03514                                                 p, len );
03515         switch( ret )
03516         {
03517         case MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH:
03518             /* act as if f_async_decrypt_start was null */
03519             break;
03520         case 0:
03521             ssl->handshake->async_in_progress = 1;
03522             return( ssl_resume_decrypt_pms( ssl,
03523                                             peer_pms,
03524                                             peer_pmslen,
03525                                             peer_pmssize ) );
03526         case MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS:
03527             ssl->handshake->async_in_progress = 1;
03528             return( MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS );
03529         default:
03530             MBEDTLS_SSL_DEBUG_RET( 1, "f_async_decrypt_start", ret );
03531             return( ret );
03532         }
03533     }
03534 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
03535 
03536     if( ! mbedtls_pk_can_do( private_key, MBEDTLS_PK_RSA ) )
03537     {
03538         MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no RSA private key" ) );
03539         return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );
03540     }
03541 
03542     ret = mbedtls_pk_decrypt( private_key, p, len,
03543                               peer_pms, peer_pmslen, peer_pmssize,
03544                               ssl->conf->f_rng, ssl->conf->p_rng );
03545     return( ret );
03546 }
03547 
03548 static int ssl_parse_encrypted_pms( mbedtls_ssl_context *ssl,
03549                                     const unsigned char *p,
03550                                     const unsigned char *end,
03551                                     size_t pms_offset )
03552 {
03553     int ret;
03554     unsigned char *pms = ssl->handshake->premaster + pms_offset;
03555     unsigned char ver[2];
03556     unsigned char fake_pms[48], peer_pms[48];
03557     unsigned char mask;
03558     size_t i, peer_pmslen;
03559     unsigned int diff;
03560 
03561     /* In case of a failure in decryption, the decryption may write less than
03562      * 2 bytes of output, but we always read the first two bytes. It doesn't
03563      * matter in the end because diff will be nonzero in that case due to
03564      * peer_pmslen being less than 48, and we only care whether diff is 0.
03565      * But do initialize peer_pms for robustness anyway. This also makes
03566      * memory analyzers happy (don't access uninitialized memory, even
03567      * if it's an unsigned char). */
03568     peer_pms[0] = peer_pms[1] = ~0;
03569 
03570     ret = ssl_decrypt_encrypted_pms( ssl, p, end,
03571                                      peer_pms,
03572                                      &peer_pmslen,
03573                                      sizeof( peer_pms ) );
03574 
03575 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
03576     if ( ret == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS )
03577         return( ret );
03578 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
03579 
03580     mbedtls_ssl_write_version( ssl->handshake->max_major_ver,
03581                                ssl->handshake->max_minor_ver,
03582                                ssl->conf->transport, ver );
03583 
03584     /* Avoid data-dependent branches while checking for invalid
03585      * padding, to protect against timing-based Bleichenbacher-type
03586      * attacks. */
03587     diff  = (unsigned int) ret;
03588     diff |= peer_pmslen ^ 48;
03589     diff |= peer_pms[0] ^ ver[0];
03590     diff |= peer_pms[1] ^ ver[1];
03591 
03592     /* mask = diff ? 0xff : 0x00 using bit operations to avoid branches */
03593     /* MSVC has a warning about unary minus on unsigned, but this is
03594      * well-defined and precisely what we want to do here */
03595 #if defined(_MSC_VER)
03596 #pragma warning( push )
03597 #pragma warning( disable : 4146 )
03598 #endif
03599     mask = - ( ( diff | - diff ) >> ( sizeof( unsigned int ) * 8 - 1 ) );
03600 #if defined(_MSC_VER)
03601 #pragma warning( pop )
03602 #endif
03603 
03604     /*
03605      * Protection against Bleichenbacher's attack: invalid PKCS#1 v1.5 padding
03606      * must not cause the connection to end immediately; instead, send a
03607      * bad_record_mac later in the handshake.
03608      * To protect against timing-based variants of the attack, we must
03609      * not have any branch that depends on whether the decryption was
03610      * successful. In particular, always generate the fake premaster secret,
03611      * regardless of whether it will ultimately influence the output or not.
03612      */
03613     ret = ssl->conf->f_rng( ssl->conf->p_rng, fake_pms, sizeof( fake_pms ) );
03614     if( ret != 0 )
03615     {
03616         /* It's ok to abort on an RNG failure, since this does not reveal
03617          * anything about the RSA decryption. */
03618         return( ret );
03619     }
03620 
03621 #if defined(MBEDTLS_SSL_DEBUG_ALL)
03622     if( diff != 0 )
03623         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
03624 #endif
03625 
03626     if( sizeof( ssl->handshake->premaster ) < pms_offset ||
03627         sizeof( ssl->handshake->premaster ) - pms_offset < 48 )
03628     {
03629         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
03630         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
03631     }
03632     ssl->handshake->pmslen = 48;
03633 
03634     /* Set pms to either the true or the fake PMS, without
03635      * data-dependent branches. */
03636     for( i = 0; i < ssl->handshake->pmslen; i++ )
03637         pms[i] = ( mask & fake_pms[i] ) | ( (~mask) & peer_pms[i] );
03638 
03639     return( 0 );
03640 }
03641 #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED ||
03642           MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
03643 
03644 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
03645 static int ssl_parse_client_psk_identity( mbedtls_ssl_context *ssl, unsigned char **p,
03646                                           const unsigned char *end )
03647 {
03648     int ret = 0;
03649     size_t n;
03650 
03651     if( ssl->conf->f_psk == NULL &&
03652         ( ssl->conf->psk == NULL || ssl->conf->psk_identity == NULL ||
03653           ssl->conf->psk_identity_len == 0 || ssl->conf->psk_len == 0 ) )
03654     {
03655         MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no pre-shared key" ) );
03656         return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );
03657     }
03658 
03659     /*
03660      * Receive client pre-shared key identity name
03661      */
03662     if( end - *p < 2 )
03663     {
03664         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
03665         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
03666     }
03667 
03668     n = ( (*p)[0] << 8 ) | (*p)[1];
03669     *p += 2;
03670 
03671     if( n < 1 || n > 65535 || n > (size_t) ( end - *p ) )
03672     {
03673         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
03674         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
03675     }
03676 
03677     if( ssl->conf->f_psk != NULL )
03678     {
03679         if( ssl->conf->f_psk( ssl->conf->p_psk, ssl, *p, n ) != 0 )
03680             ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;
03681     }
03682     else
03683     {
03684         /* Identity is not a big secret since clients send it in the clear,
03685          * but treat it carefully anyway, just in case */
03686         if( n != ssl->conf->psk_identity_len ||
03687             mbedtls_ssl_safer_memcmp( ssl->conf->psk_identity, *p, n ) != 0 )
03688         {
03689             ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;
03690         }
03691     }
03692 
03693     if( ret == MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY )
03694     {
03695         MBEDTLS_SSL_DEBUG_BUF( 3, "Unknown PSK identity", *p, n );
03696         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
03697                                         MBEDTLS_SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY );
03698         return( MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY );
03699     }
03700 
03701     *p += n;
03702 
03703     return( 0 );
03704 }
03705 #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
03706 
03707 static int ssl_parse_client_key_exchange( mbedtls_ssl_context *ssl )
03708 {
03709     int ret;
03710     const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
03711     unsigned char *p, *end;
03712 
03713     ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
03714 
03715     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse client key exchange" ) );
03716 
03717 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE) && \
03718     ( defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \
03719       defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) )
03720     if( ( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
03721           ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA ) &&
03722         ( ssl->handshake->async_in_progress != 0 ) )
03723     {
03724         /* We've already read a record and there is an asynchronous
03725          * operation in progress to decrypt it. So skip reading the
03726          * record. */
03727         MBEDTLS_SSL_DEBUG_MSG( 3, ( "will resume decryption of previously-read record" ) );
03728     }
03729     else
03730 #endif
03731     if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
03732     {
03733         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
03734         return( ret );
03735     }
03736 
03737     p = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
03738     end = ssl->in_msg + ssl->in_hslen;
03739 
03740     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
03741     {
03742         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
03743         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
03744     }
03745 
03746     if( ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_KEY_EXCHANGE )
03747     {
03748         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
03749         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
03750     }
03751 
03752 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)
03753     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA )
03754     {
03755         if( ( ret = ssl_parse_client_dh_public( ssl, &p, end ) ) != 0 )
03756         {
03757             MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_dh_public" ), ret );
03758             return( ret );
03759         }
03760 
03761         if( p != end )
03762         {
03763             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange" ) );
03764             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
03765         }
03766 
03767         if( ( ret = mbedtls_dhm_calc_secret( &ssl->handshake->dhm_ctx,
03768                                       ssl->handshake->premaster,
03769                                       MBEDTLS_PREMASTER_SIZE,
03770                                      &ssl->handshake->pmslen,
03771                                       ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
03772         {
03773             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_calc_secret", ret );
03774             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_CS );
03775         }
03776 
03777         MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: K ", &ssl->handshake->dhm_ctx.K  );
03778     }
03779     else
03780 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED */
03781 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||                     \
03782     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) ||                   \
03783     defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||                      \
03784     defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
03785     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
03786         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA ||
03787         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||
03788         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA )
03789     {
03790         if( ( ret = mbedtls_ecdh_read_public( &ssl->handshake->ecdh_ctx,
03791                                       p, end - p) ) != 0 )
03792         {
03793             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_read_public", ret );
03794             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP );
03795         }
03796 
03797         MBEDTLS_SSL_DEBUG_ECP( 3, "ECDH: Qp ", &ssl->handshake->ecdh_ctx.Qp );
03798 
03799         if( ( ret = mbedtls_ecdh_calc_secret( &ssl->handshake->ecdh_ctx,
03800                                       &ssl->handshake->pmslen,
03801                                        ssl->handshake->premaster,
03802                                        MBEDTLS_MPI_MAX_SIZE,
03803                                        ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
03804         {
03805             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_calc_secret", ret );
03806             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_CS );
03807         }
03808 
03809         MBEDTLS_SSL_DEBUG_MPI( 3, "ECDH: z  ", &ssl->handshake->ecdh_ctx.z );
03810     }
03811     else
03812 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
03813           MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
03814           MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
03815           MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
03816 #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
03817     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK )
03818     {
03819         if( ( ret = ssl_parse_client_psk_identity( ssl, &p, end ) ) != 0 )
03820         {
03821             MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_psk_identity" ), ret );
03822             return( ret );
03823         }
03824 
03825         if( p != end )
03826         {
03827             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange" ) );
03828             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
03829         }
03830 
03831         if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl,
03832                         ciphersuite_info->key_exchange ) ) != 0 )
03833         {
03834             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_psk_derive_premaster", ret );
03835             return( ret );
03836         }
03837     }
03838     else
03839 #endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */
03840 #if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
03841     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
03842     {
03843 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
03844         if ( ssl->handshake->async_in_progress != 0 )
03845         {
03846             /* There is an asynchronous operation in progress to
03847              * decrypt the encrypted premaster secret, so skip
03848              * directly to resuming this operation. */
03849             MBEDTLS_SSL_DEBUG_MSG( 3, ( "PSK identity already parsed" ) );
03850             /* Update p to skip the PSK identity. ssl_parse_encrypted_pms
03851              * won't actually use it, but maintain p anyway for robustness. */
03852             p += ssl->conf->psk_identity_len + 2;
03853         }
03854         else
03855 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
03856         if( ( ret = ssl_parse_client_psk_identity( ssl, &p, end ) ) != 0 )
03857         {
03858             MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_psk_identity" ), ret );
03859             return( ret );
03860         }
03861 
03862         if( ( ret = ssl_parse_encrypted_pms( ssl, p, end, 2 ) ) != 0 )
03863         {
03864             MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_encrypted_pms" ), ret );
03865             return( ret );
03866         }
03867 
03868         if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl,
03869                         ciphersuite_info->key_exchange ) ) != 0 )
03870         {
03871             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_psk_derive_premaster", ret );
03872             return( ret );
03873         }
03874     }
03875     else
03876 #endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
03877 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
03878     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
03879     {
03880         if( ( ret = ssl_parse_client_psk_identity( ssl, &p, end ) ) != 0 )
03881         {
03882             MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_psk_identity" ), ret );
03883             return( ret );
03884         }
03885         if( ( ret = ssl_parse_client_dh_public( ssl, &p, end ) ) != 0 )
03886         {
03887             MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_dh_public" ), ret );
03888             return( ret );
03889         }
03890 
03891         if( p != end )
03892         {
03893             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange" ) );
03894             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
03895         }
03896 
03897         if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl,
03898                         ciphersuite_info->key_exchange ) ) != 0 )
03899         {
03900             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_psk_derive_premaster", ret );
03901             return( ret );
03902         }
03903     }
03904     else
03905 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
03906 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
03907     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
03908     {
03909         if( ( ret = ssl_parse_client_psk_identity( ssl, &p, end ) ) != 0 )
03910         {
03911             MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_psk_identity" ), ret );
03912             return( ret );
03913         }
03914 
03915         if( ( ret = mbedtls_ecdh_read_public( &ssl->handshake->ecdh_ctx,
03916                                        p, end - p ) ) != 0 )
03917         {
03918             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_read_public", ret );
03919             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP );
03920         }
03921 
03922         MBEDTLS_SSL_DEBUG_ECP( 3, "ECDH: Qp ", &ssl->handshake->ecdh_ctx.Qp );
03923 
03924         if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl,
03925                         ciphersuite_info->key_exchange ) ) != 0 )
03926         {
03927             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_psk_derive_premaster", ret );
03928             return( ret );
03929         }
03930     }
03931     else
03932 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
03933 #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
03934     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA )
03935     {
03936         if( ( ret = ssl_parse_encrypted_pms( ssl, p, end, 0 ) ) != 0 )
03937         {
03938             MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_parse_encrypted_pms_secret" ), ret );
03939             return( ret );
03940         }
03941     }
03942     else
03943 #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */
03944 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
03945     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
03946     {
03947         ret = mbedtls_ecjpake_read_round_two( &ssl->handshake->ecjpake_ctx,
03948                                               p, end - p );
03949         if( ret != 0 )
03950         {
03951             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_two", ret );
03952             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
03953         }
03954 
03955         ret = mbedtls_ecjpake_derive_secret( &ssl->handshake->ecjpake_ctx,
03956                 ssl->handshake->premaster, 32, &ssl->handshake->pmslen,
03957                 ssl->conf->f_rng, ssl->conf->p_rng );
03958         if( ret != 0 )
03959         {
03960             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_derive_secret", ret );
03961             return( ret );
03962         }
03963     }
03964     else
03965 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
03966     {
03967         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
03968         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
03969     }
03970 
03971     if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )
03972     {
03973         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret );
03974         return( ret );
03975     }
03976 
03977     ssl->state++;
03978 
03979     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse client key exchange" ) );
03980 
03981     return( 0 );
03982 }
03983 
03984 #if !defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)       && \
03985     !defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)   && \
03986     !defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED)  && \
03987     !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) && \
03988     !defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)&& \
03989     !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
03990 static int ssl_parse_certificate_verify( mbedtls_ssl_context *ssl )
03991 {
03992     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
03993         ssl->transform_negotiate->ciphersuite_info;
03994 
03995     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate verify" ) );
03996 
03997     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
03998         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
03999         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
04000         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
04001         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
04002     {
04003         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate verify" ) );
04004         ssl->state++;
04005         return( 0 );
04006     }
04007 
04008     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
04009     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
04010 }
04011 #else
04012 static int ssl_parse_certificate_verify( mbedtls_ssl_context *ssl )
04013 {
04014     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
04015     size_t i, sig_len;
04016     unsigned char hash[48];
04017     unsigned char *hash_start = hash;
04018     size_t hashlen;
04019 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
04020     mbedtls_pk_type_t pk_alg;
04021 #endif
04022     mbedtls_md_type_t md_alg;
04023     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
04024         ssl->transform_negotiate->ciphersuite_info;
04025 
04026     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate verify" ) );
04027 
04028     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
04029         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
04030         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
04031         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
04032         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE ||
04033         ssl->session_negotiate->peer_cert == NULL )
04034     {
04035         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate verify" ) );
04036         ssl->state++;
04037         return( 0 );
04038     }
04039 
04040     /* Read the message without adding it to the checksum */
04041     ret = mbedtls_ssl_read_record( ssl, 0 /* no checksum update */ );
04042     if( 0 != ret )
04043     {
04044         MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ssl_read_record" ), ret );
04045         return( ret );
04046     }
04047 
04048     ssl->state++;
04049 
04050     /* Process the message contents */
04051     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ||
04052         ssl->in_msg[0] != MBEDTLS_SSL_HS_CERTIFICATE_VERIFY )
04053     {
04054         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate verify message" ) );
04055         return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY );
04056     }
04057 
04058     i = mbedtls_ssl_hs_hdr_len( ssl );
04059 
04060     /*
04061      *  struct {
04062      *     SignatureAndHashAlgorithm algorithm; -- TLS 1.2 only
04063      *     opaque signature<0..2^16-1>;
04064      *  } DigitallySigned;
04065      */
04066 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
04067     defined(MBEDTLS_SSL_PROTO_TLS1_1)
04068     if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
04069     {
04070         md_alg = MBEDTLS_MD_NONE;
04071         hashlen = 36;
04072 
04073         /* For ECDSA, use SHA-1, not MD-5 + SHA-1 */
04074         if( mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk,
04075                         MBEDTLS_PK_ECDSA ) )
04076         {
04077             hash_start += 16;
04078             hashlen -= 16;
04079             md_alg = MBEDTLS_MD_SHA1;
04080         }
04081     }
04082     else
04083 #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 ||
04084           MBEDTLS_SSL_PROTO_TLS1_1 */
04085 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
04086     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
04087     {
04088         if( i + 2 > ssl->in_hslen )
04089         {
04090             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate verify message" ) );
04091             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY );
04092         }
04093 
04094         /*
04095          * Hash
04096          */
04097         md_alg = mbedtls_ssl_md_alg_from_hash( ssl->in_msg[i] );
04098 
04099         if( md_alg == MBEDTLS_MD_NONE || mbedtls_ssl_set_calc_verify_md( ssl, ssl->in_msg[i] ) )
04100         {
04101             MBEDTLS_SSL_DEBUG_MSG( 1, ( "peer not adhering to requested sig_alg"
04102                                 " for verify message" ) );
04103             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY );
04104         }
04105 
04106 #if !defined(MBEDTLS_MD_SHA1)
04107         if( MBEDTLS_MD_SHA1 == md_alg )
04108             hash_start += 16;
04109 #endif
04110 
04111         /* Info from md_alg will be used instead */
04112         hashlen = 0;
04113 
04114         i++;
04115 
04116         /*
04117          * Signature
04118          */
04119         if( ( pk_alg = mbedtls_ssl_pk_alg_from_sig( ssl->in_msg[i] ) )
04120                         == MBEDTLS_PK_NONE )
04121         {
04122             MBEDTLS_SSL_DEBUG_MSG( 1, ( "peer not adhering to requested sig_alg"
04123                                 " for verify message" ) );
04124             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY );
04125         }
04126 
04127         /*
04128          * Check the certificate's key type matches the signature alg
04129          */
04130         if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk, pk_alg ) )
04131         {
04132             MBEDTLS_SSL_DEBUG_MSG( 1, ( "sig_alg doesn't match cert key" ) );
04133             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY );
04134         }
04135 
04136         i++;
04137     }
04138     else
04139 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
04140     {
04141         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
04142         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
04143     }
04144 
04145     if( i + 2 > ssl->in_hslen )
04146     {
04147         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate verify message" ) );
04148         return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY );
04149     }
04150 
04151     sig_len = ( ssl->in_msg[i] << 8 ) | ssl->in_msg[i+1];
04152     i += 2;
04153 
04154     if( i + sig_len != ssl->in_hslen )
04155     {
04156         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate verify message" ) );
04157         return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY );
04158     }
04159 
04160     /* Calculate hash and verify signature */
04161     ssl->handshake->calc_verify( ssl, hash );
04162 
04163     if( ( ret = mbedtls_pk_verify( &ssl->session_negotiate->peer_cert->pk,
04164                            md_alg, hash_start, hashlen,
04165                            ssl->in_msg + i, sig_len ) ) != 0 )
04166     {
04167         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_verify", ret );
04168         return( ret );
04169     }
04170 
04171     mbedtls_ssl_update_handshake_status( ssl );
04172 
04173     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse certificate verify" ) );
04174 
04175     return( ret );
04176 }
04177 #endif /* !MBEDTLS_KEY_EXCHANGE_RSA_ENABLED &&
04178           !MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED &&
04179           !MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED &&
04180           !MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED &&
04181           !MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED &&
04182           !MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
04183 
04184 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
04185 static int ssl_write_new_session_ticket( mbedtls_ssl_context *ssl )
04186 {
04187     int ret;
04188     size_t tlen;
04189     uint32_t lifetime;
04190 
04191     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write new session ticket" ) );
04192 
04193     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
04194     ssl->out_msg[0]  = MBEDTLS_SSL_HS_NEW_SESSION_TICKET;
04195 
04196     /*
04197      * struct {
04198      *     uint32 ticket_lifetime_hint;
04199      *     opaque ticket<0..2^16-1>;
04200      * } NewSessionTicket;
04201      *
04202      * 4  .  7   ticket_lifetime_hint (0 = unspecified)
04203      * 8  .  9   ticket_len (n)
04204      * 10 .  9+n ticket content
04205      */
04206 
04207     if( ( ret = ssl->conf->f_ticket_write( ssl->conf->p_ticket,
04208                                 ssl->session_negotiate,
04209                                 ssl->out_msg + 10,
04210                                 ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN,
04211                                 &tlen, &lifetime ) ) != 0 )
04212     {
04213         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_ticket_write", ret );
04214         tlen = 0;
04215     }
04216 
04217     ssl->out_msg[4] = ( lifetime >> 24 ) & 0xFF;
04218     ssl->out_msg[5] = ( lifetime >> 16 ) & 0xFF;
04219     ssl->out_msg[6] = ( lifetime >>  8 ) & 0xFF;
04220     ssl->out_msg[7] = ( lifetime       ) & 0xFF;
04221 
04222     ssl->out_msg[8] = (unsigned char)( ( tlen >> 8 ) & 0xFF );
04223     ssl->out_msg[9] = (unsigned char)( ( tlen      ) & 0xFF );
04224 
04225     ssl->out_msglen = 10 + tlen;
04226 
04227     /*
04228      * Morally equivalent to updating ssl->state, but NewSessionTicket and
04229      * ChangeCipherSpec share the same state.
04230      */
04231     ssl->handshake->new_session_ticket = 0;
04232 
04233     if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
04234     {
04235         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
04236         return( ret );
04237     }
04238 
04239     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write new session ticket" ) );
04240 
04241     return( 0 );
04242 }
04243 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
04244 
04245 /*
04246  * SSL handshake -- server side -- single step
04247  */
04248 int mbedtls_ssl_handshake_server_step( mbedtls_ssl_context *ssl )
04249 {
04250     int ret = 0;
04251 
04252     if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER || ssl->handshake == NULL )
04253         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
04254 
04255     MBEDTLS_SSL_DEBUG_MSG( 2, ( "server state: %d", ssl->state ) );
04256 
04257     if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
04258         return( ret );
04259 
04260 #if defined(MBEDTLS_SSL_PROTO_DTLS)
04261     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
04262         ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING )
04263     {
04264         if( ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 )
04265             return( ret );
04266     }
04267 #endif /* MBEDTLS_SSL_PROTO_DTLS */
04268 
04269     switch( ssl->state )
04270     {
04271         case MBEDTLS_SSL_HELLO_REQUEST:
04272             ssl->state = MBEDTLS_SSL_CLIENT_HELLO;
04273             break;
04274 
04275         /*
04276          *  <==   ClientHello
04277          */
04278         case MBEDTLS_SSL_CLIENT_HELLO:
04279             ret = ssl_parse_client_hello( ssl );
04280             break;
04281 
04282 #if defined(MBEDTLS_SSL_PROTO_DTLS)
04283         case MBEDTLS_SSL_SERVER_HELLO_VERIFY_REQUEST_SENT:
04284             return( MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED );
04285 #endif
04286 
04287         /*
04288          *  ==>   ServerHello
04289          *        Certificate
04290          *      ( ServerKeyExchange  )
04291          *      ( CertificateRequest )
04292          *        ServerHelloDone
04293          */
04294         case MBEDTLS_SSL_SERVER_HELLO:
04295             ret = ssl_write_server_hello( ssl );
04296             break;
04297 
04298         case MBEDTLS_SSL_SERVER_CERTIFICATE:
04299             ret = mbedtls_ssl_write_certificate( ssl );
04300             break;
04301 
04302         case MBEDTLS_SSL_SERVER_KEY_EXCHANGE:
04303             ret = ssl_write_server_key_exchange( ssl );
04304             break;
04305 
04306         case MBEDTLS_SSL_CERTIFICATE_REQUEST:
04307             ret = ssl_write_certificate_request( ssl );
04308             break;
04309 
04310         case MBEDTLS_SSL_SERVER_HELLO_DONE:
04311             ret = ssl_write_server_hello_done( ssl );
04312             break;
04313 
04314         /*
04315          *  <== ( Certificate/Alert  )
04316          *        ClientKeyExchange
04317          *      ( CertificateVerify  )
04318          *        ChangeCipherSpec
04319          *        Finished
04320          */
04321         case MBEDTLS_SSL_CLIENT_CERTIFICATE:
04322             ret = mbedtls_ssl_parse_certificate( ssl );
04323             break;
04324 
04325         case MBEDTLS_SSL_CLIENT_KEY_EXCHANGE:
04326             ret = ssl_parse_client_key_exchange( ssl );
04327             break;
04328 
04329         case MBEDTLS_SSL_CERTIFICATE_VERIFY:
04330             ret = ssl_parse_certificate_verify( ssl );
04331             break;
04332 
04333         case MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC:
04334             ret = mbedtls_ssl_parse_change_cipher_spec( ssl );
04335             break;
04336 
04337         case MBEDTLS_SSL_CLIENT_FINISHED:
04338             ret = mbedtls_ssl_parse_finished( ssl );
04339             break;
04340 
04341         /*
04342          *  ==> ( NewSessionTicket )
04343          *        ChangeCipherSpec
04344          *        Finished
04345          */
04346         case MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC:
04347 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
04348             if( ssl->handshake->new_session_ticket != 0 )
04349                 ret = ssl_write_new_session_ticket( ssl );
04350             else
04351 #endif
04352                 ret = mbedtls_ssl_write_change_cipher_spec( ssl );
04353             break;
04354 
04355         case MBEDTLS_SSL_SERVER_FINISHED:
04356             ret = mbedtls_ssl_write_finished( ssl );
04357             break;
04358 
04359         case MBEDTLS_SSL_FLUSH_BUFFERS:
04360             MBEDTLS_SSL_DEBUG_MSG( 2, ( "handshake: done" ) );
04361             ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
04362             break;
04363 
04364         case MBEDTLS_SSL_HANDSHAKE_WRAPUP:
04365             mbedtls_ssl_handshake_wrapup( ssl );
04366             break;
04367 
04368         default:
04369             MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid state %d", ssl->state ) );
04370             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
04371     }
04372 
04373     return( ret );
04374 }
04375 #endif /* MBEDTLS_SSL_SRV_C */