Chuck Swiger / WNCInterface2

Dependencies:   WncControllerK64F

Fork of WNCInterface by Avnet

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