joey shelton / LED_Demo

Dependencies:   MAX44000 PWM_Tone_Library nexpaq_mdk

Fork of LED_Demo by Maxim nexpaq

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers ssl_cli.c Source File

ssl_cli.c

00001 /*
00002  *  SSLv3/TLSv1 client-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_CLI_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 #define mbedtls_time      time
00037 #define mbedtls_time_t    time_t
00038 #endif
00039 
00040 #include "mbedtls/debug.h"
00041 #include "mbedtls/ssl.h"
00042 #include "mbedtls/ssl_internal.h"
00043 
00044 #include <string.h>
00045 
00046 #include <stdint.h>
00047 
00048 #if defined(MBEDTLS_HAVE_TIME)
00049 #include <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_SERVER_NAME_INDICATION)
00060 static void ssl_write_hostname_ext( mbedtls_ssl_context *ssl,
00061                                     unsigned char *buf,
00062                                     size_t *olen )
00063 {
00064     unsigned char *p = buf;
00065     const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
00066     size_t hostname_len;
00067 
00068     *olen = 0;
00069 
00070     if( ssl->hostname == NULL )
00071         return;
00072 
00073     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding server name extension: %s",
00074                    ssl->hostname ) );
00075 
00076     hostname_len = strlen( ssl->hostname );
00077 
00078     if( end < p || (size_t)( end - p ) < hostname_len + 9 )
00079     {
00080         MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
00081         return;
00082     }
00083 
00084     /*
00085      * struct {
00086      *     NameType name_type;
00087      *     select (name_type) {
00088      *         case host_name: HostName;
00089      *     } name;
00090      * } ServerName;
00091      *
00092      * enum {
00093      *     host_name(0), (255)
00094      * } NameType;
00095      *
00096      * opaque HostName<1..2^16-1>;
00097      *
00098      * struct {
00099      *     ServerName server_name_list<1..2^16-1>
00100      * } ServerNameList;
00101      */
00102     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SERVERNAME >> 8 ) & 0xFF );
00103     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SERVERNAME      ) & 0xFF );
00104 
00105     *p++ = (unsigned char)( ( (hostname_len + 5) >> 8 ) & 0xFF );
00106     *p++ = (unsigned char)( ( (hostname_len + 5)      ) & 0xFF );
00107 
00108     *p++ = (unsigned char)( ( (hostname_len + 3) >> 8 ) & 0xFF );
00109     *p++ = (unsigned char)( ( (hostname_len + 3)      ) & 0xFF );
00110 
00111     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SERVERNAME_HOSTNAME ) & 0xFF );
00112     *p++ = (unsigned char)( ( hostname_len >> 8 ) & 0xFF );
00113     *p++ = (unsigned char)( ( hostname_len      ) & 0xFF );
00114 
00115     memcpy( p, ssl->hostname, hostname_len );
00116 
00117     *olen = hostname_len + 9;
00118 }
00119 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
00120 
00121 #if defined(MBEDTLS_SSL_RENEGOTIATION)
00122 static void ssl_write_renegotiation_ext( mbedtls_ssl_context *ssl,
00123                                          unsigned char *buf,
00124                                          size_t *olen )
00125 {
00126     unsigned char *p = buf;
00127     const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
00128 
00129     *olen = 0;
00130 
00131     if( ssl->renego_status != MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
00132         return;
00133 
00134     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding renegotiation extension" ) );
00135 
00136     if( end < p || (size_t)( end - p ) < 5 + ssl->verify_data_len )
00137     {
00138         MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
00139         return;
00140     }
00141 
00142     /*
00143      * Secure renegotiation
00144      */
00145     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO >> 8 ) & 0xFF );
00146     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO      ) & 0xFF );
00147 
00148     *p++ = 0x00;
00149     *p++ = ( ssl->verify_data_len + 1 ) & 0xFF;
00150     *p++ = ssl->verify_data_len & 0xFF;
00151 
00152     memcpy( p, ssl->own_verify_data, ssl->verify_data_len );
00153 
00154     *olen = 5 + ssl->verify_data_len;
00155 }
00156 #endif /* MBEDTLS_SSL_RENEGOTIATION */
00157 
00158 /*
00159  * Only if we handle at least one key exchange that needs signatures.
00160  */
00161 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
00162     defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
00163 static void ssl_write_signature_algorithms_ext( mbedtls_ssl_context *ssl,
00164                                                 unsigned char *buf,
00165                                                 size_t *olen )
00166 {
00167     unsigned char *p = buf;
00168     const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
00169     size_t sig_alg_len = 0;
00170     const int *md;
00171 #if defined(MBEDTLS_RSA_C) || defined(MBEDTLS_ECDSA_C)
00172     unsigned char *sig_alg_list = buf + 6;
00173 #endif
00174 
00175     *olen = 0;
00176 
00177     if( ssl->conf->max_minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
00178         return;
00179 
00180     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding signature_algorithms extension" ) );
00181 
00182     for( md = ssl->conf->sig_hashes; *md != MBEDTLS_MD_NONE; md++ )
00183     {
00184 #if defined(MBEDTLS_ECDSA_C)
00185         sig_alg_len += 2;
00186 #endif
00187 #if defined(MBEDTLS_RSA_C)
00188         sig_alg_len += 2;
00189 #endif
00190     }
00191 
00192     if( end < p || (size_t)( end - p ) < sig_alg_len + 6 )
00193     {
00194         MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
00195         return;
00196     }
00197 
00198     /*
00199      * Prepare signature_algorithms extension (TLS 1.2)
00200      */
00201     sig_alg_len = 0;
00202 
00203     for( md = ssl->conf->sig_hashes; *md != MBEDTLS_MD_NONE; md++ )
00204     {
00205 #if defined(MBEDTLS_ECDSA_C)
00206         sig_alg_list[sig_alg_len++] = mbedtls_ssl_hash_from_md_alg( *md );
00207         sig_alg_list[sig_alg_len++] = MBEDTLS_SSL_SIG_ECDSA;
00208 #endif
00209 #if defined(MBEDTLS_RSA_C)
00210         sig_alg_list[sig_alg_len++] = mbedtls_ssl_hash_from_md_alg( *md );
00211         sig_alg_list[sig_alg_len++] = MBEDTLS_SSL_SIG_RSA;
00212 #endif
00213     }
00214 
00215     /*
00216      * enum {
00217      *     none(0), md5(1), sha1(2), sha224(3), sha256(4), sha384(5),
00218      *     sha512(6), (255)
00219      * } HashAlgorithm;
00220      *
00221      * enum { anonymous(0), rsa(1), dsa(2), ecdsa(3), (255) }
00222      *   SignatureAlgorithm;
00223      *
00224      * struct {
00225      *     HashAlgorithm hash;
00226      *     SignatureAlgorithm signature;
00227      * } SignatureAndHashAlgorithm;
00228      *
00229      * SignatureAndHashAlgorithm
00230      *   supported_signature_algorithms<2..2^16-2>;
00231      */
00232     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SIG_ALG >> 8 ) & 0xFF );
00233     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SIG_ALG      ) & 0xFF );
00234 
00235     *p++ = (unsigned char)( ( ( sig_alg_len + 2 ) >> 8 ) & 0xFF );
00236     *p++ = (unsigned char)( ( ( sig_alg_len + 2 )      ) & 0xFF );
00237 
00238     *p++ = (unsigned char)( ( sig_alg_len >> 8 ) & 0xFF );
00239     *p++ = (unsigned char)( ( sig_alg_len      ) & 0xFF );
00240 
00241     *olen = 6 + sig_alg_len;
00242 }
00243 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&
00244           MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
00245 
00246 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
00247     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
00248 static void ssl_write_supported_elliptic_curves_ext( mbedtls_ssl_context *ssl,
00249                                                      unsigned char *buf,
00250                                                      size_t *olen )
00251 {
00252     unsigned char *p = buf;
00253     const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
00254     unsigned char *elliptic_curve_list = p + 6;
00255     size_t elliptic_curve_len = 0;
00256     const mbedtls_ecp_curve_info *info;
00257 #if defined(MBEDTLS_ECP_C)
00258     const mbedtls_ecp_group_id *grp_id;
00259 #else
00260     ((void) ssl);
00261 #endif
00262 
00263     *olen = 0;
00264 
00265     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding supported_elliptic_curves extension" ) );
00266 
00267 #if defined(MBEDTLS_ECP_C)
00268     for( grp_id = ssl->conf->curve_list; *grp_id != MBEDTLS_ECP_DP_NONE; grp_id++ )
00269     {
00270         info = mbedtls_ecp_curve_info_from_grp_id( *grp_id );
00271 #else
00272     for( info = mbedtls_ecp_curve_list(); info->grp_id  != MBEDTLS_ECP_DP_NONE; info++ )
00273     {
00274 #endif
00275         if( info == NULL )
00276         {
00277             MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid curve in ssl configuration" ) );
00278             return;
00279         }
00280 
00281         elliptic_curve_len += 2;
00282     }
00283 
00284     if( end < p || (size_t)( end - p ) < 6 + elliptic_curve_len )
00285     {
00286         MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
00287         return;
00288     }
00289 
00290     elliptic_curve_len = 0;
00291 
00292 #if defined(MBEDTLS_ECP_C)
00293     for( grp_id = ssl->conf->curve_list; *grp_id != MBEDTLS_ECP_DP_NONE; grp_id++ )
00294     {
00295         info = mbedtls_ecp_curve_info_from_grp_id( *grp_id );
00296 #else
00297     for( info = mbedtls_ecp_curve_list(); info->grp_id  != MBEDTLS_ECP_DP_NONE; info++ )
00298     {
00299 #endif
00300         elliptic_curve_list[elliptic_curve_len++] = info->tls_id  >> 8;
00301         elliptic_curve_list[elliptic_curve_len++] = info->tls_id  & 0xFF;
00302     }
00303 
00304     if( elliptic_curve_len == 0 )
00305         return;
00306 
00307     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES >> 8 ) & 0xFF );
00308     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES      ) & 0xFF );
00309 
00310     *p++ = (unsigned char)( ( ( elliptic_curve_len + 2 ) >> 8 ) & 0xFF );
00311     *p++ = (unsigned char)( ( ( elliptic_curve_len + 2 )      ) & 0xFF );
00312 
00313     *p++ = (unsigned char)( ( ( elliptic_curve_len     ) >> 8 ) & 0xFF );
00314     *p++ = (unsigned char)( ( ( elliptic_curve_len     )      ) & 0xFF );
00315 
00316     *olen = 6 + elliptic_curve_len;
00317 }
00318 
00319 static void ssl_write_supported_point_formats_ext( mbedtls_ssl_context *ssl,
00320                                                    unsigned char *buf,
00321                                                    size_t *olen )
00322 {
00323     unsigned char *p = buf;
00324     const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
00325 
00326     *olen = 0;
00327 
00328     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding supported_point_formats extension" ) );
00329 
00330     if( end < p || (size_t)( end - p ) < 6 )
00331     {
00332         MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
00333         return;
00334     }
00335 
00336     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS >> 8 ) & 0xFF );
00337     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS      ) & 0xFF );
00338 
00339     *p++ = 0x00;
00340     *p++ = 2;
00341 
00342     *p++ = 1;
00343     *p++ = MBEDTLS_ECP_PF_UNCOMPRESSED;
00344 
00345     *olen = 6;
00346 }
00347 #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C || 
00348           MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
00349 
00350 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
00351 static void ssl_write_ecjpake_kkpp_ext( mbedtls_ssl_context *ssl,
00352                                         unsigned char *buf,
00353                                         size_t *olen )
00354 {
00355     int ret;
00356     unsigned char *p = buf;
00357     const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
00358     size_t kkpp_len;
00359 
00360     *olen = 0;
00361 
00362     /* Skip costly extension if we can't use EC J-PAKE anyway */
00363     if( mbedtls_ecjpake_check( &ssl->handshake->ecjpake_ctx ) != 0 )
00364         return;
00365 
00366     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding ecjpake_kkpp extension" ) );
00367 
00368     if( end - p < 4 )
00369     {
00370         MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
00371         return;
00372     }
00373 
00374     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ECJPAKE_KKPP >> 8 ) & 0xFF );
00375     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ECJPAKE_KKPP      ) & 0xFF );
00376 
00377     /*
00378      * We may need to send ClientHello multiple times for Hello verification.
00379      * We don't want to compute fresh values every time (both for performance
00380      * and consistency reasons), so cache the extension content.
00381      */
00382     if( ssl->handshake->ecjpake_cache == NULL ||
00383         ssl->handshake->ecjpake_cache_len == 0 )
00384     {
00385         MBEDTLS_SSL_DEBUG_MSG( 3, ( "generating new ecjpake parameters" ) );
00386 
00387         ret = mbedtls_ecjpake_write_round_one( &ssl->handshake->ecjpake_ctx,
00388                                         p + 2, end - p - 2, &kkpp_len,
00389                                         ssl->conf->f_rng, ssl->conf->p_rng );
00390         if( ret != 0 )
00391         {
00392             MBEDTLS_SSL_DEBUG_RET( 1 , "mbedtls_ecjpake_write_round_one", ret );
00393             return;
00394         }
00395 
00396         ssl->handshake->ecjpake_cache = mbedtls_calloc( 1, kkpp_len );
00397         if( ssl->handshake->ecjpake_cache == NULL )
00398         {
00399             MBEDTLS_SSL_DEBUG_MSG( 1, ( "allocation failed" ) );
00400             return;
00401         }
00402 
00403         memcpy( ssl->handshake->ecjpake_cache, p + 2, kkpp_len );
00404         ssl->handshake->ecjpake_cache_len = kkpp_len;
00405     }
00406     else
00407     {
00408         MBEDTLS_SSL_DEBUG_MSG( 3, ( "re-using cached ecjpake parameters" ) );
00409 
00410         kkpp_len = ssl->handshake->ecjpake_cache_len;
00411 
00412         if( (size_t)( end - p - 2 ) < kkpp_len )
00413         {
00414             MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
00415             return;
00416         }
00417 
00418         memcpy( p + 2, ssl->handshake->ecjpake_cache, kkpp_len );
00419     }
00420 
00421     *p++ = (unsigned char)( ( kkpp_len >> 8 ) & 0xFF );
00422     *p++ = (unsigned char)( ( kkpp_len      ) & 0xFF );
00423 
00424     *olen = kkpp_len + 4;
00425 }
00426 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
00427 
00428 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
00429 static void ssl_write_max_fragment_length_ext( mbedtls_ssl_context *ssl,
00430                                                unsigned char *buf,
00431                                                size_t *olen )
00432 {
00433     unsigned char *p = buf;
00434     const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
00435 
00436     *olen = 0;
00437 
00438     if( ssl->conf->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE ) {
00439         return;
00440     }
00441 
00442     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding max_fragment_length extension" ) );
00443 
00444     if( end < p || (size_t)( end - p ) < 5 )
00445     {
00446         MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
00447         return;
00448     }
00449 
00450     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH >> 8 ) & 0xFF );
00451     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH      ) & 0xFF );
00452 
00453     *p++ = 0x00;
00454     *p++ = 1;
00455 
00456     *p++ = ssl->conf->mfl_code;
00457 
00458     *olen = 5;
00459 }
00460 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
00461 
00462 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
00463 static void ssl_write_truncated_hmac_ext( mbedtls_ssl_context *ssl,
00464                                           unsigned char *buf, size_t *olen )
00465 {
00466     unsigned char *p = buf;
00467     const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
00468 
00469     *olen = 0;
00470 
00471     if( ssl->conf->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_DISABLED )
00472     {
00473         return;
00474     }
00475 
00476     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding truncated_hmac extension" ) );
00477 
00478     if( end < p || (size_t)( end - p ) < 4 )
00479     {
00480         MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
00481         return;
00482     }
00483 
00484     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_TRUNCATED_HMAC >> 8 ) & 0xFF );
00485     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_TRUNCATED_HMAC      ) & 0xFF );
00486 
00487     *p++ = 0x00;
00488     *p++ = 0x00;
00489 
00490     *olen = 4;
00491 }
00492 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
00493 
00494 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
00495 static void ssl_write_encrypt_then_mac_ext( mbedtls_ssl_context *ssl,
00496                                        unsigned char *buf, size_t *olen )
00497 {
00498     unsigned char *p = buf;
00499     const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
00500 
00501     *olen = 0;
00502 
00503     if( ssl->conf->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED ||
00504         ssl->conf->max_minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
00505     {
00506         return;
00507     }
00508 
00509     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding encrypt_then_mac "
00510                         "extension" ) );
00511 
00512     if( end < p || (size_t)( end - p ) < 4 )
00513     {
00514         MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
00515         return;
00516     }
00517 
00518     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC >> 8 ) & 0xFF );
00519     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC      ) & 0xFF );
00520 
00521     *p++ = 0x00;
00522     *p++ = 0x00;
00523 
00524     *olen = 4;
00525 }
00526 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
00527 
00528 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
00529 static void ssl_write_extended_ms_ext( mbedtls_ssl_context *ssl,
00530                                        unsigned char *buf, size_t *olen )
00531 {
00532     unsigned char *p = buf;
00533     const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
00534 
00535     *olen = 0;
00536 
00537     if( ssl->conf->extended_ms == MBEDTLS_SSL_EXTENDED_MS_DISABLED ||
00538         ssl->conf->max_minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
00539     {
00540         return;
00541     }
00542 
00543     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding extended_master_secret "
00544                         "extension" ) );
00545 
00546     if( end < p || (size_t)( end - p ) < 4 )
00547     {
00548         MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
00549         return;
00550     }
00551 
00552     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET >> 8 ) & 0xFF );
00553     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET      ) & 0xFF );
00554 
00555     *p++ = 0x00;
00556     *p++ = 0x00;
00557 
00558     *olen = 4;
00559 }
00560 #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
00561 
00562 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
00563 static void ssl_write_session_ticket_ext( mbedtls_ssl_context *ssl,
00564                                           unsigned char *buf, size_t *olen )
00565 {
00566     unsigned char *p = buf;
00567     const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
00568     size_t tlen = ssl->session_negotiate->ticket_len;
00569 
00570     *olen = 0;
00571 
00572     if( ssl->conf->session_tickets == MBEDTLS_SSL_SESSION_TICKETS_DISABLED )
00573     {
00574         return;
00575     }
00576 
00577     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding session ticket extension" ) );
00578 
00579     if( end < p || (size_t)( end - p ) < 4 + tlen )
00580     {
00581         MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
00582         return;
00583     }
00584 
00585     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SESSION_TICKET >> 8 ) & 0xFF );
00586     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SESSION_TICKET      ) & 0xFF );
00587 
00588     *p++ = (unsigned char)( ( tlen >> 8 ) & 0xFF );
00589     *p++ = (unsigned char)( ( tlen      ) & 0xFF );
00590 
00591     *olen = 4;
00592 
00593     if( ssl->session_negotiate->ticket == NULL || tlen == 0 )
00594     {
00595         return;
00596     }
00597 
00598     MBEDTLS_SSL_DEBUG_MSG( 3, ( "sending session ticket of length %d", tlen ) );
00599 
00600     memcpy( p, ssl->session_negotiate->ticket, tlen );
00601 
00602     *olen += tlen;
00603 }
00604 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
00605 
00606 #if defined(MBEDTLS_SSL_ALPN)
00607 static void ssl_write_alpn_ext( mbedtls_ssl_context *ssl,
00608                                 unsigned char *buf, size_t *olen )
00609 {
00610     unsigned char *p = buf;
00611     const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
00612     size_t alpnlen = 0;
00613     const char **cur;
00614 
00615     *olen = 0;
00616 
00617     if( ssl->conf->alpn_list == NULL )
00618     {
00619         return;
00620     }
00621 
00622     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding alpn extension" ) );
00623 
00624     for( cur = ssl->conf->alpn_list; *cur != NULL; cur++ )
00625         alpnlen += (unsigned char)( strlen( *cur ) & 0xFF ) + 1;
00626 
00627     if( end < p || (size_t)( end - p ) < 6 + alpnlen )
00628     {
00629         MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
00630         return;
00631     }
00632 
00633     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN >> 8 ) & 0xFF );
00634     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN      ) & 0xFF );
00635 
00636     /*
00637      * opaque ProtocolName<1..2^8-1>;
00638      *
00639      * struct {
00640      *     ProtocolName protocol_name_list<2..2^16-1>
00641      * } ProtocolNameList;
00642      */
00643 
00644     /* Skip writing extension and list length for now */
00645     p += 4;
00646 
00647     for( cur = ssl->conf->alpn_list; *cur != NULL; cur++ )
00648     {
00649         *p = (unsigned char)( strlen( *cur ) & 0xFF );
00650         memcpy( p + 1, *cur, *p );
00651         p += 1 + *p;
00652     }
00653 
00654     *olen = p - buf;
00655 
00656     /* List length = olen - 2 (ext_type) - 2 (ext_len) - 2 (list_len) */
00657     buf[4] = (unsigned char)( ( ( *olen - 6 ) >> 8 ) & 0xFF );
00658     buf[5] = (unsigned char)( ( ( *olen - 6 )      ) & 0xFF );
00659 
00660     /* Extension length = olen - 2 (ext_type) - 2 (ext_len) */
00661     buf[2] = (unsigned char)( ( ( *olen - 4 ) >> 8 ) & 0xFF );
00662     buf[3] = (unsigned char)( ( ( *olen - 4 )      ) & 0xFF );
00663 }
00664 #endif /* MBEDTLS_SSL_ALPN */
00665 
00666 /*
00667  * Generate random bytes for ClientHello
00668  */
00669 static int ssl_generate_random( mbedtls_ssl_context *ssl )
00670 {
00671     int ret;
00672     unsigned char *p = ssl->handshake->randbytes;
00673 #if defined(MBEDTLS_HAVE_TIME)
00674     mbedtls_time_t t;
00675 #endif
00676 
00677     /*
00678      * When responding to a verify request, MUST reuse random (RFC 6347 4.2.1)
00679      */
00680 #if defined(MBEDTLS_SSL_PROTO_DTLS)
00681     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
00682         ssl->handshake->verify_cookie != NULL )
00683     {
00684         return( 0 );
00685     }
00686 #endif
00687 
00688 #if defined(MBEDTLS_HAVE_TIME)
00689     t = mbedtls_time( NULL );
00690     *p++ = (unsigned char)( t >> 24 );
00691     *p++ = (unsigned char)( t >> 16 );
00692     *p++ = (unsigned char)( t >>  8 );
00693     *p++ = (unsigned char)( t       );
00694 
00695     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, current time: %lu", t ) );
00696 #else
00697     if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p, 4 ) ) != 0 )
00698         return( ret );
00699 
00700     p += 4;
00701 #endif /* MBEDTLS_HAVE_TIME */
00702 
00703     if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p, 28 ) ) != 0 )
00704         return( ret );
00705 
00706     return( 0 );
00707 }
00708 
00709 static int ssl_write_client_hello( mbedtls_ssl_context *ssl )
00710 {
00711     int ret;
00712     size_t i, n, olen, ext_len = 0;
00713     unsigned char *buf;
00714     unsigned char *p, *q;
00715     unsigned char offer_compress;
00716     const int *ciphersuites;
00717     const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
00718 
00719     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write client hello" ) );
00720 
00721     if( ssl->conf->f_rng == NULL )
00722     {
00723         MBEDTLS_SSL_DEBUG_MSG( 1, ( "no RNG provided") );
00724         return( MBEDTLS_ERR_SSL_NO_RNG );
00725     }
00726 
00727 #if defined(MBEDTLS_SSL_RENEGOTIATION)
00728     if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE )
00729 #endif
00730     {
00731         ssl->major_ver = ssl->conf->min_major_ver;
00732         ssl->minor_ver = ssl->conf->min_minor_ver;
00733     }
00734 
00735     if( ssl->conf->max_major_ver == 0 )
00736     {
00737         MBEDTLS_SSL_DEBUG_MSG( 1, ( "configured max major version is invalid, "
00738                             "consider using mbedtls_ssl_config_defaults()" ) );
00739         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
00740     }
00741 
00742     /*
00743      *     0  .   0   handshake type
00744      *     1  .   3   handshake length
00745      *     4  .   5   highest version supported
00746      *     6  .   9   current UNIX time
00747      *    10  .  37   random bytes
00748      */
00749     buf = ssl->out_msg;
00750     p = buf + 4;
00751 
00752     mbedtls_ssl_write_version( ssl->conf->max_major_ver, ssl->conf->max_minor_ver,
00753                        ssl->conf->transport, p );
00754     p += 2;
00755 
00756     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, max version: [%d:%d]",
00757                    buf[4], buf[5] ) );
00758 
00759     if( ( ret = ssl_generate_random( ssl ) ) != 0 )
00760     {
00761         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_generate_random", ret );
00762         return( ret );
00763     }
00764 
00765     memcpy( p, ssl->handshake->randbytes, 32 );
00766     MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, random bytes", p, 32 );
00767     p += 32;
00768 
00769     /*
00770      *    38  .  38   session id length
00771      *    39  . 39+n  session id
00772      *   39+n . 39+n  DTLS only: cookie length (1 byte)
00773      *   40+n .  ..   DTSL only: cookie
00774      *   ..   . ..    ciphersuitelist length (2 bytes)
00775      *   ..   . ..    ciphersuitelist
00776      *   ..   . ..    compression methods length (1 byte)
00777      *   ..   . ..    compression methods
00778      *   ..   . ..    extensions length (2 bytes)
00779      *   ..   . ..    extensions
00780      */
00781     n = ssl->session_negotiate->id_len;
00782 
00783     if( n < 16 || n > 32 ||
00784 #if defined(MBEDTLS_SSL_RENEGOTIATION)
00785         ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ||
00786 #endif
00787         ssl->handshake->resume == 0 )
00788     {
00789         n = 0;
00790     }
00791 
00792 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
00793     /*
00794      * RFC 5077 section 3.4: "When presenting a ticket, the client MAY
00795      * generate and include a Session ID in the TLS ClientHello."
00796      */
00797 #if defined(MBEDTLS_SSL_RENEGOTIATION)
00798     if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE )
00799 #endif
00800     {
00801         if( ssl->session_negotiate->ticket != NULL &&
00802                 ssl->session_negotiate->ticket_len != 0 )
00803         {
00804             ret = ssl->conf->f_rng( ssl->conf->p_rng, ssl->session_negotiate->id, 32 );
00805 
00806             if( ret != 0 )
00807                 return( ret );
00808 
00809             ssl->session_negotiate->id_len = n = 32;
00810         }
00811     }
00812 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
00813 
00814     *p++ = (unsigned char) n;
00815 
00816     for( i = 0; i < n; i++ )
00817         *p++ = ssl->session_negotiate->id[i];
00818 
00819     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, session id len.: %d", n ) );
00820     MBEDTLS_SSL_DEBUG_BUF( 3,   "client hello, session id", buf + 39, n );
00821 
00822     /*
00823      * DTLS cookie
00824      */
00825 #if defined(MBEDTLS_SSL_PROTO_DTLS)
00826     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
00827     {
00828         if( ssl->handshake->verify_cookie == NULL )
00829         {
00830             MBEDTLS_SSL_DEBUG_MSG( 3, ( "no verify cookie to send" ) );
00831             *p++ = 0;
00832         }
00833         else
00834         {
00835             MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, cookie",
00836                               ssl->handshake->verify_cookie,
00837                               ssl->handshake->verify_cookie_len );
00838 
00839             *p++ = ssl->handshake->verify_cookie_len;
00840             memcpy( p, ssl->handshake->verify_cookie,
00841                        ssl->handshake->verify_cookie_len );
00842             p += ssl->handshake->verify_cookie_len;
00843         }
00844     }
00845 #endif
00846 
00847     /*
00848      * Ciphersuite list
00849      */
00850     ciphersuites = ssl->conf->ciphersuite_list[ssl->minor_ver];
00851 
00852     /* Skip writing ciphersuite length for now */
00853     n = 0;
00854     q = p;
00855     p += 2;
00856 
00857     for( i = 0; ciphersuites[i] != 0; i++ )
00858     {
00859         ciphersuite_info = mbedtls_ssl_ciphersuite_from_id( ciphersuites[i] );
00860 
00861         if( ciphersuite_info == NULL )
00862             continue;
00863 
00864         if( ciphersuite_info->min_minor_ver > ssl->conf->max_minor_ver ||
00865             ciphersuite_info->max_minor_ver < ssl->conf->min_minor_ver )
00866             continue;
00867 
00868 #if defined(MBEDTLS_SSL_PROTO_DTLS)
00869         if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
00870             ( ciphersuite_info->flags & MBEDTLS_CIPHERSUITE_NODTLS ) )
00871             continue;
00872 #endif
00873 
00874 #if defined(MBEDTLS_ARC4_C)
00875         if( ssl->conf->arc4_disabled == MBEDTLS_SSL_ARC4_DISABLED &&
00876             ciphersuite_info->cipher == MBEDTLS_CIPHER_ARC4_128 )
00877             continue;
00878 #endif
00879 
00880 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
00881         if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE &&
00882             mbedtls_ecjpake_check( &ssl->handshake->ecjpake_ctx ) != 0 )
00883             continue;
00884 #endif
00885 
00886         MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, add ciphersuite: %04x",
00887                                     ciphersuites[i] ) );
00888 
00889         n++;
00890         *p++ = (unsigned char)( ciphersuites[i] >> 8 );
00891         *p++ = (unsigned char)( ciphersuites[i]      );
00892     }
00893 
00894     /*
00895      * Add TLS_EMPTY_RENEGOTIATION_INFO_SCSV
00896      */
00897 #if defined(MBEDTLS_SSL_RENEGOTIATION)
00898     if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE )
00899 #endif
00900     {
00901         *p++ = (unsigned char)( MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO >> 8 );
00902         *p++ = (unsigned char)( MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO      );
00903         n++;
00904     }
00905 
00906     /* Some versions of OpenSSL don't handle it correctly if not at end */
00907 #if defined(MBEDTLS_SSL_FALLBACK_SCSV)
00908     if( ssl->conf->fallback == MBEDTLS_SSL_IS_FALLBACK )
00909     {
00910         MBEDTLS_SSL_DEBUG_MSG( 3, ( "adding FALLBACK_SCSV" ) );
00911         *p++ = (unsigned char)( MBEDTLS_SSL_FALLBACK_SCSV_VALUE >> 8 );
00912         *p++ = (unsigned char)( MBEDTLS_SSL_FALLBACK_SCSV_VALUE      );
00913         n++;
00914     }
00915 #endif
00916 
00917     *q++ = (unsigned char)( n >> 7 );
00918     *q++ = (unsigned char)( n << 1 );
00919 
00920     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, got %d ciphersuites", n ) );
00921 
00922 #if defined(MBEDTLS_ZLIB_SUPPORT)
00923     offer_compress = 1;
00924 #else
00925     offer_compress = 0;
00926 #endif
00927 
00928     /*
00929      * We don't support compression with DTLS right now: is many records come
00930      * in the same datagram, uncompressing one could overwrite the next one.
00931      * We don't want to add complexity for handling that case unless there is
00932      * an actual need for it.
00933      */
00934 #if defined(MBEDTLS_SSL_PROTO_DTLS)
00935     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
00936         offer_compress = 0;
00937 #endif
00938 
00939     if( offer_compress )
00940     {
00941         MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress len.: %d", 2 ) );
00942         MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress alg.: %d %d",
00943                             MBEDTLS_SSL_COMPRESS_DEFLATE, MBEDTLS_SSL_COMPRESS_NULL ) );
00944 
00945         *p++ = 2;
00946         *p++ = MBEDTLS_SSL_COMPRESS_DEFLATE;
00947         *p++ = MBEDTLS_SSL_COMPRESS_NULL;
00948     }
00949     else
00950     {
00951         MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress len.: %d", 1 ) );
00952         MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress alg.: %d",
00953                             MBEDTLS_SSL_COMPRESS_NULL ) );
00954 
00955         *p++ = 1;
00956         *p++ = MBEDTLS_SSL_COMPRESS_NULL;
00957     }
00958 
00959     // First write extensions, then the total length
00960     //
00961 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
00962     ssl_write_hostname_ext( ssl, p + 2 + ext_len, &olen );
00963     ext_len += olen;
00964 #endif
00965 
00966 #if defined(MBEDTLS_SSL_RENEGOTIATION)
00967     ssl_write_renegotiation_ext( ssl, p + 2 + ext_len, &olen );
00968     ext_len += olen;
00969 #endif
00970 
00971 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
00972     defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
00973     ssl_write_signature_algorithms_ext( ssl, p + 2 + ext_len, &olen );
00974     ext_len += olen;
00975 #endif
00976 
00977 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
00978     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
00979     ssl_write_supported_elliptic_curves_ext( ssl, p + 2 + ext_len, &olen );
00980     ext_len += olen;
00981 
00982     ssl_write_supported_point_formats_ext( ssl, p + 2 + ext_len, &olen );
00983     ext_len += olen;
00984 #endif
00985 
00986 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
00987     ssl_write_ecjpake_kkpp_ext( ssl, p + 2 + ext_len, &olen );
00988     ext_len += olen;
00989 #endif
00990 
00991 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
00992     ssl_write_max_fragment_length_ext( ssl, p + 2 + ext_len, &olen );
00993     ext_len += olen;
00994 #endif
00995 
00996 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
00997     ssl_write_truncated_hmac_ext( ssl, p + 2 + ext_len, &olen );
00998     ext_len += olen;
00999 #endif
01000 
01001 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
01002     ssl_write_encrypt_then_mac_ext( ssl, p + 2 + ext_len, &olen );
01003     ext_len += olen;
01004 #endif
01005 
01006 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
01007     ssl_write_extended_ms_ext( ssl, p + 2 + ext_len, &olen );
01008     ext_len += olen;
01009 #endif
01010 
01011 #if defined(MBEDTLS_SSL_ALPN)
01012     ssl_write_alpn_ext( ssl, p + 2 + ext_len, &olen );
01013     ext_len += olen;
01014 #endif
01015 
01016 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
01017     ssl_write_session_ticket_ext( ssl, p + 2 + ext_len, &olen );
01018     ext_len += olen;
01019 #endif
01020 
01021     /* olen unused if all extensions are disabled */
01022     ((void) olen);
01023 
01024     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, total extension length: %d",
01025                    ext_len ) );
01026 
01027     if( ext_len > 0 )
01028     {
01029         *p++ = (unsigned char)( ( ext_len >> 8 ) & 0xFF );
01030         *p++ = (unsigned char)( ( ext_len      ) & 0xFF );
01031         p += ext_len;
01032     }
01033 
01034     ssl->out_msglen  = p - buf;
01035     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
01036     ssl->out_msg[0]  = MBEDTLS_SSL_HS_CLIENT_HELLO;
01037 
01038     ssl->state++;
01039 
01040 #if defined(MBEDTLS_SSL_PROTO_DTLS)
01041     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
01042         mbedtls_ssl_send_flight_completed( ssl );
01043 #endif
01044 
01045     if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
01046     {
01047         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
01048         return( ret );
01049     }
01050 
01051     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write client hello" ) );
01052 
01053     return( 0 );
01054 }
01055 
01056 static int ssl_parse_renegotiation_info( mbedtls_ssl_context *ssl,
01057                                          const unsigned char *buf,
01058                                          size_t len )
01059 {
01060     int ret;
01061 
01062 #if defined(MBEDTLS_SSL_RENEGOTIATION)
01063     if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE )
01064     {
01065         /* Check verify-data in constant-time. The length OTOH is no secret */
01066         if( len    != 1 + ssl->verify_data_len * 2 ||
01067             buf[0] !=     ssl->verify_data_len * 2 ||
01068             mbedtls_ssl_safer_memcmp( buf + 1,
01069                           ssl->own_verify_data, ssl->verify_data_len ) != 0 ||
01070             mbedtls_ssl_safer_memcmp( buf + 1 + ssl->verify_data_len,
01071                           ssl->peer_verify_data, ssl->verify_data_len ) != 0 )
01072         {
01073             MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching renegotiation info" ) );
01074 
01075             if( ( ret = mbedtls_ssl_send_fatal_handshake_failure( ssl ) ) != 0 )
01076                 return( ret );
01077 
01078             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
01079         }
01080     }
01081     else
01082 #endif /* MBEDTLS_SSL_RENEGOTIATION */
01083     {
01084         if( len != 1 || buf[0] != 0x00 )
01085         {
01086             MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-zero length renegotiation info" ) );
01087 
01088             if( ( ret = mbedtls_ssl_send_fatal_handshake_failure( ssl ) ) != 0 )
01089                 return( ret );
01090 
01091             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
01092         }
01093 
01094         ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION;
01095     }
01096 
01097     return( 0 );
01098 }
01099 
01100 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
01101 static int ssl_parse_max_fragment_length_ext( mbedtls_ssl_context *ssl,
01102                                               const unsigned char *buf,
01103                                               size_t len )
01104 {
01105     /*
01106      * server should use the extension only if we did,
01107      * and if so the server's value should match ours (and len is always 1)
01108      */
01109     if( ssl->conf->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE ||
01110         len != 1 ||
01111         buf[0] != ssl->conf->mfl_code )
01112     {
01113         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
01114     }
01115 
01116     return( 0 );
01117 }
01118 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
01119 
01120 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
01121 static int ssl_parse_truncated_hmac_ext( mbedtls_ssl_context *ssl,
01122                                          const unsigned char *buf,
01123                                          size_t len )
01124 {
01125     if( ssl->conf->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_DISABLED ||
01126         len != 0 )
01127     {
01128         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
01129     }
01130 
01131     ((void) buf);
01132 
01133     ssl->session_negotiate->trunc_hmac = MBEDTLS_SSL_TRUNC_HMAC_ENABLED;
01134 
01135     return( 0 );
01136 }
01137 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
01138 
01139 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
01140 static int ssl_parse_encrypt_then_mac_ext( mbedtls_ssl_context *ssl,
01141                                          const unsigned char *buf,
01142                                          size_t len )
01143 {
01144     if( ssl->conf->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED ||
01145         ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ||
01146         len != 0 )
01147     {
01148         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
01149     }
01150 
01151     ((void) buf);
01152 
01153     ssl->session_negotiate->encrypt_then_mac = MBEDTLS_SSL_ETM_ENABLED;
01154 
01155     return( 0 );
01156 }
01157 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
01158 
01159 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
01160 static int ssl_parse_extended_ms_ext( mbedtls_ssl_context *ssl,
01161                                          const unsigned char *buf,
01162                                          size_t len )
01163 {
01164     if( ssl->conf->extended_ms == MBEDTLS_SSL_EXTENDED_MS_DISABLED ||
01165         ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ||
01166         len != 0 )
01167     {
01168         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
01169     }
01170 
01171     ((void) buf);
01172 
01173     ssl->handshake->extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED;
01174 
01175     return( 0 );
01176 }
01177 #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
01178 
01179 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
01180 static int ssl_parse_session_ticket_ext( mbedtls_ssl_context *ssl,
01181                                          const unsigned char *buf,
01182                                          size_t len )
01183 {
01184     if( ssl->conf->session_tickets == MBEDTLS_SSL_SESSION_TICKETS_DISABLED ||
01185         len != 0 )
01186     {
01187         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
01188     }
01189 
01190     ((void) buf);
01191 
01192     ssl->handshake->new_session_ticket = 1;
01193 
01194     return( 0 );
01195 }
01196 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
01197 
01198 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
01199     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
01200 static int ssl_parse_supported_point_formats_ext( mbedtls_ssl_context *ssl,
01201                                                   const unsigned char *buf,
01202                                                   size_t len )
01203 {
01204     size_t list_size;
01205     const unsigned char *p;
01206 
01207     list_size = buf[0];
01208     if( list_size + 1 != len )
01209     {
01210         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
01211         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
01212     }
01213 
01214     p = buf + 1;
01215     while( list_size > 0 )
01216     {
01217         if( p[0] == MBEDTLS_ECP_PF_UNCOMPRESSED ||
01218             p[0] == MBEDTLS_ECP_PF_COMPRESSED )
01219         {
01220 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C)
01221             ssl->handshake->ecdh_ctx.point_format = p[0];
01222 #endif            
01223 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
01224             ssl->handshake->ecjpake_ctx.point_format = p[0];
01225 #endif
01226             MBEDTLS_SSL_DEBUG_MSG( 4, ( "point format selected: %d", p[0] ) );
01227             return( 0 );
01228         }
01229 
01230         list_size--;
01231         p++;
01232     }
01233 
01234     MBEDTLS_SSL_DEBUG_MSG( 1, ( "no point format in common" ) );
01235     return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
01236 }
01237 #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C || 
01238           MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
01239 
01240 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
01241 static int ssl_parse_ecjpake_kkpp( mbedtls_ssl_context *ssl,
01242                                    const unsigned char *buf,
01243                                    size_t len )
01244 {
01245     int ret;
01246 
01247     if( ssl->transform_negotiate->ciphersuite_info->key_exchange !=
01248         MBEDTLS_KEY_EXCHANGE_ECJPAKE )
01249     {
01250         MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip ecjpake kkpp extension" ) );
01251         return( 0 );
01252     }
01253 
01254     /* If we got here, we no longer need our cached extension */
01255     mbedtls_free( ssl->handshake->ecjpake_cache );
01256     ssl->handshake->ecjpake_cache = NULL;
01257     ssl->handshake->ecjpake_cache_len = 0;
01258 
01259     if( ( ret = mbedtls_ecjpake_read_round_one( &ssl->handshake->ecjpake_ctx,
01260                                                 buf, len ) ) != 0 )
01261     {
01262         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_one", ret );
01263         return( ret );
01264     }
01265 
01266     return( 0 );
01267 }
01268 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
01269 
01270 #if defined(MBEDTLS_SSL_ALPN)
01271 static int ssl_parse_alpn_ext( mbedtls_ssl_context *ssl,
01272                                const unsigned char *buf, size_t len )
01273 {
01274     size_t list_len, name_len;
01275     const char **p;
01276 
01277     /* If we didn't send it, the server shouldn't send it */
01278     if( ssl->conf->alpn_list == NULL )
01279         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
01280 
01281     /*
01282      * opaque ProtocolName<1..2^8-1>;
01283      *
01284      * struct {
01285      *     ProtocolName protocol_name_list<2..2^16-1>
01286      * } ProtocolNameList;
01287      *
01288      * the "ProtocolNameList" MUST contain exactly one "ProtocolName"
01289      */
01290 
01291     /* Min length is 2 (list_len) + 1 (name_len) + 1 (name) */
01292     if( len < 4 )
01293         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
01294 
01295     list_len = ( buf[0] << 8 ) | buf[1];
01296     if( list_len != len - 2 )
01297         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
01298 
01299     name_len = buf[2];
01300     if( name_len != list_len - 1 )
01301         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
01302 
01303     /* Check that the server chosen protocol was in our list and save it */
01304     for( p = ssl->conf->alpn_list; *p != NULL; p++ )
01305     {
01306         if( name_len == strlen( *p ) &&
01307             memcmp( buf + 3, *p, name_len ) == 0 )
01308         {
01309             ssl->alpn_chosen = *p;
01310             return( 0 );
01311         }
01312     }
01313 
01314     return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
01315 }
01316 #endif /* MBEDTLS_SSL_ALPN */
01317 
01318 /*
01319  * Parse HelloVerifyRequest.  Only called after verifying the HS type.
01320  */
01321 #if defined(MBEDTLS_SSL_PROTO_DTLS)
01322 static int ssl_parse_hello_verify_request( mbedtls_ssl_context *ssl )
01323 {
01324     const unsigned char *p = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
01325     int major_ver, minor_ver;
01326     unsigned char cookie_len;
01327 
01328     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse hello verify request" ) );
01329 
01330     /*
01331      * struct {
01332      *   ProtocolVersion server_version;
01333      *   opaque cookie<0..2^8-1>;
01334      * } HelloVerifyRequest;
01335      */
01336     MBEDTLS_SSL_DEBUG_BUF( 3, "server version", p, 2 );
01337     mbedtls_ssl_read_version( &major_ver, &minor_ver, ssl->conf->transport, p );
01338     p += 2;
01339 
01340     /*
01341      * Since the RFC is not clear on this point, accept DTLS 1.0 (TLS 1.1)
01342      * even is lower than our min version.
01343      */
01344     if( major_ver < MBEDTLS_SSL_MAJOR_VERSION_3 ||
01345         minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 ||
01346         major_ver > ssl->conf->max_major_ver  ||
01347         minor_ver > ssl->conf->max_minor_ver  )
01348     {
01349         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server version" ) );
01350 
01351         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
01352                                      MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION );
01353 
01354         return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION );
01355     }
01356 
01357     cookie_len = *p++;
01358     MBEDTLS_SSL_DEBUG_BUF( 3, "cookie", p, cookie_len );
01359 
01360     mbedtls_free( ssl->handshake->verify_cookie );
01361 
01362     ssl->handshake->verify_cookie = mbedtls_calloc( 1, cookie_len );
01363     if( ssl->handshake->verify_cookie  == NULL )
01364     {
01365         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc failed (%d bytes)", cookie_len ) );
01366         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
01367     }
01368 
01369     memcpy( ssl->handshake->verify_cookie, p, cookie_len );
01370     ssl->handshake->verify_cookie_len = cookie_len;
01371 
01372     /* Start over at ClientHello */
01373     ssl->state = MBEDTLS_SSL_CLIENT_HELLO;
01374     mbedtls_ssl_reset_checksum( ssl );
01375 
01376     mbedtls_ssl_recv_flight_completed( ssl );
01377 
01378     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse hello verify request" ) );
01379 
01380     return( 0 );
01381 }
01382 #endif /* MBEDTLS_SSL_PROTO_DTLS */
01383 
01384 static int ssl_parse_server_hello( mbedtls_ssl_context *ssl )
01385 {
01386     int ret, i;
01387     size_t n;
01388     size_t ext_len;
01389     unsigned char *buf, *ext;
01390     unsigned char comp;
01391 #if defined(MBEDTLS_ZLIB_SUPPORT)
01392     int accept_comp;
01393 #endif
01394 #if defined(MBEDTLS_SSL_RENEGOTIATION)
01395     int renegotiation_info_seen = 0;
01396 #endif
01397     int handshake_failure = 0;
01398     const mbedtls_ssl_ciphersuite_t *suite_info;
01399 #if defined(MBEDTLS_DEBUG_C)
01400     uint32_t t;
01401 #endif
01402 
01403     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server hello" ) );
01404 
01405     buf = ssl->in_msg;
01406 
01407     if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
01408     {
01409         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
01410         return( ret );
01411     }
01412 
01413     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
01414     {
01415 #if defined(MBEDTLS_SSL_RENEGOTIATION)
01416         if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
01417         {
01418             ssl->renego_records_seen++;
01419 
01420             if( ssl->conf->renego_max_records >= 0 &&
01421                 ssl->renego_records_seen > ssl->conf->renego_max_records )
01422             {
01423                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation requested, "
01424                                     "but not honored by server" ) );
01425                 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
01426             }
01427 
01428             MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-handshake message during renego" ) );
01429             return( MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO );
01430         }
01431 #endif /* MBEDTLS_SSL_RENEGOTIATION */
01432 
01433         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
01434         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
01435     }
01436 
01437 #if defined(MBEDTLS_SSL_PROTO_DTLS)
01438     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
01439     {
01440         if( buf[0] == MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST )
01441         {
01442             MBEDTLS_SSL_DEBUG_MSG( 2, ( "received hello verify request" ) );
01443             MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server hello" ) );
01444             return( ssl_parse_hello_verify_request( ssl ) );
01445         }
01446         else
01447         {
01448             /* We made it through the verification process */
01449             mbedtls_free( ssl->handshake->verify_cookie );
01450             ssl->handshake->verify_cookie = NULL;
01451             ssl->handshake->verify_cookie_len = 0;
01452         }
01453     }
01454 #endif /* MBEDTLS_SSL_PROTO_DTLS */
01455 
01456     if( ssl->in_hslen < 38 + mbedtls_ssl_hs_hdr_len( ssl ) ||
01457         buf[0] != MBEDTLS_SSL_HS_SERVER_HELLO )
01458     {
01459         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
01460         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
01461     }
01462 
01463     /*
01464      *  0   .  1    server_version
01465      *  2   . 33    random (maybe including 4 bytes of Unix time)
01466      * 34   . 34    session_id length = n
01467      * 35   . 34+n  session_id
01468      * 35+n . 36+n  cipher_suite
01469      * 37+n . 37+n  compression_method
01470      *
01471      * 38+n . 39+n  extensions length (optional)
01472      * 40+n .  ..   extensions
01473      */
01474     buf += mbedtls_ssl_hs_hdr_len( ssl );
01475 
01476     MBEDTLS_SSL_DEBUG_BUF( 3, "server hello, version", buf + 0, 2 );
01477     mbedtls_ssl_read_version( &ssl->major_ver, &ssl->minor_ver,
01478                       ssl->conf->transport, buf + 0 );
01479 
01480     if( ssl->major_ver < ssl->conf->min_major_ver ||
01481         ssl->minor_ver < ssl->conf->min_minor_ver ||
01482         ssl->major_ver > ssl->conf->max_major_ver ||
01483         ssl->minor_ver > ssl->conf->max_minor_ver )
01484     {
01485         MBEDTLS_SSL_DEBUG_MSG( 1, ( "server version out of bounds - "
01486                             " min: [%d:%d], server: [%d:%d], max: [%d:%d]",
01487                             ssl->conf->min_major_ver, ssl->conf->min_minor_ver,
01488                             ssl->major_ver, ssl->minor_ver,
01489                             ssl->conf->max_major_ver, ssl->conf->max_minor_ver ) );
01490 
01491         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
01492                                      MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION );
01493 
01494         return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION );
01495     }
01496 
01497 #if defined(MBEDTLS_DEBUG_C)
01498     t = ( (uint32_t) buf[2] << 24 )
01499       | ( (uint32_t) buf[3] << 16 )
01500       | ( (uint32_t) buf[4] <<  8 )
01501       | ( (uint32_t) buf[5]       );
01502     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, current time: %lu", t ) );
01503 #endif
01504 
01505     memcpy( ssl->handshake->randbytes + 32, buf + 2, 32 );
01506 
01507     n = buf[34];
01508 
01509     MBEDTLS_SSL_DEBUG_BUF( 3,   "server hello, random bytes", buf + 2, 32 );
01510 
01511     if( n > 32 )
01512     {
01513         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
01514         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
01515     }
01516 
01517     if( ssl->in_hslen > mbedtls_ssl_hs_hdr_len( ssl ) + 39 + n )
01518     {
01519         ext_len = ( ( buf[38 + n] <<  8 )
01520                   | ( buf[39 + n]       ) );
01521 
01522         if( ( ext_len > 0 && ext_len < 4 ) ||
01523             ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) + 40 + n + ext_len )
01524         {
01525             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
01526             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
01527         }
01528     }
01529     else if( ssl->in_hslen == mbedtls_ssl_hs_hdr_len( ssl ) + 38 + n )
01530     {
01531         ext_len = 0;
01532     }
01533     else
01534     {
01535         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
01536         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
01537     }
01538 
01539     /* ciphersuite (used later) */
01540     i = ( buf[35 + n] << 8 ) | buf[36 + n];
01541 
01542     /*
01543      * Read and check compression
01544      */
01545     comp = buf[37 + n];
01546 
01547 #if defined(MBEDTLS_ZLIB_SUPPORT)
01548     /* See comments in ssl_write_client_hello() */
01549 #if defined(MBEDTLS_SSL_PROTO_DTLS)
01550     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
01551         accept_comp = 0;
01552     else
01553 #endif
01554         accept_comp = 1;
01555 
01556     if( comp != MBEDTLS_SSL_COMPRESS_NULL &&
01557         ( comp != MBEDTLS_SSL_COMPRESS_DEFLATE || accept_comp == 0 ) )
01558 #else /* MBEDTLS_ZLIB_SUPPORT */
01559     if( comp != MBEDTLS_SSL_COMPRESS_NULL )
01560 #endif/* MBEDTLS_ZLIB_SUPPORT */
01561     {
01562         MBEDTLS_SSL_DEBUG_MSG( 1, ( "server hello, bad compression: %d", comp ) );
01563         return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
01564     }
01565 
01566     /*
01567      * Initialize update checksum functions
01568      */
01569     ssl->transform_negotiate->ciphersuite_info = mbedtls_ssl_ciphersuite_from_id( i );
01570 
01571     if( ssl->transform_negotiate->ciphersuite_info == NULL )
01572     {
01573         MBEDTLS_SSL_DEBUG_MSG( 1, ( "ciphersuite info for %04x not found", i ) );
01574         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
01575     }
01576 
01577     mbedtls_ssl_optimize_checksum( ssl, ssl->transform_negotiate->ciphersuite_info );
01578 
01579     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, session id len.: %d", n ) );
01580     MBEDTLS_SSL_DEBUG_BUF( 3,   "server hello, session id", buf + 35, n );
01581 
01582     /*
01583      * Check if the session can be resumed
01584      */
01585     if( ssl->handshake->resume == 0 || n == 0 ||
01586 #if defined(MBEDTLS_SSL_RENEGOTIATION)
01587         ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ||
01588 #endif
01589         ssl->session_negotiate->ciphersuite != i ||
01590         ssl->session_negotiate->compression != comp ||
01591         ssl->session_negotiate->id_len != n ||
01592         memcmp( ssl->session_negotiate->id, buf + 35, n ) != 0 )
01593     {
01594         ssl->state++;
01595         ssl->handshake->resume = 0;
01596 #if defined(MBEDTLS_HAVE_TIME)
01597         ssl->session_negotiate->start = mbedtls_time( NULL );
01598 #endif
01599         ssl->session_negotiate->ciphersuite = i;
01600         ssl->session_negotiate->compression = comp;
01601         ssl->session_negotiate->id_len = n;
01602         memcpy( ssl->session_negotiate->id, buf + 35, n );
01603     }
01604     else
01605     {
01606         ssl->state = MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC;
01607 
01608         if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )
01609         {
01610             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret );
01611             return( ret );
01612         }
01613     }
01614 
01615     MBEDTLS_SSL_DEBUG_MSG( 3, ( "%s session has been resumed",
01616                    ssl->handshake->resume ? "a" : "no" ) );
01617 
01618     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen ciphersuite: %04x", i ) );
01619     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, compress alg.: %d", buf[37 + n] ) );
01620 
01621     suite_info = mbedtls_ssl_ciphersuite_from_id( ssl->session_negotiate->ciphersuite );
01622     if( suite_info == NULL
01623 #if defined(MBEDTLS_ARC4_C)
01624             || ( ssl->conf->arc4_disabled &&
01625                 suite_info->cipher == MBEDTLS_CIPHER_ARC4_128 )
01626 #endif
01627         )
01628     {
01629         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
01630         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
01631     }
01632 
01633     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen ciphersuite: %s", suite_info->name ) );
01634 
01635     i = 0;
01636     while( 1 )
01637     {
01638         if( ssl->conf->ciphersuite_list[ssl->minor_ver][i] == 0 )
01639         {
01640             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
01641             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
01642         }
01643 
01644         if( ssl->conf->ciphersuite_list[ssl->minor_ver][i++] ==
01645             ssl->session_negotiate->ciphersuite )
01646         {
01647             break;
01648         }
01649     }
01650 
01651     if( comp != MBEDTLS_SSL_COMPRESS_NULL
01652 #if defined(MBEDTLS_ZLIB_SUPPORT)
01653         && comp != MBEDTLS_SSL_COMPRESS_DEFLATE
01654 #endif
01655       )
01656     {
01657         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
01658         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
01659     }
01660     ssl->session_negotiate->compression = comp;
01661 
01662     ext = buf + 40 + n;
01663 
01664     MBEDTLS_SSL_DEBUG_MSG( 2, ( "server hello, total extension length: %d", ext_len ) );
01665 
01666     while( ext_len )
01667     {
01668         unsigned int ext_id   = ( ( ext[0] <<  8 )
01669                                 | ( ext[1]       ) );
01670         unsigned int ext_size = ( ( ext[2] <<  8 )
01671                                 | ( ext[3]       ) );
01672 
01673         if( ext_size + 4 > ext_len )
01674         {
01675             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
01676             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
01677         }
01678 
01679         switch( ext_id )
01680         {
01681         case MBEDTLS_TLS_EXT_RENEGOTIATION_INFO:
01682             MBEDTLS_SSL_DEBUG_MSG( 3, ( "found renegotiation extension" ) );
01683 #if defined(MBEDTLS_SSL_RENEGOTIATION)
01684             renegotiation_info_seen = 1;
01685 #endif
01686 
01687             if( ( ret = ssl_parse_renegotiation_info( ssl, ext + 4,
01688                                                       ext_size ) ) != 0 )
01689                 return( ret );
01690 
01691             break;
01692 
01693 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
01694         case MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH:
01695             MBEDTLS_SSL_DEBUG_MSG( 3, ( "found max_fragment_length extension" ) );
01696 
01697             if( ( ret = ssl_parse_max_fragment_length_ext( ssl,
01698                             ext + 4, ext_size ) ) != 0 )
01699             {
01700                 return( ret );
01701             }
01702 
01703             break;
01704 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
01705 
01706 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
01707         case MBEDTLS_TLS_EXT_TRUNCATED_HMAC:
01708             MBEDTLS_SSL_DEBUG_MSG( 3, ( "found truncated_hmac extension" ) );
01709 
01710             if( ( ret = ssl_parse_truncated_hmac_ext( ssl,
01711                             ext + 4, ext_size ) ) != 0 )
01712             {
01713                 return( ret );
01714             }
01715 
01716             break;
01717 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
01718 
01719 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
01720         case MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC:
01721             MBEDTLS_SSL_DEBUG_MSG( 3, ( "found encrypt_then_mac extension" ) );
01722 
01723             if( ( ret = ssl_parse_encrypt_then_mac_ext( ssl,
01724                             ext + 4, ext_size ) ) != 0 )
01725             {
01726                 return( ret );
01727             }
01728 
01729             break;
01730 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
01731 
01732 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
01733         case MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET:
01734             MBEDTLS_SSL_DEBUG_MSG( 3, ( "found extended_master_secret extension" ) );
01735 
01736             if( ( ret = ssl_parse_extended_ms_ext( ssl,
01737                             ext + 4, ext_size ) ) != 0 )
01738             {
01739                 return( ret );
01740             }
01741 
01742             break;
01743 #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
01744 
01745 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
01746         case MBEDTLS_TLS_EXT_SESSION_TICKET:
01747             MBEDTLS_SSL_DEBUG_MSG( 3, ( "found session_ticket extension" ) );
01748 
01749             if( ( ret = ssl_parse_session_ticket_ext( ssl,
01750                             ext + 4, ext_size ) ) != 0 )
01751             {
01752                 return( ret );
01753             }
01754 
01755             break;
01756 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
01757 
01758 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
01759     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
01760         case MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS:
01761             MBEDTLS_SSL_DEBUG_MSG( 3, ( "found supported_point_formats extension" ) );
01762 
01763             if( ( ret = ssl_parse_supported_point_formats_ext( ssl,
01764                             ext + 4, ext_size ) ) != 0 )
01765             {
01766                 return( ret );
01767             }
01768 
01769             break;
01770 #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
01771           MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
01772 
01773 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
01774         case MBEDTLS_TLS_EXT_ECJPAKE_KKPP:
01775             MBEDTLS_SSL_DEBUG_MSG( 3, ( "found ecjpake_kkpp extension" ) );
01776 
01777             if( ( ret = ssl_parse_ecjpake_kkpp( ssl,
01778                             ext + 4, ext_size ) ) != 0 )
01779             {
01780                 return( ret );
01781             }
01782 
01783             break;
01784 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
01785 
01786 #if defined(MBEDTLS_SSL_ALPN)
01787         case MBEDTLS_TLS_EXT_ALPN:
01788             MBEDTLS_SSL_DEBUG_MSG( 3, ( "found alpn extension" ) );
01789 
01790             if( ( ret = ssl_parse_alpn_ext( ssl, ext + 4, ext_size ) ) != 0 )
01791                 return( ret );
01792 
01793             break;
01794 #endif /* MBEDTLS_SSL_ALPN */
01795 
01796         default:
01797             MBEDTLS_SSL_DEBUG_MSG( 3, ( "unknown extension found: %d (ignoring)",
01798                            ext_id ) );
01799         }
01800 
01801         ext_len -= 4 + ext_size;
01802         ext += 4 + ext_size;
01803 
01804         if( ext_len > 0 && ext_len < 4 )
01805         {
01806             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
01807             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
01808         }
01809     }
01810 
01811     /*
01812      * Renegotiation security checks
01813      */
01814     if( ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
01815         ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE )
01816     {
01817         MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation, breaking off handshake" ) );
01818         handshake_failure = 1;
01819     }
01820 #if defined(MBEDTLS_SSL_RENEGOTIATION)
01821     else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
01822              ssl->secure_renegotiation == MBEDTLS_SSL_SECURE_RENEGOTIATION &&
01823              renegotiation_info_seen == 0 )
01824     {
01825         MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation_info extension missing (secure)" ) );
01826         handshake_failure = 1;
01827     }
01828     else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
01829              ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
01830              ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION )
01831     {
01832         MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation not allowed" ) );
01833         handshake_failure = 1;
01834     }
01835     else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
01836              ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
01837              renegotiation_info_seen == 1 )
01838     {
01839         MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation_info extension present (legacy)" ) );
01840         handshake_failure = 1;
01841     }
01842 #endif /* MBEDTLS_SSL_RENEGOTIATION */
01843 
01844     if( handshake_failure == 1 )
01845     {
01846         if( ( ret = mbedtls_ssl_send_fatal_handshake_failure( ssl ) ) != 0 )
01847             return( ret );
01848 
01849         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
01850     }
01851 
01852     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server hello" ) );
01853 
01854     return( 0 );
01855 }
01856 
01857 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) ||                       \
01858     defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
01859 static int ssl_parse_server_dh_params( mbedtls_ssl_context *ssl, unsigned char **p,
01860                                        unsigned char *end )
01861 {
01862     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
01863 
01864     /*
01865      * Ephemeral DH parameters:
01866      *
01867      * struct {
01868      *     opaque dh_p<1..2^16-1>;
01869      *     opaque dh_g<1..2^16-1>;
01870      *     opaque dh_Ys<1..2^16-1>;
01871      * } ServerDHParams;
01872      */
01873     if( ( ret = mbedtls_dhm_read_params( &ssl->handshake->dhm_ctx, p, end ) ) != 0 )
01874     {
01875         MBEDTLS_SSL_DEBUG_RET( 2, ( "mbedtls_dhm_read_params" ), ret );
01876         return( ret );
01877     }
01878 
01879     if( ssl->handshake->dhm_ctx.len * 8 < ssl->conf->dhm_min_bitlen )
01880     {
01881         MBEDTLS_SSL_DEBUG_MSG( 1, ( "DHM prime too short: %d < %d",
01882                                     ssl->handshake->dhm_ctx.len * 8,
01883                                     ssl->conf->dhm_min_bitlen ) );
01884         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
01885     }
01886 
01887     MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: P ", &ssl->handshake->dhm_ctx.P  );
01888     MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: G ", &ssl->handshake->dhm_ctx.G  );
01889     MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: GY", &ssl->handshake->dhm_ctx.GY );
01890 
01891     return( ret );
01892 }
01893 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
01894           MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
01895 
01896 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||                     \
01897     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) ||                   \
01898     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) ||                     \
01899     defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||                      \
01900     defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
01901 static int ssl_check_server_ecdh_params( const mbedtls_ssl_context *ssl )
01902 {
01903     const mbedtls_ecp_curve_info *curve_info;
01904 
01905     curve_info = mbedtls_ecp_curve_info_from_grp_id( ssl->handshake->ecdh_ctx.grp.id );
01906     if( curve_info == NULL )
01907     {
01908         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
01909         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
01910     }
01911 
01912     MBEDTLS_SSL_DEBUG_MSG( 2, ( "ECDH curve: %s", curve_info->name  ) );
01913 
01914 #if defined(MBEDTLS_ECP_C)
01915     if( mbedtls_ssl_check_curve( ssl, ssl->handshake->ecdh_ctx.grp.id ) != 0 )
01916 #else
01917     if( ssl->handshake->ecdh_ctx.grp.nbits < 163 ||
01918         ssl->handshake->ecdh_ctx.grp.nbits > 521 )
01919 #endif
01920         return( -1 );
01921 
01922     MBEDTLS_SSL_DEBUG_ECP( 3, "ECDH: Qp", &ssl->handshake->ecdh_ctx.Qp );
01923 
01924     return( 0 );
01925 }
01926 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
01927           MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
01928           MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED ||
01929           MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
01930           MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
01931 
01932 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||                     \
01933     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) ||                   \
01934     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
01935 static int ssl_parse_server_ecdh_params( mbedtls_ssl_context *ssl,
01936                                          unsigned char **p,
01937                                          unsigned char *end )
01938 {
01939     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
01940 
01941     /*
01942      * Ephemeral ECDH parameters:
01943      *
01944      * struct {
01945      *     ECParameters curve_params;
01946      *     ECPoint      public;
01947      * } ServerECDHParams;
01948      */
01949     if( ( ret = mbedtls_ecdh_read_params( &ssl->handshake->ecdh_ctx,
01950                                   (const unsigned char **) p, end ) ) != 0 )
01951     {
01952         MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ecdh_read_params" ), ret );
01953         return( ret );
01954     }
01955 
01956     if( ssl_check_server_ecdh_params( ssl ) != 0 )
01957     {
01958         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message (ECDHE curve)" ) );
01959         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
01960     }
01961 
01962     return( ret );
01963 }
01964 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
01965           MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
01966           MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
01967 
01968 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
01969 static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl,
01970                                       unsigned char **p,
01971                                       unsigned char *end )
01972 {
01973     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
01974     size_t  len;
01975     ((void) ssl);
01976 
01977     /*
01978      * PSK parameters:
01979      *
01980      * opaque psk_identity_hint<0..2^16-1>;
01981      */
01982     len = (*p)[0] << 8 | (*p)[1];
01983     *p += 2;
01984 
01985     if( (*p) + len > end )
01986     {
01987         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message (psk_identity_hint length)" ) );
01988         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
01989     }
01990 
01991     /*
01992      * Note: we currently ignore the PKS identity hint, as we only allow one
01993      * PSK to be provisionned on the client. This could be changed later if
01994      * someone needs that feature.
01995      */
01996     *p += len;
01997     ret = 0;
01998 
01999     return( ret );
02000 }
02001 #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
02002 
02003 #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) ||                           \
02004     defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
02005 /*
02006  * Generate a pre-master secret and encrypt it with the server's RSA key
02007  */
02008 static int ssl_write_encrypted_pms( mbedtls_ssl_context *ssl,
02009                                     size_t offset, size_t *olen,
02010                                     size_t pms_offset )
02011 {
02012     int ret;
02013     size_t len_bytes = ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ? 0 : 2;
02014     unsigned char *p = ssl->handshake->premaster + pms_offset;
02015 
02016     if( offset + len_bytes > MBEDTLS_SSL_MAX_CONTENT_LEN )
02017     {
02018         MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small for encrypted pms" ) );
02019         return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
02020     }
02021 
02022     /*
02023      * Generate (part of) the pre-master as
02024      *  struct {
02025      *      ProtocolVersion client_version;
02026      *      opaque random[46];
02027      *  } PreMasterSecret;
02028      */
02029     mbedtls_ssl_write_version( ssl->conf->max_major_ver, ssl->conf->max_minor_ver,
02030                        ssl->conf->transport, p );
02031 
02032     if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p + 2, 46 ) ) != 0 )
02033     {
02034         MBEDTLS_SSL_DEBUG_RET( 1, "f_rng", ret );
02035         return( ret );
02036     }
02037 
02038     ssl->handshake->pmslen = 48;
02039 
02040     if( ssl->session_negotiate->peer_cert == NULL )
02041     {
02042         MBEDTLS_SSL_DEBUG_MSG( 2, ( "certificate required" ) );
02043         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
02044     }
02045 
02046     /*
02047      * Now write it out, encrypted
02048      */
02049     if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk,
02050                 MBEDTLS_PK_RSA ) )
02051     {
02052         MBEDTLS_SSL_DEBUG_MSG( 1, ( "certificate key type mismatch" ) );
02053         return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
02054     }
02055 
02056     if( ( ret = mbedtls_pk_encrypt( &ssl->session_negotiate->peer_cert->pk,
02057                             p, ssl->handshake->pmslen,
02058                             ssl->out_msg + offset + len_bytes, olen,
02059                             MBEDTLS_SSL_MAX_CONTENT_LEN - offset - len_bytes,
02060                             ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
02061     {
02062         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_rsa_pkcs1_encrypt", ret );
02063         return( ret );
02064     }
02065 
02066 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
02067     defined(MBEDTLS_SSL_PROTO_TLS1_2)
02068     if( len_bytes == 2 )
02069     {
02070         ssl->out_msg[offset+0] = (unsigned char)( *olen >> 8 );
02071         ssl->out_msg[offset+1] = (unsigned char)( *olen      );
02072         *olen += 2;
02073     }
02074 #endif
02075 
02076     return( 0 );
02077 }
02078 #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED ||
02079           MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
02080 
02081 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
02082 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) ||                       \
02083     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||                     \
02084     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
02085 static int ssl_parse_signature_algorithm( mbedtls_ssl_context *ssl,
02086                                           unsigned char **p,
02087                                           unsigned char *end,
02088                                           mbedtls_md_type_t *md_alg,
02089                                           mbedtls_pk_type_t *pk_alg )
02090 {
02091     ((void) ssl);
02092     *md_alg = MBEDTLS_MD_NONE;
02093     *pk_alg = MBEDTLS_PK_NONE;
02094 
02095     /* Only in TLS 1.2 */
02096     if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
02097     {
02098         return( 0 );
02099     }
02100 
02101     if( (*p) + 2 > end )
02102         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
02103 
02104     /*
02105      * Get hash algorithm
02106      */
02107     if( ( *md_alg = mbedtls_ssl_md_alg_from_hash( (*p)[0] ) ) == MBEDTLS_MD_NONE )
02108     {
02109         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Server used unsupported "
02110                             "HashAlgorithm %d", *(p)[0] ) );
02111         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
02112     }
02113 
02114     /*
02115      * Get signature algorithm
02116      */
02117     if( ( *pk_alg = mbedtls_ssl_pk_alg_from_sig( (*p)[1] ) ) == MBEDTLS_PK_NONE )
02118     {
02119         MBEDTLS_SSL_DEBUG_MSG( 1, ( "server used unsupported "
02120                             "SignatureAlgorithm %d", (*p)[1] ) );
02121         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
02122     }
02123 
02124     /*
02125      * Check if the hash is acceptable
02126      */
02127     if( mbedtls_ssl_check_sig_hash( ssl, *md_alg ) != 0 )
02128     {
02129         MBEDTLS_SSL_DEBUG_MSG( 1, ( "server used HashAlgorithm "
02130                                     "that was not offered" ) );
02131         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
02132     }
02133 
02134     MBEDTLS_SSL_DEBUG_MSG( 2, ( "Server used SignatureAlgorithm %d", (*p)[1] ) );
02135     MBEDTLS_SSL_DEBUG_MSG( 2, ( "Server used HashAlgorithm %d", (*p)[0] ) );
02136     *p += 2;
02137 
02138     return( 0 );
02139 }
02140 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
02141           MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
02142           MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
02143 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
02144 
02145 #if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
02146     defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
02147 static int ssl_get_ecdh_params_from_cert( mbedtls_ssl_context *ssl )
02148 {
02149     int ret;
02150     const mbedtls_ecp_keypair *peer_key;
02151 
02152     if( ssl->session_negotiate->peer_cert == NULL )
02153     {
02154         MBEDTLS_SSL_DEBUG_MSG( 2, ( "certificate required" ) );
02155         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
02156     }
02157 
02158     if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk,
02159                      MBEDTLS_PK_ECKEY ) )
02160     {
02161         MBEDTLS_SSL_DEBUG_MSG( 1, ( "server key not ECDH capable" ) );
02162         return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
02163     }
02164 
02165     peer_key = mbedtls_pk_ec( ssl->session_negotiate->peer_cert->pk );
02166 
02167     if( ( ret = mbedtls_ecdh_get_params( &ssl->handshake->ecdh_ctx, peer_key,
02168                                  MBEDTLS_ECDH_THEIRS ) ) != 0 )
02169     {
02170         MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ecdh_get_params" ), ret );
02171         return( ret );
02172     }
02173 
02174     if( ssl_check_server_ecdh_params( ssl ) != 0 )
02175     {
02176         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server certificate (ECDH curve)" ) );
02177         return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
02178     }
02179 
02180     return( ret );
02181 }
02182 #endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||
02183           MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
02184 
02185 static int ssl_parse_server_key_exchange( mbedtls_ssl_context *ssl )
02186 {
02187     int ret;
02188     const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
02189     unsigned char *p, *end;
02190 
02191     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server key exchange" ) );
02192 
02193 #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
02194     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA )
02195     {
02196         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse server key exchange" ) );
02197         ssl->state++;
02198         return( 0 );
02199     }
02200     ((void) p);
02201     ((void) end);
02202 #endif
02203 
02204 #if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
02205     defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
02206     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||
02207         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA )
02208     {
02209         if( ( ret = ssl_get_ecdh_params_from_cert( ssl ) ) != 0 )
02210         {
02211             MBEDTLS_SSL_DEBUG_RET( 1, "ssl_get_ecdh_params_from_cert", ret );
02212             return( ret );
02213         }
02214 
02215         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse server key exchange" ) );
02216         ssl->state++;
02217         return( 0 );
02218     }
02219     ((void) p);
02220     ((void) end);
02221 #endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
02222           MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
02223 
02224     if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
02225     {
02226         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
02227         return( ret );
02228     }
02229 
02230     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
02231     {
02232         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
02233         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
02234     }
02235 
02236     /*
02237      * ServerKeyExchange may be skipped with PSK and RSA-PSK when the server
02238      * doesn't use a psk_identity_hint
02239      */
02240     if( ssl->in_msg[0] != MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE )
02241     {
02242         if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
02243             ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
02244         {
02245             ssl->record_read = 1;
02246             goto exit;
02247         }
02248 
02249         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
02250         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
02251     }
02252 
02253     p   = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
02254     end = ssl->in_msg + ssl->in_hslen;
02255     MBEDTLS_SSL_DEBUG_BUF( 3,   "server key exchange", p, end - p );
02256 
02257 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
02258     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
02259         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
02260         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
02261         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
02262     {
02263         if( ssl_parse_server_psk_hint( ssl, &p, end ) != 0 )
02264         {
02265             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
02266             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
02267         }
02268     } /* FALLTROUGH */
02269 #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
02270 
02271 #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) ||                       \
02272     defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
02273     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
02274         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
02275         ; /* nothing more to do */
02276     else
02277 #endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED ||
02278           MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
02279 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) ||                       \
02280     defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
02281     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA ||
02282         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
02283     {
02284         if( ssl_parse_server_dh_params( ssl, &p, end ) != 0 )
02285         {
02286             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
02287             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
02288         }
02289     }
02290     else
02291 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
02292           MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
02293 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||                     \
02294     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) ||                     \
02295     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
02296     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
02297         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
02298         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA )
02299     {
02300         if( ssl_parse_server_ecdh_params( ssl, &p, end ) != 0 )
02301         {
02302             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
02303             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
02304         }
02305     }
02306     else
02307 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
02308           MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED ||
02309           MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
02310 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
02311     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
02312     {
02313         ret = mbedtls_ecjpake_read_round_two( &ssl->handshake->ecjpake_ctx,
02314                                               p, end - p );
02315         if( ret != 0 )
02316         {
02317             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_two", ret );
02318             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
02319         }
02320     }
02321     else
02322 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
02323     {
02324         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
02325         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
02326     }
02327 
02328 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) ||                       \
02329     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||                     \
02330     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
02331     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA ||
02332         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
02333         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA )
02334     {
02335         size_t sig_len, hashlen;
02336         unsigned char hash[64];
02337         mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE;
02338         mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE;
02339         unsigned char *params = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
02340         size_t params_len = p - params;
02341 
02342         /*
02343          * Handle the digitally-signed structure
02344          */
02345 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
02346         if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
02347         {
02348             if( ssl_parse_signature_algorithm( ssl, &p, end,
02349                                                &md_alg, &pk_alg ) != 0 )
02350             {
02351                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
02352                 return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
02353             }
02354 
02355             if( pk_alg != mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info ) )
02356             {
02357                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
02358                 return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
02359             }
02360         }
02361         else
02362 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
02363 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
02364     defined(MBEDTLS_SSL_PROTO_TLS1_1)
02365         if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 )
02366         {
02367             pk_alg = mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info );
02368 
02369             /* Default hash for ECDSA is SHA-1 */
02370             if( pk_alg == MBEDTLS_PK_ECDSA && md_alg == MBEDTLS_MD_NONE )
02371                 md_alg = MBEDTLS_MD_SHA1;
02372         }
02373         else
02374 #endif
02375         {
02376             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
02377             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
02378         }
02379 
02380         /*
02381          * Read signature
02382          */
02383         sig_len = ( p[0] << 8 ) | p[1];
02384         p += 2;
02385 
02386         if( end != p + sig_len )
02387         {
02388             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
02389             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
02390         }
02391 
02392         MBEDTLS_SSL_DEBUG_BUF( 3, "signature", p, sig_len );
02393 
02394         /*
02395          * Compute the hash that has been signed
02396          */
02397 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
02398     defined(MBEDTLS_SSL_PROTO_TLS1_1)
02399         if( md_alg == MBEDTLS_MD_NONE )
02400         {
02401             mbedtls_md5_context mbedtls_md5;
02402             mbedtls_sha1_context mbedtls_sha1;
02403 
02404             mbedtls_md5_init(  &mbedtls_md5  );
02405             mbedtls_sha1_init( &mbedtls_sha1 );
02406 
02407             hashlen = 36;
02408 
02409             /*
02410              * digitally-signed struct {
02411              *     opaque md5_hash[16];
02412              *     opaque sha_hash[20];
02413              * };
02414              *
02415              * md5_hash
02416              *     MD5(ClientHello.random + ServerHello.random
02417              *                            + ServerParams);
02418              * sha_hash
02419              *     SHA(ClientHello.random + ServerHello.random
02420              *                            + ServerParams);
02421              */
02422             mbedtls_md5_starts( &mbedtls_md5 );
02423             mbedtls_md5_update( &mbedtls_md5, ssl->handshake->randbytes, 64 );
02424             mbedtls_md5_update( &mbedtls_md5, params, params_len );
02425             mbedtls_md5_finish( &mbedtls_md5, hash );
02426 
02427             mbedtls_sha1_starts( &mbedtls_sha1 );
02428             mbedtls_sha1_update( &mbedtls_sha1, ssl->handshake->randbytes, 64 );
02429             mbedtls_sha1_update( &mbedtls_sha1, params, params_len );
02430             mbedtls_sha1_finish( &mbedtls_sha1, hash + 16 );
02431 
02432             mbedtls_md5_free(  &mbedtls_md5  );
02433             mbedtls_sha1_free( &mbedtls_sha1 );
02434         }
02435         else
02436 #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
02437           MBEDTLS_SSL_PROTO_TLS1_1 */
02438 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
02439     defined(MBEDTLS_SSL_PROTO_TLS1_2)
02440         if( md_alg != MBEDTLS_MD_NONE )
02441         {
02442             mbedtls_md_context_t ctx;
02443 
02444             mbedtls_md_init( &ctx );
02445 
02446             /* Info from md_alg will be used instead */
02447             hashlen = 0;
02448 
02449             /*
02450              * digitally-signed struct {
02451              *     opaque client_random[32];
02452              *     opaque server_random[32];
02453              *     ServerDHParams params;
02454              * };
02455              */
02456             if( ( ret = mbedtls_md_setup( &ctx,
02457                                      mbedtls_md_info_from_type( md_alg ), 0 ) ) != 0 )
02458             {
02459                 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_setup", ret );
02460                 return( ret );
02461             }
02462 
02463             mbedtls_md_starts( &ctx );
02464             mbedtls_md_update( &ctx, ssl->handshake->randbytes, 64 );
02465             mbedtls_md_update( &ctx, params, params_len );
02466             mbedtls_md_finish( &ctx, hash );
02467             mbedtls_md_free( &ctx );
02468         }
02469         else
02470 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
02471           MBEDTLS_SSL_PROTO_TLS1_2 */
02472         {
02473             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
02474             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
02475         }
02476 
02477         MBEDTLS_SSL_DEBUG_BUF( 3, "parameters hash", hash, hashlen != 0 ? hashlen :
02478             (unsigned int) ( mbedtls_md_get_size( mbedtls_md_info_from_type( md_alg ) ) ) );
02479 
02480         if( ssl->session_negotiate->peer_cert == NULL )
02481         {
02482             MBEDTLS_SSL_DEBUG_MSG( 2, ( "certificate required" ) );
02483             return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
02484         }
02485 
02486         /*
02487          * Verify signature
02488          */
02489         if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk, pk_alg ) )
02490         {
02491             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
02492             return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
02493         }
02494 
02495         if( ( ret = mbedtls_pk_verify( &ssl->session_negotiate->peer_cert->pk,
02496                                md_alg, hash, hashlen, p, sig_len ) ) != 0 )
02497         {
02498             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_verify", ret );
02499             return( ret );
02500         }
02501     }
02502 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
02503           MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
02504           MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
02505 
02506 exit:
02507     ssl->state++;
02508 
02509     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server key exchange" ) );
02510 
02511     return( 0 );
02512 }
02513 
02514 #if !defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)       && \
02515     !defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)   && \
02516     !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) && \
02517     !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
02518 static int ssl_parse_certificate_request( mbedtls_ssl_context *ssl )
02519 {
02520     const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
02521 
02522     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate request" ) );
02523 
02524     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
02525         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
02526         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
02527         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
02528         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
02529     {
02530         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate request" ) );
02531         ssl->state++;
02532         return( 0 );
02533     }
02534 
02535     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
02536     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
02537 }
02538 #else
02539 static int ssl_parse_certificate_request( mbedtls_ssl_context *ssl )
02540 {
02541     int ret;
02542     unsigned char *buf;
02543     size_t n = 0;
02544     size_t cert_type_len = 0, dn_len = 0;
02545     const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
02546 
02547     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate request" ) );
02548 
02549     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
02550         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
02551         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
02552         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
02553         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
02554     {
02555         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate request" ) );
02556         ssl->state++;
02557         return( 0 );
02558     }
02559 
02560     if( ssl->record_read == 0 )
02561     {
02562         if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
02563         {
02564             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
02565             return( ret );
02566         }
02567 
02568         if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
02569         {
02570             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
02571             return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
02572         }
02573 
02574         ssl->record_read = 1;
02575     }
02576 
02577     ssl->client_auth = 0;
02578     ssl->state++;
02579 
02580     if( ssl->in_msg[0] == MBEDTLS_SSL_HS_CERTIFICATE_REQUEST )
02581         ssl->client_auth++;
02582 
02583     MBEDTLS_SSL_DEBUG_MSG( 3, ( "got %s certificate request",
02584                         ssl->client_auth ? "a" : "no" ) );
02585 
02586     if( ssl->client_auth == 0 )
02587         goto exit;
02588 
02589     ssl->record_read = 0;
02590 
02591     /*
02592      *  struct {
02593      *      ClientCertificateType certificate_types<1..2^8-1>;
02594      *      SignatureAndHashAlgorithm
02595      *        supported_signature_algorithms<2^16-1>; -- TLS 1.2 only
02596      *      DistinguishedName certificate_authorities<0..2^16-1>;
02597      *  } CertificateRequest;
02598      *
02599      *  Since we only support a single certificate on clients, let's just
02600      *  ignore all the information that's supposed to help us pick a
02601      *  certificate.
02602      *
02603      *  We could check that our certificate matches the request, and bail out
02604      *  if it doesn't, but it's simpler to just send the certificate anyway,
02605      *  and give the server the opportunity to decide if it should terminate
02606      *  the connection when it doesn't like our certificate.
02607      *
02608      *  Same goes for the hash in TLS 1.2's signature_algorithms: at this
02609      *  point we only have one hash available (see comments in
02610      *  write_certificate_verify), so let's just use what we have.
02611      *
02612      *  However, we still minimally parse the message to check it is at least
02613      *  superficially sane.
02614      */
02615     buf = ssl->in_msg;
02616 
02617     /* certificate_types */
02618     cert_type_len = buf[mbedtls_ssl_hs_hdr_len( ssl )];
02619     n = cert_type_len;
02620 
02621     if( ssl->in_hslen < mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n )
02622     {
02623         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
02624         return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST );
02625     }
02626 
02627     /* supported_signature_algorithms */
02628 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
02629     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
02630     {
02631         size_t sig_alg_len = ( ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 1 + n] <<  8 )
02632                              | ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n]       ) );
02633 
02634         n += 2 + sig_alg_len;
02635 
02636         if( ssl->in_hslen < mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n )
02637         {
02638             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
02639             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST );
02640         }
02641     }
02642 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
02643 
02644     /* certificate_authorities */
02645     dn_len = ( ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 1 + n] <<  8 )
02646              | ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n]       ) );
02647 
02648     n += dn_len;
02649     if( ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n )
02650     {
02651         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
02652         return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST );
02653     }
02654 
02655 exit:
02656     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse certificate request" ) );
02657 
02658     return( 0 );
02659 }
02660 #endif /* !MBEDTLS_KEY_EXCHANGE_RSA_ENABLED &&
02661           !MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED &&
02662           !MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED &&
02663           !MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
02664 
02665 static int ssl_parse_server_hello_done( mbedtls_ssl_context *ssl )
02666 {
02667     int ret;
02668 
02669     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server hello done" ) );
02670 
02671     if( ssl->record_read == 0 )
02672     {
02673         if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
02674         {
02675             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
02676             return( ret );
02677         }
02678 
02679         if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
02680         {
02681             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello done message" ) );
02682             return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
02683         }
02684     }
02685     ssl->record_read = 0;
02686 
02687     if( ssl->in_hslen  != mbedtls_ssl_hs_hdr_len( ssl ) ||
02688         ssl->in_msg[0] != MBEDTLS_SSL_HS_SERVER_HELLO_DONE )
02689     {
02690         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello done message" ) );
02691         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO_DONE );
02692     }
02693 
02694     ssl->state++;
02695 
02696 #if defined(MBEDTLS_SSL_PROTO_DTLS)
02697     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
02698         mbedtls_ssl_recv_flight_completed( ssl );
02699 #endif
02700 
02701     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server hello done" ) );
02702 
02703     return( 0 );
02704 }
02705 
02706 static int ssl_write_client_key_exchange( mbedtls_ssl_context *ssl )
02707 {
02708     int ret;
02709     size_t i, n;
02710     const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
02711 
02712     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write client key exchange" ) );
02713 
02714 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)
02715     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA )
02716     {
02717         /*
02718          * DHM key exchange -- send G^X mod P
02719          */
02720         n = ssl->handshake->dhm_ctx.len;
02721 
02722         ssl->out_msg[4] = (unsigned char)( n >> 8 );
02723         ssl->out_msg[5] = (unsigned char)( n      );
02724         i = 6;
02725 
02726         ret = mbedtls_dhm_make_public( &ssl->handshake->dhm_ctx,
02727                                 (int) mbedtls_mpi_size( &ssl->handshake->dhm_ctx.P ),
02728                                &ssl->out_msg[i], n,
02729                                 ssl->conf->f_rng, ssl->conf->p_rng );
02730         if( ret != 0 )
02731         {
02732             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_make_public", ret );
02733             return( ret );
02734         }
02735 
02736         MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: X ", &ssl->handshake->dhm_ctx.X  );
02737         MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: GX", &ssl->handshake->dhm_ctx.GX );
02738 
02739         if( ( ret = mbedtls_dhm_calc_secret( &ssl->handshake->dhm_ctx,
02740                                       ssl->handshake->premaster,
02741                                       MBEDTLS_PREMASTER_SIZE,
02742                                      &ssl->handshake->pmslen,
02743                                       ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
02744         {
02745             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_calc_secret", ret );
02746             return( ret );
02747         }
02748 
02749         MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: K ", &ssl->handshake->dhm_ctx.K  );
02750     }
02751     else
02752 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED */
02753 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||                     \
02754     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) ||                   \
02755     defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||                      \
02756     defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
02757     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
02758         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA ||
02759         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||
02760         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA )
02761     {
02762         /*
02763          * ECDH key exchange -- send client public value
02764          */
02765         i = 4;
02766 
02767         ret = mbedtls_ecdh_make_public( &ssl->handshake->ecdh_ctx,
02768                                 &n,
02769                                 &ssl->out_msg[i], 1000,
02770                                 ssl->conf->f_rng, ssl->conf->p_rng );
02771         if( ret != 0 )
02772         {
02773             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_make_public", ret );
02774             return( ret );
02775         }
02776 
02777         MBEDTLS_SSL_DEBUG_ECP( 3, "ECDH: Q", &ssl->handshake->ecdh_ctx.Q );
02778 
02779         if( ( ret = mbedtls_ecdh_calc_secret( &ssl->handshake->ecdh_ctx,
02780                                       &ssl->handshake->pmslen,
02781                                        ssl->handshake->premaster,
02782                                        MBEDTLS_MPI_MAX_SIZE,
02783                                        ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
02784         {
02785             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_calc_secret", ret );
02786             return( ret );
02787         }
02788 
02789         MBEDTLS_SSL_DEBUG_MPI( 3, "ECDH: z", &ssl->handshake->ecdh_ctx.z );
02790     }
02791     else
02792 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
02793           MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
02794           MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
02795           MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
02796 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
02797     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
02798         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
02799         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
02800         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
02801     {
02802         /*
02803          * opaque psk_identity<0..2^16-1>;
02804          */
02805         if( ssl->conf->psk == NULL || ssl->conf->psk_identity == NULL )
02806         {
02807             MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no private key for PSK" ) );
02808             return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );
02809         }
02810 
02811         i = 4;
02812         n = ssl->conf->psk_identity_len;
02813 
02814         if( i + 2 + n > MBEDTLS_SSL_MAX_CONTENT_LEN )
02815         {
02816             MBEDTLS_SSL_DEBUG_MSG( 1, ( "psk identity too long or "
02817                                         "SSL buffer too short" ) );
02818             return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
02819         }
02820 
02821         ssl->out_msg[i++] = (unsigned char)( n >> 8 );
02822         ssl->out_msg[i++] = (unsigned char)( n      );
02823 
02824         memcpy( ssl->out_msg + i, ssl->conf->psk_identity, ssl->conf->psk_identity_len );
02825         i += ssl->conf->psk_identity_len;
02826 
02827 #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
02828         if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK )
02829         {
02830             n = 0;
02831         }
02832         else
02833 #endif
02834 #if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
02835         if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
02836         {
02837             if( ( ret = ssl_write_encrypted_pms( ssl, i, &n, 2 ) ) != 0 )
02838                 return( ret );
02839         }
02840         else
02841 #endif
02842 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
02843         if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
02844         {
02845             /*
02846              * ClientDiffieHellmanPublic public (DHM send G^X mod P)
02847              */
02848             n = ssl->handshake->dhm_ctx.len;
02849 
02850             if( i + 2 + n > MBEDTLS_SSL_MAX_CONTENT_LEN )
02851             {
02852                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "psk identity or DHM size too long"
02853                                             " or SSL buffer too short" ) );
02854                 return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
02855             }
02856 
02857             ssl->out_msg[i++] = (unsigned char)( n >> 8 );
02858             ssl->out_msg[i++] = (unsigned char)( n      );
02859 
02860             ret = mbedtls_dhm_make_public( &ssl->handshake->dhm_ctx,
02861                     (int) mbedtls_mpi_size( &ssl->handshake->dhm_ctx.P ),
02862                     &ssl->out_msg[i], n,
02863                     ssl->conf->f_rng, ssl->conf->p_rng );
02864             if( ret != 0 )
02865             {
02866                 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_make_public", ret );
02867                 return( ret );
02868             }
02869         }
02870         else
02871 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
02872 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
02873         if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
02874         {
02875             /*
02876              * ClientECDiffieHellmanPublic public;
02877              */
02878             ret = mbedtls_ecdh_make_public( &ssl->handshake->ecdh_ctx, &n,
02879                     &ssl->out_msg[i], MBEDTLS_SSL_MAX_CONTENT_LEN - i,
02880                     ssl->conf->f_rng, ssl->conf->p_rng );
02881             if( ret != 0 )
02882             {
02883                 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_make_public", ret );
02884                 return( ret );
02885             }
02886 
02887             MBEDTLS_SSL_DEBUG_ECP( 3, "ECDH: Q", &ssl->handshake->ecdh_ctx.Q );
02888         }
02889         else
02890 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
02891         {
02892             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
02893             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
02894         }
02895 
02896         if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl,
02897                         ciphersuite_info->key_exchange ) ) != 0 )
02898         {
02899             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_psk_derive_premaster", ret );
02900             return( ret );
02901         }
02902     }
02903     else
02904 #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
02905 #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
02906     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA )
02907     {
02908         i = 4;
02909         if( ( ret = ssl_write_encrypted_pms( ssl, i, &n, 0 ) ) != 0 )
02910             return( ret );
02911     }
02912     else
02913 #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */
02914 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
02915     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
02916     {
02917         i = 4;
02918 
02919         ret = mbedtls_ecjpake_write_round_two( &ssl->handshake->ecjpake_ctx,
02920                 ssl->out_msg + i, MBEDTLS_SSL_MAX_CONTENT_LEN - i, &n,
02921                 ssl->conf->f_rng, ssl->conf->p_rng );
02922         if( ret != 0 )
02923         {
02924             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_write_round_two", ret );
02925             return( ret );
02926         }
02927 
02928         ret = mbedtls_ecjpake_derive_secret( &ssl->handshake->ecjpake_ctx,
02929                 ssl->handshake->premaster, 32, &ssl->handshake->pmslen,
02930                 ssl->conf->f_rng, ssl->conf->p_rng );
02931         if( ret != 0 )
02932         {
02933             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_derive_secret", ret );
02934             return( ret );
02935         }
02936     }
02937     else
02938 #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */
02939     {
02940         ((void) ciphersuite_info);
02941         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
02942         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
02943     }
02944 
02945     ssl->out_msglen  = i + n;
02946     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
02947     ssl->out_msg[0]  = MBEDTLS_SSL_HS_CLIENT_KEY_EXCHANGE;
02948 
02949     ssl->state++;
02950 
02951     if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
02952     {
02953         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
02954         return( ret );
02955     }
02956 
02957     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write client key exchange" ) );
02958 
02959     return( 0 );
02960 }
02961 
02962 #if !defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)       && \
02963     !defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)   && \
02964     !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) && \
02965     !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
02966 static int ssl_write_certificate_verify( mbedtls_ssl_context *ssl )
02967 {
02968     const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
02969     int ret;
02970 
02971     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate verify" ) );
02972 
02973     if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )
02974     {
02975         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret );
02976         return( ret );
02977     }
02978 
02979     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
02980         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
02981         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
02982         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
02983         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
02984     {
02985         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate verify" ) );
02986         ssl->state++;
02987         return( 0 );
02988     }
02989 
02990     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
02991     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
02992 }
02993 #else
02994 static int ssl_write_certificate_verify( mbedtls_ssl_context *ssl )
02995 {
02996     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
02997     const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
02998     size_t n = 0, offset = 0;
02999     unsigned char hash[48];
03000     unsigned char *hash_start = hash;
03001     mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE;
03002     unsigned int hashlen;
03003 
03004     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate verify" ) );
03005 
03006     if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )
03007     {
03008         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret );
03009         return( ret );
03010     }
03011 
03012     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
03013         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
03014         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
03015         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
03016         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
03017     {
03018         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate verify" ) );
03019         ssl->state++;
03020         return( 0 );
03021     }
03022 
03023     if( ssl->client_auth == 0 || mbedtls_ssl_own_cert( ssl ) == NULL )
03024     {
03025         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate verify" ) );
03026         ssl->state++;
03027         return( 0 );
03028     }
03029 
03030     if( mbedtls_ssl_own_key( ssl ) == NULL )
03031     {
03032         MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no private key for certificate" ) );
03033         return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );
03034     }
03035 
03036     /*
03037      * Make an RSA signature of the handshake digests
03038      */
03039     ssl->handshake->calc_verify( ssl, hash );
03040 
03041 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
03042     defined(MBEDTLS_SSL_PROTO_TLS1_1)
03043     if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
03044     {
03045         /*
03046          * digitally-signed struct {
03047          *     opaque md5_hash[16];
03048          *     opaque sha_hash[20];
03049          * };
03050          *
03051          * md5_hash
03052          *     MD5(handshake_messages);
03053          *
03054          * sha_hash
03055          *     SHA(handshake_messages);
03056          */
03057         hashlen = 36;
03058         md_alg = MBEDTLS_MD_NONE;
03059 
03060         /*
03061          * For ECDSA, default hash is SHA-1 only
03062          */
03063         if( mbedtls_pk_can_do( mbedtls_ssl_own_key( ssl ), MBEDTLS_PK_ECDSA ) )
03064         {
03065             hash_start += 16;
03066             hashlen -= 16;
03067             md_alg = MBEDTLS_MD_SHA1;
03068         }
03069     }
03070     else
03071 #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
03072           MBEDTLS_SSL_PROTO_TLS1_1 */
03073 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
03074     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
03075     {
03076         /*
03077          * digitally-signed struct {
03078          *     opaque handshake_messages[handshake_messages_length];
03079          * };
03080          *
03081          * Taking shortcut here. We assume that the server always allows the
03082          * PRF Hash function and has sent it in the allowed signature
03083          * algorithms list received in the Certificate Request message.
03084          *
03085          * Until we encounter a server that does not, we will take this
03086          * shortcut.
03087          *
03088          * Reason: Otherwise we should have running hashes for SHA512 and SHA224
03089          *         in order to satisfy 'weird' needs from the server side.
03090          */
03091         if( ssl->transform_negotiate->ciphersuite_info->mac ==
03092             MBEDTLS_MD_SHA384 )
03093         {
03094             md_alg = MBEDTLS_MD_SHA384;
03095             ssl->out_msg[4] = MBEDTLS_SSL_HASH_SHA384;
03096         }
03097         else
03098         {
03099             md_alg = MBEDTLS_MD_SHA256;
03100             ssl->out_msg[4] = MBEDTLS_SSL_HASH_SHA256;
03101         }
03102         ssl->out_msg[5] = mbedtls_ssl_sig_from_pk( mbedtls_ssl_own_key( ssl ) );
03103 
03104         /* Info from md_alg will be used instead */
03105         hashlen = 0;
03106         offset = 2;
03107     }
03108     else
03109 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
03110     {
03111         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
03112         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
03113     }
03114 
03115     if( ( ret = mbedtls_pk_sign( mbedtls_ssl_own_key( ssl ), md_alg, hash_start, hashlen,
03116                          ssl->out_msg + 6 + offset, &n,
03117                          ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
03118     {
03119         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_sign", ret );
03120         return( ret );
03121     }
03122 
03123     ssl->out_msg[4 + offset] = (unsigned char)( n >> 8 );
03124     ssl->out_msg[5 + offset] = (unsigned char)( n      );
03125 
03126     ssl->out_msglen  = 6 + n + offset;
03127     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
03128     ssl->out_msg[0]  = MBEDTLS_SSL_HS_CERTIFICATE_VERIFY;
03129 
03130     ssl->state++;
03131 
03132     if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
03133     {
03134         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
03135         return( ret );
03136     }
03137 
03138     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write certificate verify" ) );
03139 
03140     return( ret );
03141 }
03142 #endif /* !MBEDTLS_KEY_EXCHANGE_RSA_ENABLED &&
03143           !MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED &&
03144           !MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED */
03145 
03146 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
03147 static int ssl_parse_new_session_ticket( mbedtls_ssl_context *ssl )
03148 {
03149     int ret;
03150     uint32_t lifetime;
03151     size_t ticket_len;
03152     unsigned char *ticket;
03153     const unsigned char *msg;
03154 
03155     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse new session ticket" ) );
03156 
03157     if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
03158     {
03159         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
03160         return( ret );
03161     }
03162 
03163     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
03164     {
03165         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad new session ticket message" ) );
03166         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
03167     }
03168 
03169     /*
03170      * struct {
03171      *     uint32 ticket_lifetime_hint;
03172      *     opaque ticket<0..2^16-1>;
03173      * } NewSessionTicket;
03174      *
03175      * 0  .  3   ticket_lifetime_hint
03176      * 4  .  5   ticket_len (n)
03177      * 6  .  5+n ticket content
03178      */
03179     if( ssl->in_msg[0] != MBEDTLS_SSL_HS_NEW_SESSION_TICKET ||
03180         ssl->in_hslen < 6 + mbedtls_ssl_hs_hdr_len( ssl ) )
03181     {
03182         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad new session ticket message" ) );
03183         return( MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET );
03184     }
03185 
03186     msg = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
03187 
03188     lifetime = ( msg[0] << 24 ) | ( msg[1] << 16 ) |
03189                ( msg[2] <<  8 ) | ( msg[3]       );
03190 
03191     ticket_len = ( msg[4] << 8 ) | ( msg[5] );
03192 
03193     if( ticket_len + 6 + mbedtls_ssl_hs_hdr_len( ssl ) != ssl->in_hslen )
03194     {
03195         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad new session ticket message" ) );
03196         return( MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET );
03197     }
03198 
03199     MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket length: %d", ticket_len ) );
03200 
03201     /* We're not waiting for a NewSessionTicket message any more */
03202     ssl->handshake->new_session_ticket = 0;
03203     ssl->state = MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC;
03204 
03205     /*
03206      * Zero-length ticket means the server changed his mind and doesn't want
03207      * to send a ticket after all, so just forget it
03208      */
03209     if( ticket_len == 0 )
03210         return( 0 );
03211 
03212     mbedtls_zeroize( ssl->session_negotiate->ticket,
03213                       ssl->session_negotiate->ticket_len );
03214     mbedtls_free( ssl->session_negotiate->ticket );
03215     ssl->session_negotiate->ticket = NULL;
03216     ssl->session_negotiate->ticket_len = 0;
03217 
03218     if( ( ticket = mbedtls_calloc( 1, ticket_len ) ) == NULL )
03219     {
03220         MBEDTLS_SSL_DEBUG_MSG( 1, ( "ticket alloc failed" ) );
03221         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
03222     }
03223 
03224     memcpy( ticket, msg + 6, ticket_len );
03225 
03226     ssl->session_negotiate->ticket = ticket;
03227     ssl->session_negotiate->ticket_len = ticket_len;
03228     ssl->session_negotiate->ticket_lifetime = lifetime;
03229 
03230     /*
03231      * RFC 5077 section 3.4:
03232      * "If the client receives a session ticket from the server, then it
03233      * discards any Session ID that was sent in the ServerHello."
03234      */
03235     MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket in use, discarding session id" ) );
03236     ssl->session_negotiate->id_len = 0;
03237 
03238     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse new session ticket" ) );
03239 
03240     return( 0 );
03241 }
03242 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
03243 
03244 /*
03245  * SSL handshake -- client side -- single step
03246  */
03247 int mbedtls_ssl_handshake_client_step( mbedtls_ssl_context *ssl )
03248 {
03249     int ret = 0;
03250 
03251     if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER || ssl->handshake == NULL )
03252         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
03253 
03254     MBEDTLS_SSL_DEBUG_MSG( 2, ( "client state: %d", ssl->state ) );
03255 
03256     if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
03257         return( ret );
03258 
03259 #if defined(MBEDTLS_SSL_PROTO_DTLS)
03260     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
03261         ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING )
03262     {
03263         if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )
03264             return( ret );
03265     }
03266 #endif
03267 
03268     /* Change state now, so that it is right in mbedtls_ssl_read_record(), used
03269      * by DTLS for dropping out-of-sequence ChangeCipherSpec records */
03270 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
03271     if( ssl->state == MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC &&
03272         ssl->handshake->new_session_ticket != 0 )
03273     {
03274         ssl->state = MBEDTLS_SSL_SERVER_NEW_SESSION_TICKET;
03275     }
03276 #endif
03277 
03278     switch( ssl->state )
03279     {
03280         case MBEDTLS_SSL_HELLO_REQUEST:
03281             ssl->state = MBEDTLS_SSL_CLIENT_HELLO;
03282             break;
03283 
03284        /*
03285         *  ==>   ClientHello
03286         */
03287        case MBEDTLS_SSL_CLIENT_HELLO:
03288            ret = ssl_write_client_hello( ssl );
03289            break;
03290 
03291        /*
03292         *  <==   ServerHello
03293         *        Certificate
03294         *      ( ServerKeyExchange  )
03295         *      ( CertificateRequest )
03296         *        ServerHelloDone
03297         */
03298        case MBEDTLS_SSL_SERVER_HELLO:
03299            ret = ssl_parse_server_hello( ssl );
03300            break;
03301 
03302        case MBEDTLS_SSL_SERVER_CERTIFICATE:
03303            ret = mbedtls_ssl_parse_certificate( ssl );
03304            break;
03305 
03306        case MBEDTLS_SSL_SERVER_KEY_EXCHANGE:
03307            ret = ssl_parse_server_key_exchange( ssl );
03308            break;
03309 
03310        case MBEDTLS_SSL_CERTIFICATE_REQUEST:
03311            ret = ssl_parse_certificate_request( ssl );
03312            break;
03313 
03314        case MBEDTLS_SSL_SERVER_HELLO_DONE:
03315            ret = ssl_parse_server_hello_done( ssl );
03316            break;
03317 
03318        /*
03319         *  ==> ( Certificate/Alert  )
03320         *        ClientKeyExchange
03321         *      ( CertificateVerify  )
03322         *        ChangeCipherSpec
03323         *        Finished
03324         */
03325        case MBEDTLS_SSL_CLIENT_CERTIFICATE:
03326            ret = mbedtls_ssl_write_certificate( ssl );
03327            break;
03328 
03329        case MBEDTLS_SSL_CLIENT_KEY_EXCHANGE:
03330            ret = ssl_write_client_key_exchange( ssl );
03331            break;
03332 
03333        case MBEDTLS_SSL_CERTIFICATE_VERIFY:
03334            ret = ssl_write_certificate_verify( ssl );
03335            break;
03336 
03337        case MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC:
03338            ret = mbedtls_ssl_write_change_cipher_spec( ssl );
03339            break;
03340 
03341        case MBEDTLS_SSL_CLIENT_FINISHED:
03342            ret = mbedtls_ssl_write_finished( ssl );
03343            break;
03344 
03345        /*
03346         *  <==   ( NewSessionTicket )
03347         *        ChangeCipherSpec
03348         *        Finished
03349         */
03350 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
03351        case MBEDTLS_SSL_SERVER_NEW_SESSION_TICKET:
03352            ret = ssl_parse_new_session_ticket( ssl );
03353            break;
03354 #endif
03355 
03356        case MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC:
03357            ret = mbedtls_ssl_parse_change_cipher_spec( ssl );
03358            break;
03359 
03360        case MBEDTLS_SSL_SERVER_FINISHED:
03361            ret = mbedtls_ssl_parse_finished( ssl );
03362            break;
03363 
03364        case MBEDTLS_SSL_FLUSH_BUFFERS:
03365            MBEDTLS_SSL_DEBUG_MSG( 2, ( "handshake: done" ) );
03366            ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
03367            break;
03368 
03369        case MBEDTLS_SSL_HANDSHAKE_WRAPUP:
03370            mbedtls_ssl_handshake_wrapup( ssl );
03371            break;
03372 
03373        default:
03374            MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid state %d", ssl->state ) );
03375            return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
03376    }
03377 
03378     return( ret );
03379 }
03380 #endif /* MBEDTLS_SSL_CLI_C */