takashi kadono / Mbed OS Nucleo446_SSD1331

Dependencies:   ssd1331

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers ssl_tls.c Source File

ssl_tls.c

00001 /*
00002  *  SSLv3/TLSv1 shared 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  *  The SSL 3.0 specification was drafted by Netscape in 1996,
00023  *  and became an IETF standard in 1999.
00024  *
00025  *  http://wp.netscape.com/eng/ssl3/
00026  *  http://www.ietf.org/rfc/rfc2246.txt
00027  *  http://www.ietf.org/rfc/rfc4346.txt
00028  */
00029 
00030 #if !defined(MBEDTLS_CONFIG_FILE)
00031 #include "mbedtls/config.h"
00032 #else
00033 #include MBEDTLS_CONFIG_FILE
00034 #endif
00035 
00036 #if defined(MBEDTLS_SSL_TLS_C)
00037 
00038 #if defined(MBEDTLS_PLATFORM_C)
00039 #include "mbedtls/platform.h"
00040 #else
00041 #include <stdlib.h>
00042 #define mbedtls_calloc    calloc
00043 #define mbedtls_free      free
00044 #endif
00045 
00046 #include "mbedtls/debug.h"
00047 #include "mbedtls/ssl.h"
00048 #include "mbedtls/ssl_internal.h"
00049 #include "mbedtls/platform_util.h"
00050 
00051 #include <string.h>
00052 
00053 #if defined(MBEDTLS_X509_CRT_PARSE_C)
00054 #include "mbedtls/oid.h"
00055 #endif
00056 
00057 static void ssl_reset_in_out_pointers( mbedtls_ssl_context *ssl );
00058 static uint32_t ssl_get_hs_total_len( mbedtls_ssl_context const *ssl );
00059 
00060 /* Length of the "epoch" field in the record header */
00061 static inline size_t ssl_ep_len( const mbedtls_ssl_context *ssl )
00062 {
00063 #if defined(MBEDTLS_SSL_PROTO_DTLS)
00064     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
00065         return( 2 );
00066 #else
00067     ((void) ssl);
00068 #endif
00069     return( 0 );
00070 }
00071 
00072 /*
00073  * Start a timer.
00074  * Passing millisecs = 0 cancels a running timer.
00075  */
00076 static void ssl_set_timer( mbedtls_ssl_context *ssl, uint32_t millisecs )
00077 {
00078     if( ssl->f_set_timer == NULL )
00079         return;
00080 
00081     MBEDTLS_SSL_DEBUG_MSG( 3, ( "set_timer to %d ms", (int) millisecs ) );
00082     ssl->f_set_timer( ssl->p_timer, millisecs / 4, millisecs );
00083 }
00084 
00085 /*
00086  * Return -1 is timer is expired, 0 if it isn't.
00087  */
00088 static int ssl_check_timer( mbedtls_ssl_context *ssl )
00089 {
00090     if( ssl->f_get_timer == NULL )
00091         return( 0 );
00092 
00093     if( ssl->f_get_timer( ssl->p_timer ) == 2 )
00094     {
00095         MBEDTLS_SSL_DEBUG_MSG( 3, ( "timer expired" ) );
00096         return( -1 );
00097     }
00098 
00099     return( 0 );
00100 }
00101 
00102 static void ssl_update_out_pointers( mbedtls_ssl_context *ssl,
00103                                      mbedtls_ssl_transform *transform );
00104 static void ssl_update_in_pointers( mbedtls_ssl_context *ssl,
00105                                     mbedtls_ssl_transform *transform );
00106 
00107 #define SSL_DONT_FORCE_FLUSH 0
00108 #define SSL_FORCE_FLUSH      1
00109 
00110 #if defined(MBEDTLS_SSL_PROTO_DTLS)
00111 
00112 /* Forward declarations for functions related to message buffering. */
00113 static void ssl_buffering_free( mbedtls_ssl_context *ssl );
00114 static void ssl_buffering_free_slot( mbedtls_ssl_context *ssl,
00115                                      uint8_t slot );
00116 static void ssl_free_buffered_record( mbedtls_ssl_context *ssl );
00117 static int ssl_load_buffered_message( mbedtls_ssl_context *ssl );
00118 static int ssl_load_buffered_record( mbedtls_ssl_context *ssl );
00119 static int ssl_buffer_message( mbedtls_ssl_context *ssl );
00120 static int ssl_buffer_future_record( mbedtls_ssl_context *ssl );
00121 static int ssl_next_record_is_in_datagram( mbedtls_ssl_context *ssl );
00122 
00123 static size_t ssl_get_current_mtu( const mbedtls_ssl_context *ssl );
00124 static size_t ssl_get_maximum_datagram_size( mbedtls_ssl_context const *ssl )
00125 {
00126     size_t mtu = ssl_get_current_mtu( ssl );
00127 
00128     if( mtu != 0 && mtu < MBEDTLS_SSL_OUT_BUFFER_LEN )
00129         return( mtu );
00130 
00131     return( MBEDTLS_SSL_OUT_BUFFER_LEN );
00132 }
00133 
00134 static int ssl_get_remaining_space_in_datagram( mbedtls_ssl_context const *ssl )
00135 {
00136     size_t const bytes_written = ssl->out_left;
00137     size_t const mtu           = ssl_get_maximum_datagram_size( ssl );
00138 
00139     /* Double-check that the write-index hasn't gone
00140      * past what we can transmit in a single datagram. */
00141     if( bytes_written > mtu )
00142     {
00143         /* Should never happen... */
00144         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
00145     }
00146 
00147     return( (int) ( mtu - bytes_written ) );
00148 }
00149 
00150 static int ssl_get_remaining_payload_in_datagram( mbedtls_ssl_context const *ssl )
00151 {
00152     int ret;
00153     size_t remaining, expansion;
00154     size_t max_len = MBEDTLS_SSL_MAX_CONTENT_LEN;
00155 
00156 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
00157     const size_t mfl = mbedtls_ssl_get_max_frag_len( ssl );
00158 
00159     if( max_len > mfl )
00160         max_len = mfl;
00161 
00162     /* By the standard (RFC 6066 Sect. 4), the MFL extension
00163      * only limits the maximum record payload size, so in theory
00164      * we would be allowed to pack multiple records of payload size
00165      * MFL into a single datagram. However, this would mean that there's
00166      * no way to explicitly communicate MTU restrictions to the peer.
00167      *
00168      * The following reduction of max_len makes sure that we never
00169      * write datagrams larger than MFL + Record Expansion Overhead.
00170      */
00171     if( max_len <= ssl->out_left )
00172         return( 0 );
00173 
00174     max_len -= ssl->out_left;
00175 #endif
00176 
00177     ret = ssl_get_remaining_space_in_datagram( ssl );
00178     if( ret < 0 )
00179         return( ret );
00180     remaining = (size_t) ret;
00181 
00182     ret = mbedtls_ssl_get_record_expansion( ssl );
00183     if( ret < 0 )
00184         return( ret );
00185     expansion = (size_t) ret;
00186 
00187     if( remaining <= expansion )
00188         return( 0 );
00189 
00190     remaining -= expansion;
00191     if( remaining >= max_len )
00192         remaining = max_len;
00193 
00194     return( (int) remaining );
00195 }
00196 
00197 /*
00198  * Double the retransmit timeout value, within the allowed range,
00199  * returning -1 if the maximum value has already been reached.
00200  */
00201 static int ssl_double_retransmit_timeout( mbedtls_ssl_context *ssl )
00202 {
00203     uint32_t new_timeout;
00204 
00205     if( ssl->handshake->retransmit_timeout >= ssl->conf->hs_timeout_max )
00206         return( -1 );
00207 
00208     /* Implement the final paragraph of RFC 6347 section 4.1.1.1
00209      * in the following way: after the initial transmission and a first
00210      * retransmission, back off to a temporary estimated MTU of 508 bytes.
00211      * This value is guaranteed to be deliverable (if not guaranteed to be
00212      * delivered) of any compliant IPv4 (and IPv6) network, and should work
00213      * on most non-IP stacks too. */
00214     if( ssl->handshake->retransmit_timeout != ssl->conf->hs_timeout_min )
00215         ssl->handshake->mtu = 508;
00216 
00217     new_timeout = 2 * ssl->handshake->retransmit_timeout;
00218 
00219     /* Avoid arithmetic overflow and range overflow */
00220     if( new_timeout < ssl->handshake->retransmit_timeout ||
00221         new_timeout > ssl->conf->hs_timeout_max )
00222     {
00223         new_timeout = ssl->conf->hs_timeout_max;
00224     }
00225 
00226     ssl->handshake->retransmit_timeout = new_timeout;
00227     MBEDTLS_SSL_DEBUG_MSG( 3, ( "update timeout value to %d millisecs",
00228                         ssl->handshake->retransmit_timeout ) );
00229 
00230     return( 0 );
00231 }
00232 
00233 static void ssl_reset_retransmit_timeout( mbedtls_ssl_context *ssl )
00234 {
00235     ssl->handshake->retransmit_timeout = ssl->conf->hs_timeout_min;
00236     MBEDTLS_SSL_DEBUG_MSG( 3, ( "update timeout value to %d millisecs",
00237                         ssl->handshake->retransmit_timeout ) );
00238 }
00239 #endif /* MBEDTLS_SSL_PROTO_DTLS */
00240 
00241 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
00242 /*
00243  * Convert max_fragment_length codes to length.
00244  * RFC 6066 says:
00245  *    enum{
00246  *        2^9(1), 2^10(2), 2^11(3), 2^12(4), (255)
00247  *    } MaxFragmentLength;
00248  * and we add 0 -> extension unused
00249  */
00250 static unsigned int ssl_mfl_code_to_length( int mfl )
00251 {
00252     switch( mfl )
00253     {
00254     case MBEDTLS_SSL_MAX_FRAG_LEN_NONE:
00255         return ( MBEDTLS_TLS_EXT_ADV_CONTENT_LEN );
00256     case MBEDTLS_SSL_MAX_FRAG_LEN_512:
00257         return 512;
00258     case MBEDTLS_SSL_MAX_FRAG_LEN_1024:
00259         return 1024;
00260     case MBEDTLS_SSL_MAX_FRAG_LEN_2048:
00261         return 2048;
00262     case MBEDTLS_SSL_MAX_FRAG_LEN_4096:
00263         return 4096;
00264     default:
00265         return ( MBEDTLS_TLS_EXT_ADV_CONTENT_LEN );
00266     }
00267 }
00268 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
00269 
00270 #if defined(MBEDTLS_SSL_CLI_C)
00271 static int ssl_session_copy( mbedtls_ssl_session *dst, const mbedtls_ssl_session *src )
00272 {
00273     mbedtls_ssl_session_free( dst );
00274     memcpy( dst, src, sizeof( mbedtls_ssl_session ) );
00275 
00276 #if defined(MBEDTLS_X509_CRT_PARSE_C)
00277     if( src->peer_cert != NULL )
00278     {
00279         int ret;
00280 
00281         dst->peer_cert = mbedtls_calloc( 1, sizeof(mbedtls_x509_crt) );
00282         if( dst->peer_cert == NULL )
00283             return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
00284 
00285         mbedtls_x509_crt_init( dst->peer_cert );
00286 
00287         if( ( ret = mbedtls_x509_crt_parse_der( dst->peer_cert, src->peer_cert->raw.p,
00288                                         src->peer_cert->raw.len ) ) != 0 )
00289         {
00290             mbedtls_free( dst->peer_cert );
00291             dst->peer_cert = NULL;
00292             return( ret );
00293         }
00294     }
00295 #endif /* MBEDTLS_X509_CRT_PARSE_C */
00296 
00297 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
00298     if( src->ticket != NULL )
00299     {
00300         dst->ticket = mbedtls_calloc( 1, src->ticket_len );
00301         if( dst->ticket == NULL )
00302             return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
00303 
00304         memcpy( dst->ticket, src->ticket, src->ticket_len );
00305     }
00306 #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */
00307 
00308     return( 0 );
00309 }
00310 #endif /* MBEDTLS_SSL_CLI_C */
00311 
00312 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
00313 int (*mbedtls_ssl_hw_record_init)( mbedtls_ssl_context *ssl,
00314                      const unsigned char *key_enc, const unsigned char *key_dec,
00315                      size_t keylen,
00316                      const unsigned char *iv_enc,  const unsigned char *iv_dec,
00317                      size_t ivlen,
00318                      const unsigned char *mac_enc, const unsigned char *mac_dec,
00319                      size_t maclen ) = NULL;
00320 int (*mbedtls_ssl_hw_record_activate)( mbedtls_ssl_context *ssl, int direction) = NULL;
00321 int (*mbedtls_ssl_hw_record_reset)( mbedtls_ssl_context *ssl ) = NULL;
00322 int (*mbedtls_ssl_hw_record_write)( mbedtls_ssl_context *ssl ) = NULL;
00323 int (*mbedtls_ssl_hw_record_read)( mbedtls_ssl_context *ssl ) = NULL;
00324 int (*mbedtls_ssl_hw_record_finish)( mbedtls_ssl_context *ssl ) = NULL;
00325 #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
00326 
00327 /*
00328  * Key material generation
00329  */
00330 #if defined(MBEDTLS_SSL_PROTO_SSL3)
00331 static int ssl3_prf( const unsigned char *secret, size_t slen,
00332                      const char *label,
00333                      const unsigned char *random, size_t rlen,
00334                      unsigned char *dstbuf, size_t dlen )
00335 {
00336     int ret = 0;
00337     size_t i;
00338     mbedtls_md5_context md5;
00339     mbedtls_sha1_context sha1;
00340     unsigned char padding[16];
00341     unsigned char sha1sum[20];
00342     ((void)label);
00343 
00344     mbedtls_md5_init(  &md5  );
00345     mbedtls_sha1_init( &sha1 );
00346 
00347     /*
00348      *  SSLv3:
00349      *    block =
00350      *      MD5( secret + SHA1( 'A'    + secret + random ) ) +
00351      *      MD5( secret + SHA1( 'BB'   + secret + random ) ) +
00352      *      MD5( secret + SHA1( 'CCC'  + secret + random ) ) +
00353      *      ...
00354      */
00355     for( i = 0; i < dlen / 16; i++ )
00356     {
00357         memset( padding, (unsigned char) ('A' + i), 1 + i );
00358 
00359         if( ( ret = mbedtls_sha1_starts_ret( &sha1 ) ) != 0 )
00360             goto exit;
00361         if( ( ret = mbedtls_sha1_update_ret( &sha1, padding, 1 + i ) ) != 0 )
00362             goto exit;
00363         if( ( ret = mbedtls_sha1_update_ret( &sha1, secret, slen ) ) != 0 )
00364             goto exit;
00365         if( ( ret = mbedtls_sha1_update_ret( &sha1, random, rlen ) ) != 0 )
00366             goto exit;
00367         if( ( ret = mbedtls_sha1_finish_ret( &sha1, sha1sum ) ) != 0 )
00368             goto exit;
00369 
00370         if( ( ret = mbedtls_md5_starts_ret( &md5 ) ) != 0 )
00371             goto exit;
00372         if( ( ret = mbedtls_md5_update_ret( &md5, secret, slen ) ) != 0 )
00373             goto exit;
00374         if( ( ret = mbedtls_md5_update_ret( &md5, sha1sum, 20 ) ) != 0 )
00375             goto exit;
00376         if( ( ret = mbedtls_md5_finish_ret( &md5, dstbuf + i * 16 ) ) != 0 )
00377             goto exit;
00378     }
00379 
00380 exit:
00381     mbedtls_md5_free(  &md5  );
00382     mbedtls_sha1_free( &sha1 );
00383 
00384     mbedtls_platform_zeroize( padding, sizeof( padding ) );
00385     mbedtls_platform_zeroize( sha1sum, sizeof( sha1sum ) );
00386 
00387     return( ret );
00388 }
00389 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
00390 
00391 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
00392 static int tls1_prf( const unsigned char *secret, size_t slen,
00393                      const char *label,
00394                      const unsigned char *random, size_t rlen,
00395                      unsigned char *dstbuf, size_t dlen )
00396 {
00397     size_t nb, hs;
00398     size_t i, j, k;
00399     const unsigned char *S1, *S2;
00400     unsigned char tmp[128];
00401     unsigned char h_i[20];
00402     const mbedtls_md_info_t *md_info;
00403     mbedtls_md_context_t md_ctx;
00404     int ret;
00405 
00406     mbedtls_md_init( &md_ctx );
00407 
00408     if( sizeof( tmp ) < 20 + strlen( label ) + rlen )
00409         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
00410 
00411     hs = ( slen + 1 ) / 2;
00412     S1 = secret;
00413     S2 = secret + slen - hs;
00414 
00415     nb = strlen( label );
00416     memcpy( tmp + 20, label, nb );
00417     memcpy( tmp + 20 + nb, random, rlen );
00418     nb += rlen;
00419 
00420     /*
00421      * First compute P_md5(secret,label+random)[0..dlen]
00422      */
00423     if( ( md_info = mbedtls_md_info_from_type( MBEDTLS_MD_MD5 ) ) == NULL )
00424         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
00425 
00426     if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )
00427         return( ret );
00428 
00429     mbedtls_md_hmac_starts( &md_ctx, S1, hs );
00430     mbedtls_md_hmac_update( &md_ctx, tmp + 20, nb );
00431     mbedtls_md_hmac_finish( &md_ctx, 4 + tmp );
00432 
00433     for( i = 0; i < dlen; i += 16 )
00434     {
00435         mbedtls_md_hmac_reset ( &md_ctx );
00436         mbedtls_md_hmac_update( &md_ctx, 4 + tmp, 16 + nb );
00437         mbedtls_md_hmac_finish( &md_ctx, h_i );
00438 
00439         mbedtls_md_hmac_reset ( &md_ctx );
00440         mbedtls_md_hmac_update( &md_ctx, 4 + tmp, 16 );
00441         mbedtls_md_hmac_finish( &md_ctx, 4 + tmp );
00442 
00443         k = ( i + 16 > dlen ) ? dlen % 16 : 16;
00444 
00445         for( j = 0; j < k; j++ )
00446             dstbuf[i + j]  = h_i[j];
00447     }
00448 
00449     mbedtls_md_free( &md_ctx );
00450 
00451     /*
00452      * XOR out with P_sha1(secret,label+random)[0..dlen]
00453      */
00454     if( ( md_info = mbedtls_md_info_from_type( MBEDTLS_MD_SHA1 ) ) == NULL )
00455         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
00456 
00457     if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )
00458         return( ret );
00459 
00460     mbedtls_md_hmac_starts( &md_ctx, S2, hs );
00461     mbedtls_md_hmac_update( &md_ctx, tmp + 20, nb );
00462     mbedtls_md_hmac_finish( &md_ctx, tmp );
00463 
00464     for( i = 0; i < dlen; i += 20 )
00465     {
00466         mbedtls_md_hmac_reset ( &md_ctx );
00467         mbedtls_md_hmac_update( &md_ctx, tmp, 20 + nb );
00468         mbedtls_md_hmac_finish( &md_ctx, h_i );
00469 
00470         mbedtls_md_hmac_reset ( &md_ctx );
00471         mbedtls_md_hmac_update( &md_ctx, tmp, 20 );
00472         mbedtls_md_hmac_finish( &md_ctx, tmp );
00473 
00474         k = ( i + 20 > dlen ) ? dlen % 20 : 20;
00475 
00476         for( j = 0; j < k; j++ )
00477             dstbuf[i + j] = (unsigned char)( dstbuf[i + j] ^ h_i[j] );
00478     }
00479 
00480     mbedtls_md_free( &md_ctx );
00481 
00482     mbedtls_platform_zeroize( tmp, sizeof( tmp ) );
00483     mbedtls_platform_zeroize( h_i, sizeof( h_i ) );
00484 
00485     return( 0 );
00486 }
00487 #endif /* MBEDTLS_SSL_PROTO_TLS1) || MBEDTLS_SSL_PROTO_TLS1_1 */
00488 
00489 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
00490 static int tls_prf_generic( mbedtls_md_type_t md_type,
00491                             const unsigned char *secret, size_t slen,
00492                             const char *label,
00493                             const unsigned char *random, size_t rlen,
00494                             unsigned char *dstbuf, size_t dlen )
00495 {
00496     size_t nb;
00497     size_t i, j, k, md_len;
00498     unsigned char tmp[128];
00499     unsigned char h_i[MBEDTLS_MD_MAX_SIZE];
00500     const mbedtls_md_info_t *md_info;
00501     mbedtls_md_context_t md_ctx;
00502     int ret;
00503 
00504     mbedtls_md_init( &md_ctx );
00505 
00506     if( ( md_info = mbedtls_md_info_from_type( md_type ) ) == NULL )
00507         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
00508 
00509     md_len = mbedtls_md_get_size( md_info );
00510 
00511     if( sizeof( tmp ) < md_len + strlen( label ) + rlen )
00512         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
00513 
00514     nb = strlen( label );
00515     memcpy( tmp + md_len, label, nb );
00516     memcpy( tmp + md_len + nb, random, rlen );
00517     nb += rlen;
00518 
00519     /*
00520      * Compute P_<hash>(secret, label + random)[0..dlen]
00521      */
00522     if ( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )
00523         return( ret );
00524 
00525     mbedtls_md_hmac_starts( &md_ctx, secret, slen );
00526     mbedtls_md_hmac_update( &md_ctx, tmp + md_len, nb );
00527     mbedtls_md_hmac_finish( &md_ctx, tmp );
00528 
00529     for( i = 0; i < dlen; i += md_len )
00530     {
00531         mbedtls_md_hmac_reset ( &md_ctx );
00532         mbedtls_md_hmac_update( &md_ctx, tmp, md_len + nb );
00533         mbedtls_md_hmac_finish( &md_ctx, h_i );
00534 
00535         mbedtls_md_hmac_reset ( &md_ctx );
00536         mbedtls_md_hmac_update( &md_ctx, tmp, md_len );
00537         mbedtls_md_hmac_finish( &md_ctx, tmp );
00538 
00539         k = ( i + md_len > dlen ) ? dlen % md_len : md_len;
00540 
00541         for( j = 0; j < k; j++ )
00542             dstbuf[i + j]  = h_i[j];
00543     }
00544 
00545     mbedtls_md_free( &md_ctx );
00546 
00547     mbedtls_platform_zeroize( tmp, sizeof( tmp ) );
00548     mbedtls_platform_zeroize( h_i, sizeof( h_i ) );
00549 
00550     return( 0 );
00551 }
00552 
00553 #if defined(MBEDTLS_SHA256_C)
00554 static int tls_prf_sha256( const unsigned char *secret, size_t slen,
00555                            const char *label,
00556                            const unsigned char *random, size_t rlen,
00557                            unsigned char *dstbuf, size_t dlen )
00558 {
00559     return( tls_prf_generic( MBEDTLS_MD_SHA256, secret, slen,
00560                              label, random, rlen, dstbuf, dlen ) );
00561 }
00562 #endif /* MBEDTLS_SHA256_C */
00563 
00564 #if defined(MBEDTLS_SHA512_C)
00565 static int tls_prf_sha384( const unsigned char *secret, size_t slen,
00566                            const char *label,
00567                            const unsigned char *random, size_t rlen,
00568                            unsigned char *dstbuf, size_t dlen )
00569 {
00570     return( tls_prf_generic( MBEDTLS_MD_SHA384, secret, slen,
00571                              label, random, rlen, dstbuf, dlen ) );
00572 }
00573 #endif /* MBEDTLS_SHA512_C */
00574 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
00575 
00576 static void ssl_update_checksum_start( mbedtls_ssl_context *, const unsigned char *, size_t );
00577 
00578 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
00579     defined(MBEDTLS_SSL_PROTO_TLS1_1)
00580 static void ssl_update_checksum_md5sha1( mbedtls_ssl_context *, const unsigned char *, size_t );
00581 #endif
00582 
00583 #if defined(MBEDTLS_SSL_PROTO_SSL3)
00584 static void ssl_calc_verify_ssl( mbedtls_ssl_context *, unsigned char * );
00585 static void ssl_calc_finished_ssl( mbedtls_ssl_context *, unsigned char *, int );
00586 #endif
00587 
00588 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
00589 static void ssl_calc_verify_tls( mbedtls_ssl_context *, unsigned char * );
00590 static void ssl_calc_finished_tls( mbedtls_ssl_context *, unsigned char *, int );
00591 #endif
00592 
00593 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
00594 #if defined(MBEDTLS_SHA256_C)
00595 static void ssl_update_checksum_sha256( mbedtls_ssl_context *, const unsigned char *, size_t );
00596 static void ssl_calc_verify_tls_sha256( mbedtls_ssl_context *,unsigned char * );
00597 static void ssl_calc_finished_tls_sha256( mbedtls_ssl_context *,unsigned char *, int );
00598 #endif
00599 
00600 #if defined(MBEDTLS_SHA512_C)
00601 static void ssl_update_checksum_sha384( mbedtls_ssl_context *, const unsigned char *, size_t );
00602 static void ssl_calc_verify_tls_sha384( mbedtls_ssl_context *, unsigned char * );
00603 static void ssl_calc_finished_tls_sha384( mbedtls_ssl_context *, unsigned char *, int );
00604 #endif
00605 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
00606 
00607 int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl )
00608 {
00609     int ret = 0;
00610     unsigned char tmp[64];
00611     unsigned char keyblk[256];
00612     unsigned char *key1;
00613     unsigned char *key2;
00614     unsigned char *mac_enc;
00615     unsigned char *mac_dec;
00616     size_t mac_key_len;
00617     size_t iv_copy_len;
00618     const mbedtls_cipher_info_t *cipher_info;
00619     const mbedtls_md_info_t *md_info;
00620 
00621     mbedtls_ssl_session *session = ssl->session_negotiate;
00622     mbedtls_ssl_transform *transform = ssl->transform_negotiate;
00623     mbedtls_ssl_handshake_params *handshake = ssl->handshake;
00624 
00625     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> derive keys" ) );
00626 
00627     cipher_info = mbedtls_cipher_info_from_type( transform->ciphersuite_info->cipher );
00628     if( cipher_info == NULL )
00629     {
00630         MBEDTLS_SSL_DEBUG_MSG( 1, ( "cipher info for %d not found",
00631                             transform->ciphersuite_info->cipher ) );
00632         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
00633     }
00634 
00635     md_info = mbedtls_md_info_from_type( transform->ciphersuite_info->mac );
00636     if( md_info == NULL )
00637     {
00638         MBEDTLS_SSL_DEBUG_MSG( 1, ( "mbedtls_md info for %d not found",
00639                             transform->ciphersuite_info->mac ) );
00640         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
00641     }
00642 
00643     /*
00644      * Set appropriate PRF function and other SSL / TLS / TLS1.2 functions
00645      */
00646 #if defined(MBEDTLS_SSL_PROTO_SSL3)
00647     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
00648     {
00649         handshake->tls_prf = ssl3_prf;
00650         handshake->calc_verify = ssl_calc_verify_ssl;
00651         handshake->calc_finished = ssl_calc_finished_ssl;
00652     }
00653     else
00654 #endif
00655 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
00656     if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 )
00657     {
00658         handshake->tls_prf = tls1_prf;
00659         handshake->calc_verify = ssl_calc_verify_tls;
00660         handshake->calc_finished = ssl_calc_finished_tls;
00661     }
00662     else
00663 #endif
00664 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
00665 #if defined(MBEDTLS_SHA512_C)
00666     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 &&
00667         transform->ciphersuite_info->mac == MBEDTLS_MD_SHA384 )
00668     {
00669         handshake->tls_prf = tls_prf_sha384;
00670         handshake->calc_verify = ssl_calc_verify_tls_sha384;
00671         handshake->calc_finished = ssl_calc_finished_tls_sha384;
00672     }
00673     else
00674 #endif
00675 #if defined(MBEDTLS_SHA256_C)
00676     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
00677     {
00678         handshake->tls_prf = tls_prf_sha256;
00679         handshake->calc_verify = ssl_calc_verify_tls_sha256;
00680         handshake->calc_finished = ssl_calc_finished_tls_sha256;
00681     }
00682     else
00683 #endif
00684 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
00685     {
00686         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
00687         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
00688     }
00689 
00690     /*
00691      * SSLv3:
00692      *   master =
00693      *     MD5( premaster + SHA1( 'A'   + premaster + randbytes ) ) +
00694      *     MD5( premaster + SHA1( 'BB'  + premaster + randbytes ) ) +
00695      *     MD5( premaster + SHA1( 'CCC' + premaster + randbytes ) )
00696      *
00697      * TLSv1+:
00698      *   master = PRF( premaster, "master secret", randbytes )[0..47]
00699      */
00700     if( handshake->resume == 0 )
00701     {
00702         MBEDTLS_SSL_DEBUG_BUF( 3, "premaster secret", handshake->premaster,
00703                        handshake->pmslen );
00704 
00705 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
00706         if( ssl->handshake->extended_ms == MBEDTLS_SSL_EXTENDED_MS_ENABLED )
00707         {
00708             unsigned char session_hash[48];
00709             size_t hash_len;
00710 
00711             MBEDTLS_SSL_DEBUG_MSG( 3, ( "using extended master secret" ) );
00712 
00713             ssl->handshake->calc_verify( ssl, session_hash );
00714 
00715 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
00716             if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
00717             {
00718 #if defined(MBEDTLS_SHA512_C)
00719                 if( ssl->transform_negotiate->ciphersuite_info->mac ==
00720                     MBEDTLS_MD_SHA384 )
00721                 {
00722                     hash_len = 48;
00723                 }
00724                 else
00725 #endif
00726                     hash_len = 32;
00727             }
00728             else
00729 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
00730                 hash_len = 36;
00731 
00732             MBEDTLS_SSL_DEBUG_BUF( 3, "session hash", session_hash, hash_len );
00733 
00734             ret = handshake->tls_prf( handshake->premaster, handshake->pmslen,
00735                                       "extended master secret",
00736                                       session_hash, hash_len,
00737                                       session->master, 48 );
00738             if( ret != 0 )
00739             {
00740                 MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret );
00741                 return( ret );
00742             }
00743 
00744         }
00745         else
00746 #endif
00747         ret = handshake->tls_prf( handshake->premaster, handshake->pmslen,
00748                                   "master secret",
00749                                   handshake->randbytes, 64,
00750                                   session->master, 48 );
00751         if( ret != 0 )
00752         {
00753             MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret );
00754             return( ret );
00755         }
00756 
00757         mbedtls_platform_zeroize( handshake->premaster,
00758                                   sizeof(handshake->premaster) );
00759     }
00760     else
00761         MBEDTLS_SSL_DEBUG_MSG( 3, ( "no premaster (session resumed)" ) );
00762 
00763     /*
00764      * Swap the client and server random values.
00765      */
00766     memcpy( tmp, handshake->randbytes, 64 );
00767     memcpy( handshake->randbytes, tmp + 32, 32 );
00768     memcpy( handshake->randbytes + 32, tmp, 32 );
00769     mbedtls_platform_zeroize( tmp, sizeof( tmp ) );
00770 
00771     /*
00772      *  SSLv3:
00773      *    key block =
00774      *      MD5( master + SHA1( 'A'    + master + randbytes ) ) +
00775      *      MD5( master + SHA1( 'BB'   + master + randbytes ) ) +
00776      *      MD5( master + SHA1( 'CCC'  + master + randbytes ) ) +
00777      *      MD5( master + SHA1( 'DDDD' + master + randbytes ) ) +
00778      *      ...
00779      *
00780      *  TLSv1:
00781      *    key block = PRF( master, "key expansion", randbytes )
00782      */
00783     ret = handshake->tls_prf( session->master, 48, "key expansion",
00784                               handshake->randbytes, 64, keyblk, 256 );
00785     if( ret != 0 )
00786     {
00787         MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret );
00788         return( ret );
00789     }
00790 
00791     MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite = %s",
00792                    mbedtls_ssl_get_ciphersuite_name( session->ciphersuite ) ) );
00793     MBEDTLS_SSL_DEBUG_BUF( 3, "master secret", session->master, 48 );
00794     MBEDTLS_SSL_DEBUG_BUF( 4, "random bytes", handshake->randbytes, 64 );
00795     MBEDTLS_SSL_DEBUG_BUF( 4, "key block", keyblk, 256 );
00796 
00797     mbedtls_platform_zeroize( handshake->randbytes,
00798                               sizeof( handshake->randbytes ) );
00799 
00800     /*
00801      * Determine the appropriate key, IV and MAC length.
00802      */
00803 
00804     transform->keylen = cipher_info->key_bitlen / 8;
00805 
00806     if( cipher_info->mode == MBEDTLS_MODE_GCM ||
00807         cipher_info->mode == MBEDTLS_MODE_CCM ||
00808         cipher_info->mode == MBEDTLS_MODE_CHACHAPOLY )
00809     {
00810         size_t taglen, explicit_ivlen;
00811 
00812         transform->maclen = 0;
00813         mac_key_len = 0;
00814 
00815         /* All modes haves 96-bit IVs;
00816          * GCM and CCM has 4 implicit and 8 explicit bytes
00817          * ChachaPoly has all 12 bytes implicit
00818          */
00819         transform->ivlen = 12;
00820         if( cipher_info->mode == MBEDTLS_MODE_CHACHAPOLY )
00821             transform->fixed_ivlen = 12;
00822         else
00823             transform->fixed_ivlen = 4;
00824 
00825         /* All modes have 128-bit tags, except CCM_8 (ciphersuite flag) */
00826         taglen = transform->ciphersuite_info->flags &
00827                   MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16;
00828 
00829 
00830         /* Minimum length of encrypted record */
00831         explicit_ivlen = transform->ivlen - transform->fixed_ivlen;
00832         transform->minlen = explicit_ivlen + taglen;
00833     }
00834     else
00835     {
00836         /* Initialize HMAC contexts */
00837         if( ( ret = mbedtls_md_setup( &transform->md_ctx_enc, md_info, 1 ) ) != 0 ||
00838             ( ret = mbedtls_md_setup( &transform->md_ctx_dec, md_info, 1 ) ) != 0 )
00839         {
00840             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_setup", ret );
00841             return( ret );
00842         }
00843 
00844         /* Get MAC length */
00845         mac_key_len = mbedtls_md_get_size( md_info );
00846         transform->maclen = mac_key_len;
00847 
00848 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
00849         /*
00850          * If HMAC is to be truncated, we shall keep the leftmost bytes,
00851          * (rfc 6066 page 13 or rfc 2104 section 4),
00852          * so we only need to adjust the length here.
00853          */
00854         if( session->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_ENABLED )
00855         {
00856             transform->maclen = MBEDTLS_SSL_TRUNCATED_HMAC_LEN;
00857 
00858 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT)
00859             /* Fall back to old, non-compliant version of the truncated
00860              * HMAC implementation which also truncates the key
00861              * (Mbed TLS versions from 1.3 to 2.6.0) */
00862             mac_key_len = transform->maclen;
00863 #endif
00864         }
00865 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
00866 
00867         /* IV length */
00868         transform->ivlen = cipher_info->iv_size;
00869 
00870         /* Minimum length */
00871         if( cipher_info->mode == MBEDTLS_MODE_STREAM )
00872             transform->minlen = transform->maclen;
00873         else
00874         {
00875             /*
00876              * GenericBlockCipher:
00877              * 1. if EtM is in use: one block plus MAC
00878              *    otherwise: * first multiple of blocklen greater than maclen
00879              * 2. IV except for SSL3 and TLS 1.0
00880              */
00881 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
00882             if( session->encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED )
00883             {
00884                 transform->minlen = transform->maclen
00885                                   + cipher_info->block_size;
00886             }
00887             else
00888 #endif
00889             {
00890                 transform->minlen = transform->maclen
00891                                   + cipher_info->block_size
00892                                   - transform->maclen % cipher_info->block_size;
00893             }
00894 
00895 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1)
00896             if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ||
00897                 ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_1 )
00898                 ; /* No need to adjust minlen */
00899             else
00900 #endif
00901 #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
00902             if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_2 ||
00903                 ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
00904             {
00905                 transform->minlen += transform->ivlen;
00906             }
00907             else
00908 #endif
00909             {
00910                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
00911                 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
00912             }
00913         }
00914     }
00915 
00916     MBEDTLS_SSL_DEBUG_MSG( 3, ( "keylen: %d, minlen: %d, ivlen: %d, maclen: %d",
00917                    transform->keylen, transform->minlen, transform->ivlen,
00918                    transform->maclen ) );
00919 
00920     /*
00921      * Finally setup the cipher contexts, IVs and MAC secrets.
00922      */
00923 #if defined(MBEDTLS_SSL_CLI_C)
00924     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
00925     {
00926         key1 = keyblk + mac_key_len * 2;
00927         key2 = keyblk + mac_key_len * 2 + transform->keylen;
00928 
00929         mac_enc = keyblk;
00930         mac_dec = keyblk + mac_key_len;
00931 
00932         /*
00933          * This is not used in TLS v1.1.
00934          */
00935         iv_copy_len = ( transform->fixed_ivlen ) ?
00936                             transform->fixed_ivlen : transform->ivlen;
00937         memcpy( transform->iv_enc, key2 + transform->keylen,  iv_copy_len );
00938         memcpy( transform->iv_dec, key2 + transform->keylen + iv_copy_len,
00939                 iv_copy_len );
00940     }
00941     else
00942 #endif /* MBEDTLS_SSL_CLI_C */
00943 #if defined(MBEDTLS_SSL_SRV_C)
00944     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
00945     {
00946         key1 = keyblk + mac_key_len * 2 + transform->keylen;
00947         key2 = keyblk + mac_key_len * 2;
00948 
00949         mac_enc = keyblk + mac_key_len;
00950         mac_dec = keyblk;
00951 
00952         /*
00953          * This is not used in TLS v1.1.
00954          */
00955         iv_copy_len = ( transform->fixed_ivlen ) ?
00956                             transform->fixed_ivlen : transform->ivlen;
00957         memcpy( transform->iv_dec, key1 + transform->keylen,  iv_copy_len );
00958         memcpy( transform->iv_enc, key1 + transform->keylen + iv_copy_len,
00959                 iv_copy_len );
00960     }
00961     else
00962 #endif /* MBEDTLS_SSL_SRV_C */
00963     {
00964         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
00965         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
00966     }
00967 
00968 #if defined(MBEDTLS_SSL_PROTO_SSL3)
00969     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
00970     {
00971         if( mac_key_len > sizeof transform->mac_enc )
00972         {
00973             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
00974             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
00975         }
00976 
00977         memcpy( transform->mac_enc, mac_enc, mac_key_len );
00978         memcpy( transform->mac_dec, mac_dec, mac_key_len );
00979     }
00980     else
00981 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
00982 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
00983     defined(MBEDTLS_SSL_PROTO_TLS1_2)
00984     if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 )
00985     {
00986         /* For HMAC-based ciphersuites, initialize the HMAC transforms.
00987            For AEAD-based ciphersuites, there is nothing to do here. */
00988         if( mac_key_len != 0 )
00989         {
00990             mbedtls_md_hmac_starts( &transform->md_ctx_enc, mac_enc, mac_key_len );
00991             mbedtls_md_hmac_starts( &transform->md_ctx_dec, mac_dec, mac_key_len );
00992         }
00993     }
00994     else
00995 #endif
00996     {
00997         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
00998         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
00999     }
01000 
01001 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
01002     if( mbedtls_ssl_hw_record_init != NULL )
01003     {
01004         int ret = 0;
01005 
01006         MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_init()" ) );
01007 
01008         if( ( ret = mbedtls_ssl_hw_record_init( ssl, key1, key2, transform->keylen,
01009                                         transform->iv_enc, transform->iv_dec,
01010                                         iv_copy_len,
01011                                         mac_enc, mac_dec,
01012                                         mac_key_len ) ) != 0 )
01013         {
01014             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_init", ret );
01015             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
01016         }
01017     }
01018 #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
01019 
01020 #if defined(MBEDTLS_SSL_EXPORT_KEYS)
01021     if( ssl->conf->f_export_keys != NULL )
01022     {
01023         ssl->conf->f_export_keys( ssl->conf->p_export_keys,
01024                                   session->master, keyblk,
01025                                   mac_key_len, transform->keylen,
01026                                   iv_copy_len );
01027     }
01028 #endif
01029 
01030     if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_enc,
01031                                  cipher_info ) ) != 0 )
01032     {
01033         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup", ret );
01034         return( ret );
01035     }
01036 
01037     if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_dec,
01038                                  cipher_info ) ) != 0 )
01039     {
01040         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup", ret );
01041         return( ret );
01042     }
01043 
01044     if( ( ret = mbedtls_cipher_setkey( &transform->cipher_ctx_enc, key1,
01045                                cipher_info->key_bitlen,
01046                                MBEDTLS_ENCRYPT ) ) != 0 )
01047     {
01048         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setkey", ret );
01049         return( ret );
01050     }
01051 
01052     if( ( ret = mbedtls_cipher_setkey( &transform->cipher_ctx_dec, key2,
01053                                cipher_info->key_bitlen,
01054                                MBEDTLS_DECRYPT ) ) != 0 )
01055     {
01056         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setkey", ret );
01057         return( ret );
01058     }
01059 
01060 #if defined(MBEDTLS_CIPHER_MODE_CBC)
01061     if( cipher_info->mode == MBEDTLS_MODE_CBC )
01062     {
01063         if( ( ret = mbedtls_cipher_set_padding_mode( &transform->cipher_ctx_enc,
01064                                              MBEDTLS_PADDING_NONE ) ) != 0 )
01065         {
01066             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_set_padding_mode", ret );
01067             return( ret );
01068         }
01069 
01070         if( ( ret = mbedtls_cipher_set_padding_mode( &transform->cipher_ctx_dec,
01071                                              MBEDTLS_PADDING_NONE ) ) != 0 )
01072         {
01073             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_set_padding_mode", ret );
01074             return( ret );
01075         }
01076     }
01077 #endif /* MBEDTLS_CIPHER_MODE_CBC */
01078 
01079     mbedtls_platform_zeroize( keyblk, sizeof( keyblk ) );
01080 
01081 #if defined(MBEDTLS_ZLIB_SUPPORT)
01082     // Initialize compression
01083     //
01084     if( session->compression == MBEDTLS_SSL_COMPRESS_DEFLATE )
01085     {
01086         if( ssl->compress_buf == NULL )
01087         {
01088             MBEDTLS_SSL_DEBUG_MSG( 3, ( "Allocating compression buffer" ) );
01089             ssl->compress_buf = mbedtls_calloc( 1, MBEDTLS_SSL_COMPRESS_BUFFER_LEN );
01090             if( ssl->compress_buf == NULL )
01091             {
01092                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed",
01093                                     MBEDTLS_SSL_COMPRESS_BUFFER_LEN ) );
01094                 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
01095             }
01096         }
01097 
01098         MBEDTLS_SSL_DEBUG_MSG( 3, ( "Initializing zlib states" ) );
01099 
01100         memset( &transform->ctx_deflate, 0, sizeof( transform->ctx_deflate ) );
01101         memset( &transform->ctx_inflate, 0, sizeof( transform->ctx_inflate ) );
01102 
01103         if( deflateInit( &transform->ctx_deflate,
01104                          Z_DEFAULT_COMPRESSION )   != Z_OK ||
01105             inflateInit( &transform->ctx_inflate ) != Z_OK )
01106         {
01107             MBEDTLS_SSL_DEBUG_MSG( 1, ( "Failed to initialize compression" ) );
01108             return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED );
01109         }
01110     }
01111 #endif /* MBEDTLS_ZLIB_SUPPORT */
01112 
01113     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= derive keys" ) );
01114 
01115     return( 0 );
01116 }
01117 
01118 #if defined(MBEDTLS_SSL_PROTO_SSL3)
01119 void ssl_calc_verify_ssl( mbedtls_ssl_context *ssl, unsigned char hash[36] )
01120 {
01121     mbedtls_md5_context md5;
01122     mbedtls_sha1_context sha1;
01123     unsigned char pad_1[48];
01124     unsigned char pad_2[48];
01125 
01126     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify ssl" ) );
01127 
01128     mbedtls_md5_init( &md5 );
01129     mbedtls_sha1_init( &sha1 );
01130 
01131     mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
01132     mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
01133 
01134     memset( pad_1, 0x36, 48 );
01135     memset( pad_2, 0x5C, 48 );
01136 
01137     mbedtls_md5_update_ret( &md5, ssl->session_negotiate->master, 48 );
01138     mbedtls_md5_update_ret( &md5, pad_1, 48 );
01139     mbedtls_md5_finish_ret( &md5, hash );
01140 
01141     mbedtls_md5_starts_ret( &md5 );
01142     mbedtls_md5_update_ret( &md5, ssl->session_negotiate->master, 48 );
01143     mbedtls_md5_update_ret( &md5, pad_2, 48 );
01144     mbedtls_md5_update_ret( &md5, hash,  16 );
01145     mbedtls_md5_finish_ret( &md5, hash );
01146 
01147     mbedtls_sha1_update_ret( &sha1, ssl->session_negotiate->master, 48 );
01148     mbedtls_sha1_update_ret( &sha1, pad_1, 40 );
01149     mbedtls_sha1_finish_ret( &sha1, hash + 16 );
01150 
01151     mbedtls_sha1_starts_ret( &sha1 );
01152     mbedtls_sha1_update_ret( &sha1, ssl->session_negotiate->master, 48 );
01153     mbedtls_sha1_update_ret( &sha1, pad_2, 40 );
01154     mbedtls_sha1_update_ret( &sha1, hash + 16, 20 );
01155     mbedtls_sha1_finish_ret( &sha1, hash + 16 );
01156 
01157     MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 36 );
01158     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
01159 
01160     mbedtls_md5_free(  &md5  );
01161     mbedtls_sha1_free( &sha1 );
01162 
01163     return;
01164 }
01165 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
01166 
01167 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
01168 void ssl_calc_verify_tls( mbedtls_ssl_context *ssl, unsigned char hash[36] )
01169 {
01170     mbedtls_md5_context md5;
01171     mbedtls_sha1_context sha1;
01172 
01173     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify tls" ) );
01174 
01175     mbedtls_md5_init( &md5 );
01176     mbedtls_sha1_init( &sha1 );
01177 
01178     mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
01179     mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
01180 
01181      mbedtls_md5_finish_ret( &md5,  hash );
01182     mbedtls_sha1_finish_ret( &sha1, hash + 16 );
01183 
01184     MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 36 );
01185     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
01186 
01187     mbedtls_md5_free(  &md5  );
01188     mbedtls_sha1_free( &sha1 );
01189 
01190     return;
01191 }
01192 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
01193 
01194 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
01195 #if defined(MBEDTLS_SHA256_C)
01196 void ssl_calc_verify_tls_sha256( mbedtls_ssl_context *ssl, unsigned char hash[32] )
01197 {
01198     mbedtls_sha256_context sha256;
01199 
01200     mbedtls_sha256_init( &sha256 );
01201 
01202     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify sha256" ) );
01203 
01204     mbedtls_sha256_clone( &sha256, &ssl->handshake->fin_sha256 );
01205     mbedtls_sha256_finish_ret( &sha256, hash );
01206 
01207     MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 32 );
01208     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
01209 
01210     mbedtls_sha256_free( &sha256 );
01211 
01212     return;
01213 }
01214 #endif /* MBEDTLS_SHA256_C */
01215 
01216 #if defined(MBEDTLS_SHA512_C)
01217 void ssl_calc_verify_tls_sha384( mbedtls_ssl_context *ssl, unsigned char hash[48] )
01218 {
01219     mbedtls_sha512_context sha512;
01220 
01221     mbedtls_sha512_init( &sha512 );
01222 
01223     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify sha384" ) );
01224 
01225     mbedtls_sha512_clone( &sha512, &ssl->handshake->fin_sha512 );
01226     mbedtls_sha512_finish_ret( &sha512, hash );
01227 
01228     MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 48 );
01229     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
01230 
01231     mbedtls_sha512_free( &sha512 );
01232 
01233     return;
01234 }
01235 #endif /* MBEDTLS_SHA512_C */
01236 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
01237 
01238 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
01239 int mbedtls_ssl_psk_derive_premaster( mbedtls_ssl_context *ssl, mbedtls_key_exchange_type_t key_ex )
01240 {
01241     unsigned char *p = ssl->handshake->premaster;
01242     unsigned char *end = p + sizeof( ssl->handshake->premaster );
01243     const unsigned char *psk = ssl->conf->psk;
01244     size_t psk_len = ssl->conf->psk_len;
01245 
01246     /* If the psk callback was called, use its result */
01247     if( ssl->handshake->psk != NULL )
01248     {
01249         psk = ssl->handshake->psk;
01250         psk_len = ssl->handshake->psk_len;
01251     }
01252 
01253     /*
01254      * PMS = struct {
01255      *     opaque other_secret<0..2^16-1>;
01256      *     opaque psk<0..2^16-1>;
01257      * };
01258      * with "other_secret" depending on the particular key exchange
01259      */
01260 #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
01261     if( key_ex == MBEDTLS_KEY_EXCHANGE_PSK )
01262     {
01263         if( end - p < 2 )
01264             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
01265 
01266         *(p++) = (unsigned char)( psk_len >> 8 );
01267         *(p++) = (unsigned char)( psk_len      );
01268 
01269         if( end < p || (size_t)( end - p ) < psk_len )
01270             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
01271 
01272         memset( p, 0, psk_len );
01273         p += psk_len;
01274     }
01275     else
01276 #endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */
01277 #if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
01278     if( key_ex == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
01279     {
01280         /*
01281          * other_secret already set by the ClientKeyExchange message,
01282          * and is 48 bytes long
01283          */
01284         if( end - p < 2 )
01285             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
01286 
01287         *p++ = 0;
01288         *p++ = 48;
01289         p += 48;
01290     }
01291     else
01292 #endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
01293 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
01294     if( key_ex == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
01295     {
01296         int ret;
01297         size_t len;
01298 
01299         /* Write length only when we know the actual value */
01300         if( ( ret = mbedtls_dhm_calc_secret( &ssl->handshake->dhm_ctx,
01301                                       p + 2, end - ( p + 2 ), &len,
01302                                       ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
01303         {
01304             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_calc_secret", ret );
01305             return( ret );
01306         }
01307         *(p++) = (unsigned char)( len >> 8 );
01308         *(p++) = (unsigned char)( len );
01309         p += len;
01310 
01311         MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: K ", &ssl->handshake->dhm_ctx.K  );
01312     }
01313     else
01314 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
01315 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
01316     if( key_ex == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
01317     {
01318         int ret;
01319         size_t zlen;
01320 
01321         if( ( ret = mbedtls_ecdh_calc_secret( &ssl->handshake->ecdh_ctx, &zlen,
01322                                        p + 2, end - ( p + 2 ),
01323                                        ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
01324         {
01325             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_calc_secret", ret );
01326             return( ret );
01327         }
01328 
01329         *(p++) = (unsigned char)( zlen >> 8 );
01330         *(p++) = (unsigned char)( zlen      );
01331         p += zlen;
01332 
01333         MBEDTLS_SSL_DEBUG_MPI( 3, "ECDH: z", &ssl->handshake->ecdh_ctx.z );
01334     }
01335     else
01336 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
01337     {
01338         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
01339         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
01340     }
01341 
01342     /* opaque psk<0..2^16-1>; */
01343     if( end - p < 2 )
01344         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
01345 
01346     *(p++) = (unsigned char)( psk_len >> 8 );
01347     *(p++) = (unsigned char)( psk_len      );
01348 
01349     if( end < p || (size_t)( end - p ) < psk_len )
01350         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
01351 
01352     memcpy( p, psk, psk_len );
01353     p += psk_len;
01354 
01355     ssl->handshake->pmslen = p - ssl->handshake->premaster;
01356 
01357     return( 0 );
01358 }
01359 #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
01360 
01361 #if defined(MBEDTLS_SSL_PROTO_SSL3)
01362 /*
01363  * SSLv3.0 MAC functions
01364  */
01365 #define SSL_MAC_MAX_BYTES   20  /* MD-5 or SHA-1 */
01366 static void ssl_mac( mbedtls_md_context_t *md_ctx,
01367                      const unsigned char *secret,
01368                      const unsigned char *buf, size_t len,
01369                      const unsigned char *ctr, int type,
01370                      unsigned char out[SSL_MAC_MAX_BYTES] )
01371 {
01372     unsigned char header[11];
01373     unsigned char padding[48];
01374     int padlen;
01375     int md_size = mbedtls_md_get_size( md_ctx->md_info );
01376     int md_type = mbedtls_md_get_type( md_ctx->md_info );
01377 
01378     /* Only MD5 and SHA-1 supported */
01379     if( md_type == MBEDTLS_MD_MD5 )
01380         padlen = 48;
01381     else
01382         padlen = 40;
01383 
01384     memcpy( header, ctr, 8 );
01385     header[ 8] = (unsigned char)  type;
01386     header[ 9] = (unsigned char)( len >> 8 );
01387     header[10] = (unsigned char)( len      );
01388 
01389     memset( padding, 0x36, padlen );
01390     mbedtls_md_starts( md_ctx );
01391     mbedtls_md_update( md_ctx, secret,  md_size );
01392     mbedtls_md_update( md_ctx, padding, padlen  );
01393     mbedtls_md_update( md_ctx, header,  11      );
01394     mbedtls_md_update( md_ctx, buf,     len     );
01395     mbedtls_md_finish( md_ctx, out              );
01396 
01397     memset( padding, 0x5C, padlen );
01398     mbedtls_md_starts( md_ctx );
01399     mbedtls_md_update( md_ctx, secret,    md_size );
01400     mbedtls_md_update( md_ctx, padding,   padlen  );
01401     mbedtls_md_update( md_ctx, out,       md_size );
01402     mbedtls_md_finish( md_ctx, out                );
01403 }
01404 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
01405 
01406 #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER) ||     \
01407     ( defined(MBEDTLS_CIPHER_MODE_CBC) &&                                  \
01408       ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_CAMELLIA_C) || defined(MBEDTLS_ARIA_C)) )
01409 #define SSL_SOME_MODES_USE_MAC
01410 #endif
01411 
01412 /* The function below is only used in the Lucky 13 counter-measure in
01413  * ssl_decrypt_buf(). These are the defines that guard the call site. */
01414 #if defined(SSL_SOME_MODES_USE_MAC) && \
01415     ( defined(MBEDTLS_SSL_PROTO_TLS1) || \
01416       defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
01417       defined(MBEDTLS_SSL_PROTO_TLS1_2) )
01418 /* This function makes sure every byte in the memory region is accessed
01419  * (in ascending addresses order) */
01420 static void ssl_read_memory( unsigned char *p, size_t len )
01421 {
01422     unsigned char acc = 0;
01423     volatile unsigned char force;
01424 
01425     for( ; len != 0; p++, len-- )
01426         acc ^= *p;
01427 
01428     force = acc;
01429     (void) force;
01430 }
01431 #endif /* SSL_SOME_MODES_USE_MAC && ( TLS1 || TLS1_1 || TLS1_2 ) */
01432 
01433 /*
01434  * Encryption/decryption functions
01435  */
01436 static int ssl_encrypt_buf( mbedtls_ssl_context *ssl )
01437 {
01438     mbedtls_cipher_mode_t mode;
01439     int auth_done = 0;
01440 
01441     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> encrypt buf" ) );
01442 
01443     if( ssl->session_out == NULL || ssl->transform_out == NULL )
01444     {
01445         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
01446         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
01447     }
01448 
01449     mode = mbedtls_cipher_get_cipher_mode( &ssl->transform_out->cipher_ctx_enc );
01450 
01451     MBEDTLS_SSL_DEBUG_BUF( 4, "before encrypt: output payload",
01452                       ssl->out_msg, ssl->out_msglen );
01453 
01454     /*
01455      * Add MAC before if needed
01456      */
01457 #if defined(SSL_SOME_MODES_USE_MAC)
01458     if( mode == MBEDTLS_MODE_STREAM ||
01459         ( mode == MBEDTLS_MODE_CBC
01460 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
01461           && ssl->session_out->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED
01462 #endif
01463         ) )
01464     {
01465 #if defined(MBEDTLS_SSL_PROTO_SSL3)
01466         if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
01467         {
01468             unsigned char mac[SSL_MAC_MAX_BYTES];
01469 
01470             ssl_mac( &ssl->transform_out->md_ctx_enc,
01471                       ssl->transform_out->mac_enc,
01472                       ssl->out_msg, ssl->out_msglen,
01473                       ssl->out_ctr, ssl->out_msgtype,
01474                       mac );
01475 
01476             memcpy( ssl->out_msg + ssl->out_msglen, mac, ssl->transform_out->maclen );
01477         }
01478         else
01479 #endif
01480 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
01481         defined(MBEDTLS_SSL_PROTO_TLS1_2)
01482         if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 )
01483         {
01484             unsigned char mac[MBEDTLS_SSL_MAC_ADD];
01485 
01486             mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, ssl->out_ctr, 8 );
01487             mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, ssl->out_hdr, 3 );
01488             mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, ssl->out_len, 2 );
01489             mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc,
01490                              ssl->out_msg, ssl->out_msglen );
01491             mbedtls_md_hmac_finish( &ssl->transform_out->md_ctx_enc, mac );
01492             mbedtls_md_hmac_reset( &ssl->transform_out->md_ctx_enc );
01493 
01494             memcpy( ssl->out_msg + ssl->out_msglen, mac, ssl->transform_out->maclen );
01495         }
01496         else
01497 #endif
01498         {
01499             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
01500             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
01501         }
01502 
01503         MBEDTLS_SSL_DEBUG_BUF( 4, "computed mac",
01504                        ssl->out_msg + ssl->out_msglen,
01505                        ssl->transform_out->maclen );
01506 
01507         ssl->out_msglen += ssl->transform_out->maclen;
01508         auth_done++;
01509     }
01510 #endif /* AEAD not the only option */
01511 
01512     /*
01513      * Encrypt
01514      */
01515 #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER)
01516     if( mode == MBEDTLS_MODE_STREAM )
01517     {
01518         int ret;
01519         size_t olen = 0;
01520 
01521         MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
01522                             "including %d bytes of padding",
01523                        ssl->out_msglen, 0 ) );
01524 
01525         if( ( ret = mbedtls_cipher_crypt( &ssl->transform_out->cipher_ctx_enc,
01526                                    ssl->transform_out->iv_enc,
01527                                    ssl->transform_out->ivlen,
01528                                    ssl->out_msg, ssl->out_msglen,
01529                                    ssl->out_msg, &olen ) ) != 0 )
01530         {
01531             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
01532             return( ret );
01533         }
01534 
01535         if( ssl->out_msglen != olen )
01536         {
01537             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
01538             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
01539         }
01540     }
01541     else
01542 #endif /* MBEDTLS_ARC4_C || MBEDTLS_CIPHER_NULL_CIPHER */
01543 #if defined(MBEDTLS_GCM_C) || \
01544     defined(MBEDTLS_CCM_C) || \
01545     defined(MBEDTLS_CHACHAPOLY_C)
01546     if( mode == MBEDTLS_MODE_GCM ||
01547         mode == MBEDTLS_MODE_CCM ||
01548         mode == MBEDTLS_MODE_CHACHAPOLY )
01549     {
01550         int ret;
01551         size_t enc_msglen, olen;
01552         unsigned char *enc_msg;
01553         unsigned char add_data[13];
01554         unsigned char iv[12];
01555         mbedtls_ssl_transform *transform = ssl->transform_out;
01556         unsigned char taglen = transform->ciphersuite_info->flags &
01557                                MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16;
01558         size_t explicit_ivlen = transform->ivlen - transform->fixed_ivlen;
01559 
01560         /*
01561          * Prepare additional authenticated data
01562          */
01563         memcpy( add_data, ssl->out_ctr, 8 );
01564         add_data[8]  = ssl->out_msgtype;
01565         mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,
01566                            ssl->conf->transport, add_data + 9 );
01567         add_data[11] = ( ssl->out_msglen >> 8 ) & 0xFF;
01568         add_data[12] = ssl->out_msglen & 0xFF;
01569 
01570         MBEDTLS_SSL_DEBUG_BUF( 4, "additional data for AEAD", add_data, 13 );
01571 
01572         /*
01573          * Generate IV
01574          */
01575         if( transform->ivlen == 12 && transform->fixed_ivlen == 4 )
01576         {
01577             /* GCM and CCM: fixed || explicit (=seqnum) */
01578             memcpy( iv, transform->iv_enc, transform->fixed_ivlen );
01579             memcpy( iv + transform->fixed_ivlen, ssl->out_ctr, 8 );
01580             memcpy( ssl->out_iv, ssl->out_ctr, 8 );
01581 
01582         }
01583         else if( transform->ivlen == 12 && transform->fixed_ivlen == 12 )
01584         {
01585             /* ChachaPoly: fixed XOR sequence number */
01586             unsigned char i;
01587 
01588             memcpy( iv, transform->iv_enc, transform->fixed_ivlen );
01589 
01590             for( i = 0; i < 8; i++ )
01591                 iv[i+4] ^= ssl->out_ctr[i];
01592         }
01593         else
01594         {
01595             /* Reminder if we ever add an AEAD mode with a different size */
01596             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
01597             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
01598         }
01599 
01600         MBEDTLS_SSL_DEBUG_BUF( 4, "IV used (internal)",
01601                                   iv, transform->ivlen );
01602         MBEDTLS_SSL_DEBUG_BUF( 4, "IV used (transmitted)",
01603                                   ssl->out_iv, explicit_ivlen );
01604 
01605         /*
01606          * Fix message length with added IV
01607          */
01608         enc_msg = ssl->out_msg;
01609         enc_msglen = ssl->out_msglen;
01610         ssl->out_msglen += explicit_ivlen;
01611 
01612         MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
01613                                     "including 0 bytes of padding",
01614                                     ssl->out_msglen ) );
01615 
01616         /*
01617          * Encrypt and authenticate
01618          */
01619         if( ( ret = mbedtls_cipher_auth_encrypt( &transform->cipher_ctx_enc,
01620                                          iv, transform->ivlen,
01621                                          add_data, 13,
01622                                          enc_msg, enc_msglen,
01623                                          enc_msg, &olen,
01624                                          enc_msg + enc_msglen, taglen ) ) != 0 )
01625         {
01626             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_auth_encrypt", ret );
01627             return( ret );
01628         }
01629 
01630         if( olen != enc_msglen )
01631         {
01632             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
01633             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
01634         }
01635 
01636         ssl->out_msglen += taglen;
01637         auth_done++;
01638 
01639         MBEDTLS_SSL_DEBUG_BUF( 4, "after encrypt: tag", enc_msg + enc_msglen, taglen );
01640     }
01641     else
01642 #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C */
01643 #if defined(MBEDTLS_CIPHER_MODE_CBC) &&                                    \
01644     ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_CAMELLIA_C) || defined(MBEDTLS_ARIA_C) )
01645     if( mode == MBEDTLS_MODE_CBC )
01646     {
01647         int ret;
01648         unsigned char *enc_msg;
01649         size_t enc_msglen, padlen, olen = 0, i;
01650 
01651         padlen = ssl->transform_out->ivlen - ( ssl->out_msglen + 1 ) %
01652                  ssl->transform_out->ivlen;
01653         if( padlen == ssl->transform_out->ivlen )
01654             padlen = 0;
01655 
01656         for( i = 0; i <= padlen; i++ )
01657             ssl->out_msg[ssl->out_msglen + i] = (unsigned char) padlen;
01658 
01659         ssl->out_msglen += padlen + 1;
01660 
01661         enc_msglen = ssl->out_msglen;
01662         enc_msg = ssl->out_msg;
01663 
01664 #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
01665         /*
01666          * Prepend per-record IV for block cipher in TLS v1.1 and up as per
01667          * Method 1 (6.2.3.2. in RFC4346 and RFC5246)
01668          */
01669         if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
01670         {
01671             /*
01672              * Generate IV
01673              */
01674             ret = ssl->conf->f_rng( ssl->conf->p_rng, ssl->transform_out->iv_enc,
01675                                   ssl->transform_out->ivlen );
01676             if( ret != 0 )
01677                 return( ret );
01678 
01679             memcpy( ssl->out_iv, ssl->transform_out->iv_enc,
01680                     ssl->transform_out->ivlen );
01681 
01682             /*
01683              * Fix pointer positions and message length with added IV
01684              */
01685             enc_msg = ssl->out_msg;
01686             enc_msglen = ssl->out_msglen;
01687             ssl->out_msglen += ssl->transform_out->ivlen;
01688         }
01689 #endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */
01690 
01691         MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
01692                             "including %d bytes of IV and %d bytes of padding",
01693                             ssl->out_msglen, ssl->transform_out->ivlen,
01694                             padlen + 1 ) );
01695 
01696         if( ( ret = mbedtls_cipher_crypt( &ssl->transform_out->cipher_ctx_enc,
01697                                    ssl->transform_out->iv_enc,
01698                                    ssl->transform_out->ivlen,
01699                                    enc_msg, enc_msglen,
01700                                    enc_msg, &olen ) ) != 0 )
01701         {
01702             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
01703             return( ret );
01704         }
01705 
01706         if( enc_msglen != olen )
01707         {
01708             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
01709             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
01710         }
01711 
01712 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1)
01713         if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 )
01714         {
01715             /*
01716              * Save IV in SSL3 and TLS1
01717              */
01718             memcpy( ssl->transform_out->iv_enc,
01719                     ssl->transform_out->cipher_ctx_enc.iv,
01720                     ssl->transform_out->ivlen );
01721         }
01722 #endif
01723 
01724 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
01725         if( auth_done == 0 )
01726         {
01727             unsigned char mac[MBEDTLS_SSL_MAC_ADD];
01728 
01729             /*
01730              * MAC(MAC_write_key, seq_num +
01731              *     TLSCipherText.type +
01732              *     TLSCipherText.version +
01733              *     length_of( (IV +) ENC(...) ) +
01734              *     IV + // except for TLS 1.0
01735              *     ENC(content + padding + padding_length));
01736              */
01737             unsigned char pseudo_hdr[13];
01738 
01739             MBEDTLS_SSL_DEBUG_MSG( 3, ( "using encrypt then mac" ) );
01740 
01741             memcpy( pseudo_hdr +  0, ssl->out_ctr, 8 );
01742             memcpy( pseudo_hdr +  8, ssl->out_hdr, 3 );
01743             pseudo_hdr[11] = (unsigned char)( ( ssl->out_msglen >> 8 ) & 0xFF );
01744             pseudo_hdr[12] = (unsigned char)( ( ssl->out_msglen      ) & 0xFF );
01745 
01746             MBEDTLS_SSL_DEBUG_BUF( 4, "MAC'd meta-data", pseudo_hdr, 13 );
01747 
01748             mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, pseudo_hdr, 13 );
01749             mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc,
01750                              ssl->out_iv, ssl->out_msglen );
01751             mbedtls_md_hmac_finish( &ssl->transform_out->md_ctx_enc, mac );
01752             mbedtls_md_hmac_reset( &ssl->transform_out->md_ctx_enc );
01753 
01754             memcpy( ssl->out_iv + ssl->out_msglen, mac,
01755                     ssl->transform_out->maclen );
01756 
01757             ssl->out_msglen += ssl->transform_out->maclen;
01758             auth_done++;
01759         }
01760 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
01761     }
01762     else
01763 #endif /* MBEDTLS_CIPHER_MODE_CBC &&
01764           ( MBEDTLS_AES_C || MBEDTLS_CAMELLIA_C || MBEDTLS_ARIA_C ) */
01765     {
01766         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
01767         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
01768     }
01769 
01770     /* Make extra sure authentication was performed, exactly once */
01771     if( auth_done != 1 )
01772     {
01773         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
01774         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
01775     }
01776 
01777     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= encrypt buf" ) );
01778 
01779     return( 0 );
01780 }
01781 
01782 static int ssl_decrypt_buf( mbedtls_ssl_context *ssl )
01783 {
01784     mbedtls_cipher_mode_t mode;
01785     int auth_done = 0;
01786 #if defined(SSL_SOME_MODES_USE_MAC)
01787     size_t padlen = 0, correct = 1;
01788 #endif
01789 
01790     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> decrypt buf" ) );
01791 
01792     if( ssl->session_in == NULL || ssl->transform_in == NULL )
01793     {
01794         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
01795         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
01796     }
01797 
01798     mode = mbedtls_cipher_get_cipher_mode( &ssl->transform_in->cipher_ctx_dec );
01799 
01800     if( ssl->in_msglen < ssl->transform_in->minlen )
01801     {
01802         MBEDTLS_SSL_DEBUG_MSG( 1, ( "in_msglen (%d) < minlen (%d)",
01803                        ssl->in_msglen, ssl->transform_in->minlen ) );
01804         return( MBEDTLS_ERR_SSL_INVALID_MAC );
01805     }
01806 
01807 #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER)
01808     if( mode == MBEDTLS_MODE_STREAM )
01809     {
01810         int ret;
01811         size_t olen = 0;
01812 
01813         padlen = 0;
01814 
01815         if( ( ret = mbedtls_cipher_crypt( &ssl->transform_in->cipher_ctx_dec,
01816                                    ssl->transform_in->iv_dec,
01817                                    ssl->transform_in->ivlen,
01818                                    ssl->in_msg, ssl->in_msglen,
01819                                    ssl->in_msg, &olen ) ) != 0 )
01820         {
01821             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
01822             return( ret );
01823         }
01824 
01825         if( ssl->in_msglen != olen )
01826         {
01827             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
01828             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
01829         }
01830     }
01831     else
01832 #endif /* MBEDTLS_ARC4_C || MBEDTLS_CIPHER_NULL_CIPHER */
01833 #if defined(MBEDTLS_GCM_C) || \
01834     defined(MBEDTLS_CCM_C) || \
01835     defined(MBEDTLS_CHACHAPOLY_C)
01836     if( mode == MBEDTLS_MODE_GCM ||
01837         mode == MBEDTLS_MODE_CCM ||
01838         mode == MBEDTLS_MODE_CHACHAPOLY )
01839     {
01840         int ret;
01841         size_t dec_msglen, olen;
01842         unsigned char *dec_msg;
01843         unsigned char *dec_msg_result;
01844         unsigned char add_data[13];
01845         unsigned char iv[12];
01846         mbedtls_ssl_transform *transform = ssl->transform_in;
01847         unsigned char taglen = transform->ciphersuite_info->flags &
01848                                MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16;
01849         size_t explicit_iv_len = transform->ivlen - transform->fixed_ivlen;
01850 
01851         /*
01852          * Compute and update sizes
01853          */
01854         if( ssl->in_msglen < explicit_iv_len + taglen )
01855         {
01856             MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < explicit_iv_len (%d) "
01857                                 "+ taglen (%d)", ssl->in_msglen,
01858                                 explicit_iv_len, taglen ) );
01859             return( MBEDTLS_ERR_SSL_INVALID_MAC );
01860         }
01861         dec_msglen = ssl->in_msglen - explicit_iv_len - taglen;
01862 
01863         dec_msg = ssl->in_msg;
01864         dec_msg_result = ssl->in_msg;
01865         ssl->in_msglen = dec_msglen;
01866 
01867         /*
01868          * Prepare additional authenticated data
01869          */
01870         memcpy( add_data, ssl->in_ctr, 8 );
01871         add_data[8]  = ssl->in_msgtype;
01872         mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,
01873                            ssl->conf->transport, add_data + 9 );
01874         add_data[11] = ( ssl->in_msglen >> 8 ) & 0xFF;
01875         add_data[12] = ssl->in_msglen & 0xFF;
01876 
01877         MBEDTLS_SSL_DEBUG_BUF( 4, "additional data for AEAD", add_data, 13 );
01878 
01879         /*
01880          * Prepare IV
01881          */
01882         if( transform->ivlen == 12 && transform->fixed_ivlen == 4 )
01883         {
01884             /* GCM and CCM: fixed || explicit (transmitted) */
01885             memcpy( iv, transform->iv_dec, transform->fixed_ivlen );
01886             memcpy( iv + transform->fixed_ivlen, ssl->in_iv, 8 );
01887 
01888         }
01889         else if( transform->ivlen == 12 && transform->fixed_ivlen == 12 )
01890         {
01891             /* ChachaPoly: fixed XOR sequence number */
01892             unsigned char i;
01893 
01894             memcpy( iv, transform->iv_dec, transform->fixed_ivlen );
01895 
01896             for( i = 0; i < 8; i++ )
01897                 iv[i+4] ^= ssl->in_ctr[i];
01898         }
01899         else
01900         {
01901             /* Reminder if we ever add an AEAD mode with a different size */
01902             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
01903             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
01904         }
01905 
01906         MBEDTLS_SSL_DEBUG_BUF( 4, "IV used", iv, transform->ivlen );
01907         MBEDTLS_SSL_DEBUG_BUF( 4, "TAG used", dec_msg + dec_msglen, taglen );
01908 
01909         /*
01910          * Decrypt and authenticate
01911          */
01912         if( ( ret = mbedtls_cipher_auth_decrypt( &ssl->transform_in->cipher_ctx_dec,
01913                                          iv, transform->ivlen,
01914                                          add_data, 13,
01915                                          dec_msg, dec_msglen,
01916                                          dec_msg_result, &olen,
01917                                          dec_msg + dec_msglen, taglen ) ) != 0 )
01918         {
01919             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_auth_decrypt", ret );
01920 
01921             if( ret == MBEDTLS_ERR_CIPHER_AUTH_FAILED )
01922                 return( MBEDTLS_ERR_SSL_INVALID_MAC );
01923 
01924             return( ret );
01925         }
01926         auth_done++;
01927 
01928         if( olen != dec_msglen )
01929         {
01930             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
01931             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
01932         }
01933     }
01934     else
01935 #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C */
01936 #if defined(MBEDTLS_CIPHER_MODE_CBC) &&                                    \
01937     ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_CAMELLIA_C) || defined(MBEDTLS_ARIA_C) )
01938     if( mode == MBEDTLS_MODE_CBC )
01939     {
01940         /*
01941          * Decrypt and check the padding
01942          */
01943         int ret;
01944         unsigned char *dec_msg;
01945         unsigned char *dec_msg_result;
01946         size_t dec_msglen;
01947         size_t minlen = 0;
01948         size_t olen = 0;
01949 
01950         /*
01951          * Check immediate ciphertext sanity
01952          */
01953 #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
01954         if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
01955             minlen += ssl->transform_in->ivlen;
01956 #endif
01957 
01958         if( ssl->in_msglen < minlen + ssl->transform_in->ivlen ||
01959             ssl->in_msglen < minlen + ssl->transform_in->maclen + 1 )
01960         {
01961             MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < max( ivlen(%d), maclen (%d) "
01962                                 "+ 1 ) ( + expl IV )", ssl->in_msglen,
01963                                 ssl->transform_in->ivlen,
01964                                 ssl->transform_in->maclen ) );
01965             return( MBEDTLS_ERR_SSL_INVALID_MAC );
01966         }
01967 
01968         dec_msglen = ssl->in_msglen;
01969         dec_msg = ssl->in_msg;
01970         dec_msg_result = ssl->in_msg;
01971 
01972         /*
01973          * Authenticate before decrypt if enabled
01974          */
01975 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
01976         if( ssl->session_in->encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED )
01977         {
01978             unsigned char mac_expect[MBEDTLS_SSL_MAC_ADD];
01979             unsigned char pseudo_hdr[13];
01980 
01981             MBEDTLS_SSL_DEBUG_MSG( 3, ( "using encrypt then mac" ) );
01982 
01983             dec_msglen -= ssl->transform_in->maclen;
01984             ssl->in_msglen -= ssl->transform_in->maclen;
01985 
01986             memcpy( pseudo_hdr +  0, ssl->in_ctr, 8 );
01987             memcpy( pseudo_hdr +  8, ssl->in_hdr, 3 );
01988             pseudo_hdr[11] = (unsigned char)( ( ssl->in_msglen >> 8 ) & 0xFF );
01989             pseudo_hdr[12] = (unsigned char)( ( ssl->in_msglen      ) & 0xFF );
01990 
01991             MBEDTLS_SSL_DEBUG_BUF( 4, "MAC'd meta-data", pseudo_hdr, 13 );
01992 
01993             mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, pseudo_hdr, 13 );
01994             mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec,
01995                              ssl->in_iv, ssl->in_msglen );
01996             mbedtls_md_hmac_finish( &ssl->transform_in->md_ctx_dec, mac_expect );
01997             mbedtls_md_hmac_reset( &ssl->transform_in->md_ctx_dec );
01998 
01999             MBEDTLS_SSL_DEBUG_BUF( 4, "message  mac", ssl->in_iv + ssl->in_msglen,
02000                                               ssl->transform_in->maclen );
02001             MBEDTLS_SSL_DEBUG_BUF( 4, "expected mac", mac_expect,
02002                                               ssl->transform_in->maclen );
02003 
02004             if( mbedtls_ssl_safer_memcmp( ssl->in_iv + ssl->in_msglen, mac_expect,
02005                                           ssl->transform_in->maclen ) != 0 )
02006             {
02007                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "message mac does not match" ) );
02008 
02009                 return( MBEDTLS_ERR_SSL_INVALID_MAC );
02010             }
02011             auth_done++;
02012         }
02013 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
02014 
02015         /*
02016          * Check length sanity
02017          */
02018         if( ssl->in_msglen % ssl->transform_in->ivlen != 0 )
02019         {
02020             MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) %% ivlen (%d) != 0",
02021                            ssl->in_msglen, ssl->transform_in->ivlen ) );
02022             return( MBEDTLS_ERR_SSL_INVALID_MAC );
02023         }
02024 
02025 #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
02026         /*
02027          * Initialize for prepended IV for block cipher in TLS v1.1 and up
02028          */
02029         if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
02030         {
02031             unsigned char i;
02032             dec_msglen -= ssl->transform_in->ivlen;
02033             ssl->in_msglen -= ssl->transform_in->ivlen;
02034 
02035             for( i = 0; i < ssl->transform_in->ivlen; i++ )
02036                 ssl->transform_in->iv_dec[i] = ssl->in_iv[i];
02037         }
02038 #endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */
02039 
02040         if( ( ret = mbedtls_cipher_crypt( &ssl->transform_in->cipher_ctx_dec,
02041                                    ssl->transform_in->iv_dec,
02042                                    ssl->transform_in->ivlen,
02043                                    dec_msg, dec_msglen,
02044                                    dec_msg_result, &olen ) ) != 0 )
02045         {
02046             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
02047             return( ret );
02048         }
02049 
02050         if( dec_msglen != olen )
02051         {
02052             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
02053             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
02054         }
02055 
02056 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1)
02057         if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 )
02058         {
02059             /*
02060              * Save IV in SSL3 and TLS1
02061              */
02062             memcpy( ssl->transform_in->iv_dec,
02063                     ssl->transform_in->cipher_ctx_dec.iv,
02064                     ssl->transform_in->ivlen );
02065         }
02066 #endif
02067 
02068         padlen = 1 + ssl->in_msg[ssl->in_msglen - 1];
02069 
02070         if( ssl->in_msglen < ssl->transform_in->maclen + padlen &&
02071             auth_done == 0 )
02072         {
02073 #if defined(MBEDTLS_SSL_DEBUG_ALL)
02074             MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < maclen (%d) + padlen (%d)",
02075                         ssl->in_msglen, ssl->transform_in->maclen, padlen ) );
02076 #endif
02077             padlen = 0;
02078             correct = 0;
02079         }
02080 
02081 #if defined(MBEDTLS_SSL_PROTO_SSL3)
02082         if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
02083         {
02084             if( padlen > ssl->transform_in->ivlen )
02085             {
02086 #if defined(MBEDTLS_SSL_DEBUG_ALL)
02087                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad padding length: is %d, "
02088                                     "should be no more than %d",
02089                                padlen, ssl->transform_in->ivlen ) );
02090 #endif
02091                 correct = 0;
02092             }
02093         }
02094         else
02095 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
02096 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
02097     defined(MBEDTLS_SSL_PROTO_TLS1_2)
02098         if( ssl->minor_ver > MBEDTLS_SSL_MINOR_VERSION_0 )
02099         {
02100             /*
02101              * TLSv1+: always check the padding up to the first failure
02102              * and fake check up to 256 bytes of padding
02103              */
02104             size_t pad_count = 0, real_count = 1;
02105             size_t padding_idx = ssl->in_msglen - padlen;
02106             size_t i;
02107 
02108             /*
02109              * Padding is guaranteed to be incorrect if:
02110              *   1. padlen > ssl->in_msglen
02111              *
02112              *   2. padding_idx > MBEDTLS_SSL_IN_CONTENT_LEN +
02113              *                     ssl->transform_in->maclen
02114              *
02115              * In both cases we reset padding_idx to a safe value (0) to
02116              * prevent out-of-buffer reads.
02117              */
02118             correct &= ( padlen <= ssl->in_msglen );
02119             correct &= ( padding_idx <= MBEDTLS_SSL_IN_CONTENT_LEN +
02120                                        ssl->transform_in->maclen );
02121 
02122             padding_idx *= correct;
02123 
02124             for( i = 0; i < 256; i++ )
02125             {
02126                 real_count &= ( i < padlen );
02127                 pad_count += real_count *
02128                              ( ssl->in_msg[padding_idx + i] == padlen - 1 );
02129             }
02130 
02131             correct &= ( pad_count == padlen ); /* Only 1 on correct padding */
02132 
02133 #if defined(MBEDTLS_SSL_DEBUG_ALL)
02134             if( padlen > 0 && correct == 0 )
02135                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad padding byte detected" ) );
02136 #endif
02137             padlen &= correct * 0x1FF;
02138         }
02139         else
02140 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
02141           MBEDTLS_SSL_PROTO_TLS1_2 */
02142         {
02143             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
02144             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
02145         }
02146 
02147         ssl->in_msglen -= padlen;
02148     }
02149     else
02150 #endif /* MBEDTLS_CIPHER_MODE_CBC &&
02151           ( MBEDTLS_AES_C || MBEDTLS_CAMELLIA_C || MBEDTLS_ARIA_C ) */
02152     {
02153         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
02154         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
02155     }
02156 
02157 #if defined(MBEDTLS_SSL_DEBUG_ALL)
02158     MBEDTLS_SSL_DEBUG_BUF( 4, "raw buffer after decryption",
02159                    ssl->in_msg, ssl->in_msglen );
02160 #endif
02161 
02162     /*
02163      * Authenticate if not done yet.
02164      * Compute the MAC regardless of the padding result (RFC4346, CBCTIME).
02165      */
02166 #if defined(SSL_SOME_MODES_USE_MAC)
02167     if( auth_done == 0 )
02168     {
02169         unsigned char mac_expect[MBEDTLS_SSL_MAC_ADD];
02170 
02171         ssl->in_msglen -= ssl->transform_in->maclen;
02172 
02173         ssl->in_len[0] = (unsigned char)( ssl->in_msglen >> 8 );
02174         ssl->in_len[1] = (unsigned char)( ssl->in_msglen      );
02175 
02176 #if defined(MBEDTLS_SSL_PROTO_SSL3)
02177         if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
02178         {
02179             ssl_mac( &ssl->transform_in->md_ctx_dec,
02180                       ssl->transform_in->mac_dec,
02181                       ssl->in_msg, ssl->in_msglen,
02182                       ssl->in_ctr, ssl->in_msgtype,
02183                       mac_expect );
02184         }
02185         else
02186 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
02187 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
02188         defined(MBEDTLS_SSL_PROTO_TLS1_2)
02189         if( ssl->minor_ver > MBEDTLS_SSL_MINOR_VERSION_0 )
02190         {
02191             /*
02192              * Process MAC and always update for padlen afterwards to make
02193              * total time independent of padlen.
02194              *
02195              * Known timing attacks:
02196              *  - Lucky Thirteen (http://www.isg.rhul.ac.uk/tls/TLStiming.pdf)
02197              *
02198              * To compensate for different timings for the MAC calculation
02199              * depending on how much padding was removed (which is determined
02200              * by padlen), process extra_run more blocks through the hash
02201              * function.
02202              *
02203              * The formula in the paper is
02204              *   extra_run = ceil( (L1-55) / 64 ) - ceil( (L2-55) / 64 )
02205              * where L1 is the size of the header plus the decrypted message
02206              * plus CBC padding and L2 is the size of the header plus the
02207              * decrypted message. This is for an underlying hash function
02208              * with 64-byte blocks.
02209              * We use ( (Lx+8) / 64 ) to handle 'negative Lx' values
02210              * correctly. We round down instead of up, so -56 is the correct
02211              * value for our calculations instead of -55.
02212              *
02213              * Repeat the formula rather than defining a block_size variable.
02214              * This avoids requiring division by a variable at runtime
02215              * (which would be marginally less efficient and would require
02216              * linking an extra division function in some builds).
02217              */
02218             size_t j, extra_run = 0;
02219 
02220             /*
02221              * The next two sizes are the minimum and maximum values of
02222              * in_msglen over all padlen values.
02223              *
02224              * They're independent of padlen, since we previously did
02225              * in_msglen -= padlen.
02226              *
02227              * Note that max_len + maclen is never more than the buffer
02228              * length, as we previously did in_msglen -= maclen too.
02229              */
02230             const size_t max_len = ssl->in_msglen + padlen;
02231             const size_t min_len = ( max_len > 256 ) ? max_len - 256 : 0;
02232 
02233             switch( ssl->transform_in->ciphersuite_info->mac )
02234             {
02235 #if defined(MBEDTLS_MD5_C) || defined(MBEDTLS_SHA1_C) || \
02236     defined(MBEDTLS_SHA256_C)
02237                 case MBEDTLS_MD_MD5:
02238                 case MBEDTLS_MD_SHA1:
02239                 case MBEDTLS_MD_SHA256:
02240                     /* 8 bytes of message size, 64-byte compression blocks */
02241                     extra_run = ( 13 + ssl->in_msglen + padlen + 8 ) / 64 -
02242                                 ( 13 + ssl->in_msglen          + 8 ) / 64;
02243                     break;
02244 #endif
02245 #if defined(MBEDTLS_SHA512_C)
02246                 case MBEDTLS_MD_SHA384:
02247                     /* 16 bytes of message size, 128-byte compression blocks */
02248                     extra_run = ( 13 + ssl->in_msglen + padlen + 16 ) / 128 -
02249                                 ( 13 + ssl->in_msglen          + 16 ) / 128;
02250                     break;
02251 #endif
02252                 default:
02253                     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
02254                     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
02255             }
02256 
02257             extra_run &= correct * 0xFF;
02258 
02259             mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_ctr, 8 );
02260             mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_hdr, 3 );
02261             mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_len, 2 );
02262             mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_msg,
02263                              ssl->in_msglen );
02264             /* Make sure we access everything even when padlen > 0. This
02265              * makes the synchronisation requirements for just-in-time
02266              * Prime+Probe attacks much tighter and hopefully impractical. */
02267             ssl_read_memory( ssl->in_msg + ssl->in_msglen, padlen );
02268             mbedtls_md_hmac_finish( &ssl->transform_in->md_ctx_dec, mac_expect );
02269 
02270             /* Call mbedtls_md_process at least once due to cache attacks
02271              * that observe whether md_process() was called of not */
02272             for( j = 0; j < extra_run + 1; j++ )
02273                 mbedtls_md_process( &ssl->transform_in->md_ctx_dec, ssl->in_msg );
02274 
02275             mbedtls_md_hmac_reset( &ssl->transform_in->md_ctx_dec );
02276 
02277             /* Make sure we access all the memory that could contain the MAC,
02278              * before we check it in the next code block. This makes the
02279              * synchronisation requirements for just-in-time Prime+Probe
02280              * attacks much tighter and hopefully impractical. */
02281             ssl_read_memory( ssl->in_msg + min_len,
02282                                  max_len - min_len + ssl->transform_in->maclen );
02283         }
02284         else
02285 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
02286               MBEDTLS_SSL_PROTO_TLS1_2 */
02287         {
02288             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
02289             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
02290         }
02291 
02292 #if defined(MBEDTLS_SSL_DEBUG_ALL)
02293         MBEDTLS_SSL_DEBUG_BUF( 4, "expected mac", mac_expect, ssl->transform_in->maclen );
02294         MBEDTLS_SSL_DEBUG_BUF( 4, "message  mac", ssl->in_msg + ssl->in_msglen,
02295                                ssl->transform_in->maclen );
02296 #endif
02297 
02298         if( mbedtls_ssl_safer_memcmp( ssl->in_msg + ssl->in_msglen, mac_expect,
02299                                       ssl->transform_in->maclen ) != 0 )
02300         {
02301 #if defined(MBEDTLS_SSL_DEBUG_ALL)
02302             MBEDTLS_SSL_DEBUG_MSG( 1, ( "message mac does not match" ) );
02303 #endif
02304             correct = 0;
02305         }
02306         auth_done++;
02307 
02308         /*
02309          * Finally check the correct flag
02310          */
02311         if( correct == 0 )
02312             return( MBEDTLS_ERR_SSL_INVALID_MAC );
02313     }
02314 #endif /* SSL_SOME_MODES_USE_MAC */
02315 
02316     /* Make extra sure authentication was performed, exactly once */
02317     if( auth_done != 1 )
02318     {
02319         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
02320         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
02321     }
02322 
02323     if( ssl->in_msglen == 0 )
02324     {
02325 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
02326         if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3
02327             && ssl->in_msgtype != MBEDTLS_SSL_MSG_APPLICATION_DATA )
02328         {
02329             /* TLS v1.2 explicitly disallows zero-length messages which are not application data */
02330             MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid zero-length message type: %d", ssl->in_msgtype ) );
02331             return( MBEDTLS_ERR_SSL_INVALID_RECORD );
02332         }
02333 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
02334 
02335         ssl->nb_zero++;
02336 
02337         /*
02338          * Three or more empty messages may be a DoS attack
02339          * (excessive CPU consumption).
02340          */
02341         if( ssl->nb_zero > 3 )
02342         {
02343             MBEDTLS_SSL_DEBUG_MSG( 1, ( "received four consecutive empty "
02344                                 "messages, possible DoS attack" ) );
02345             return( MBEDTLS_ERR_SSL_INVALID_MAC );
02346         }
02347     }
02348     else
02349         ssl->nb_zero = 0;
02350 
02351 #if defined(MBEDTLS_SSL_PROTO_DTLS)
02352     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
02353     {
02354         ; /* in_ctr read from peer, not maintained internally */
02355     }
02356     else
02357 #endif
02358     {
02359         unsigned char i;
02360         for( i = 8; i > ssl_ep_len( ssl ); i-- )
02361             if( ++ssl->in_ctr[i - 1] != 0 )
02362                 break;
02363 
02364         /* The loop goes to its end iff the counter is wrapping */
02365         if( i == ssl_ep_len( ssl ) )
02366         {
02367             MBEDTLS_SSL_DEBUG_MSG( 1, ( "incoming message counter would wrap" ) );
02368             return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
02369         }
02370     }
02371 
02372     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= decrypt buf" ) );
02373 
02374     return( 0 );
02375 }
02376 
02377 #undef MAC_NONE
02378 #undef MAC_PLAINTEXT
02379 #undef MAC_CIPHERTEXT
02380 
02381 #if defined(MBEDTLS_ZLIB_SUPPORT)
02382 /*
02383  * Compression/decompression functions
02384  */
02385 static int ssl_compress_buf( mbedtls_ssl_context *ssl )
02386 {
02387     int ret;
02388     unsigned char *msg_post = ssl->out_msg;
02389     ptrdiff_t bytes_written = ssl->out_msg - ssl->out_buf;
02390     size_t len_pre = ssl->out_msglen;
02391     unsigned char *msg_pre = ssl->compress_buf;
02392 
02393     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> compress buf" ) );
02394 
02395     if( len_pre == 0 )
02396         return( 0 );
02397 
02398     memcpy( msg_pre, ssl->out_msg, len_pre );
02399 
02400     MBEDTLS_SSL_DEBUG_MSG( 3, ( "before compression: msglen = %d, ",
02401                    ssl->out_msglen ) );
02402 
02403     MBEDTLS_SSL_DEBUG_BUF( 4, "before compression: output payload",
02404                    ssl->out_msg, ssl->out_msglen );
02405 
02406     ssl->transform_out->ctx_deflate.next_in = msg_pre;
02407     ssl->transform_out->ctx_deflate.avail_in = len_pre;
02408     ssl->transform_out->ctx_deflate.next_out = msg_post;
02409     ssl->transform_out->ctx_deflate.avail_out = MBEDTLS_SSL_OUT_BUFFER_LEN - bytes_written;
02410 
02411     ret = deflate( &ssl->transform_out->ctx_deflate, Z_SYNC_FLUSH );
02412     if( ret != Z_OK )
02413     {
02414         MBEDTLS_SSL_DEBUG_MSG( 1, ( "failed to perform compression (%d)", ret ) );
02415         return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED );
02416     }
02417 
02418     ssl->out_msglen = MBEDTLS_SSL_OUT_BUFFER_LEN -
02419                       ssl->transform_out->ctx_deflate.avail_out - bytes_written;
02420 
02421     MBEDTLS_SSL_DEBUG_MSG( 3, ( "after compression: msglen = %d, ",
02422                    ssl->out_msglen ) );
02423 
02424     MBEDTLS_SSL_DEBUG_BUF( 4, "after compression: output payload",
02425                    ssl->out_msg, ssl->out_msglen );
02426 
02427     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= compress buf" ) );
02428 
02429     return( 0 );
02430 }
02431 
02432 static int ssl_decompress_buf( mbedtls_ssl_context *ssl )
02433 {
02434     int ret;
02435     unsigned char *msg_post = ssl->in_msg;
02436     ptrdiff_t header_bytes = ssl->in_msg - ssl->in_buf;
02437     size_t len_pre = ssl->in_msglen;
02438     unsigned char *msg_pre = ssl->compress_buf;
02439 
02440     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> decompress buf" ) );
02441 
02442     if( len_pre == 0 )
02443         return( 0 );
02444 
02445     memcpy( msg_pre, ssl->in_msg, len_pre );
02446 
02447     MBEDTLS_SSL_DEBUG_MSG( 3, ( "before decompression: msglen = %d, ",
02448                    ssl->in_msglen ) );
02449 
02450     MBEDTLS_SSL_DEBUG_BUF( 4, "before decompression: input payload",
02451                    ssl->in_msg, ssl->in_msglen );
02452 
02453     ssl->transform_in->ctx_inflate.next_in = msg_pre;
02454     ssl->transform_in->ctx_inflate.avail_in = len_pre;
02455     ssl->transform_in->ctx_inflate.next_out = msg_post;
02456     ssl->transform_in->ctx_inflate.avail_out = MBEDTLS_SSL_IN_BUFFER_LEN -
02457                                                header_bytes;
02458 
02459     ret = inflate( &ssl->transform_in->ctx_inflate, Z_SYNC_FLUSH );
02460     if( ret != Z_OK )
02461     {
02462         MBEDTLS_SSL_DEBUG_MSG( 1, ( "failed to perform decompression (%d)", ret ) );
02463         return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED );
02464     }
02465 
02466     ssl->in_msglen = MBEDTLS_SSL_IN_BUFFER_LEN -
02467                      ssl->transform_in->ctx_inflate.avail_out - header_bytes;
02468 
02469     MBEDTLS_SSL_DEBUG_MSG( 3, ( "after decompression: msglen = %d, ",
02470                    ssl->in_msglen ) );
02471 
02472     MBEDTLS_SSL_DEBUG_BUF( 4, "after decompression: input payload",
02473                    ssl->in_msg, ssl->in_msglen );
02474 
02475     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= decompress buf" ) );
02476 
02477     return( 0 );
02478 }
02479 #endif /* MBEDTLS_ZLIB_SUPPORT */
02480 
02481 #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
02482 static int ssl_write_hello_request( mbedtls_ssl_context *ssl );
02483 
02484 #if defined(MBEDTLS_SSL_PROTO_DTLS)
02485 static int ssl_resend_hello_request( mbedtls_ssl_context *ssl )
02486 {
02487     /* If renegotiation is not enforced, retransmit until we would reach max
02488      * timeout if we were using the usual handshake doubling scheme */
02489     if( ssl->conf->renego_max_records < 0 )
02490     {
02491         uint32_t ratio = ssl->conf->hs_timeout_max / ssl->conf->hs_timeout_min + 1;
02492         unsigned char doublings = 1;
02493 
02494         while( ratio != 0 )
02495         {
02496             ++doublings;
02497             ratio >>= 1;
02498         }
02499 
02500         if( ++ssl->renego_records_seen > doublings )
02501         {
02502             MBEDTLS_SSL_DEBUG_MSG( 2, ( "no longer retransmitting hello request" ) );
02503             return( 0 );
02504         }
02505     }
02506 
02507     return( ssl_write_hello_request( ssl ) );
02508 }
02509 #endif
02510 #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
02511 
02512 /*
02513  * Fill the input message buffer by appending data to it.
02514  * The amount of data already fetched is in ssl->in_left.
02515  *
02516  * If we return 0, is it guaranteed that (at least) nb_want bytes are
02517  * available (from this read and/or a previous one). Otherwise, an error code
02518  * is returned (possibly EOF or WANT_READ).
02519  *
02520  * With stream transport (TLS) on success ssl->in_left == nb_want, but
02521  * with datagram transport (DTLS) on success ssl->in_left >= nb_want,
02522  * since we always read a whole datagram at once.
02523  *
02524  * For DTLS, it is up to the caller to set ssl->next_record_offset when
02525  * they're done reading a record.
02526  */
02527 int mbedtls_ssl_fetch_input( mbedtls_ssl_context *ssl, size_t nb_want )
02528 {
02529     int ret;
02530     size_t len;
02531 
02532     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> fetch input" ) );
02533 
02534     if( ssl->f_recv == NULL && ssl->f_recv_timeout == NULL )
02535     {
02536         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Bad usage of mbedtls_ssl_set_bio() "
02537                             "or mbedtls_ssl_set_bio()" ) );
02538         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
02539     }
02540 
02541     if( nb_want > MBEDTLS_SSL_IN_BUFFER_LEN - (size_t)( ssl->in_hdr - ssl->in_buf ) )
02542     {
02543         MBEDTLS_SSL_DEBUG_MSG( 1, ( "requesting more data than fits" ) );
02544         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
02545     }
02546 
02547 #if defined(MBEDTLS_SSL_PROTO_DTLS)
02548     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
02549     {
02550         uint32_t timeout;
02551 
02552         /* Just to be sure */
02553         if( ssl->f_set_timer == NULL || ssl->f_get_timer == NULL )
02554         {
02555             MBEDTLS_SSL_DEBUG_MSG( 1, ( "You must use "
02556                         "mbedtls_ssl_set_timer_cb() for DTLS" ) );
02557             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
02558         }
02559 
02560         /*
02561          * The point is, we need to always read a full datagram at once, so we
02562          * sometimes read more then requested, and handle the additional data.
02563          * It could be the rest of the current record (while fetching the
02564          * header) and/or some other records in the same datagram.
02565          */
02566 
02567         /*
02568          * Move to the next record in the already read datagram if applicable
02569          */
02570         if( ssl->next_record_offset != 0 )
02571         {
02572             if( ssl->in_left < ssl->next_record_offset )
02573             {
02574                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
02575                 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
02576             }
02577 
02578             ssl->in_left -= ssl->next_record_offset;
02579 
02580             if( ssl->in_left != 0 )
02581             {
02582                 MBEDTLS_SSL_DEBUG_MSG( 2, ( "next record in same datagram, offset: %d",
02583                                     ssl->next_record_offset ) );
02584                 memmove( ssl->in_hdr,
02585                          ssl->in_hdr + ssl->next_record_offset,
02586                          ssl->in_left );
02587             }
02588 
02589             ssl->next_record_offset = 0;
02590         }
02591 
02592         MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d",
02593                        ssl->in_left, nb_want ) );
02594 
02595         /*
02596          * Done if we already have enough data.
02597          */
02598         if( nb_want <= ssl->in_left)
02599         {
02600             MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= fetch input" ) );
02601             return( 0 );
02602         }
02603 
02604         /*
02605          * A record can't be split accross datagrams. If we need to read but
02606          * are not at the beginning of a new record, the caller did something
02607          * wrong.
02608          */
02609         if( ssl->in_left != 0 )
02610         {
02611             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
02612             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
02613         }
02614 
02615         /*
02616          * Don't even try to read if time's out already.
02617          * This avoids by-passing the timer when repeatedly receiving messages
02618          * that will end up being dropped.
02619          */
02620         if( ssl_check_timer( ssl ) != 0 )
02621         {
02622             MBEDTLS_SSL_DEBUG_MSG( 2, ( "timer has expired" ) );
02623             ret = MBEDTLS_ERR_SSL_TIMEOUT;
02624         }
02625         else
02626         {
02627             len = MBEDTLS_SSL_IN_BUFFER_LEN - ( ssl->in_hdr - ssl->in_buf );
02628 
02629             if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
02630                 timeout = ssl->handshake->retransmit_timeout;
02631             else
02632                 timeout = ssl->conf->read_timeout;
02633 
02634             MBEDTLS_SSL_DEBUG_MSG( 3, ( "f_recv_timeout: %u ms", timeout ) );
02635 
02636             if( ssl->f_recv_timeout != NULL )
02637                 ret = ssl->f_recv_timeout( ssl->p_bio, ssl->in_hdr, len,
02638                                                                     timeout );
02639             else
02640                 ret = ssl->f_recv( ssl->p_bio, ssl->in_hdr, len );
02641 
02642             MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_recv(_timeout)", ret );
02643 
02644             if( ret == 0 )
02645                 return( MBEDTLS_ERR_SSL_CONN_EOF );
02646         }
02647 
02648         if( ret == MBEDTLS_ERR_SSL_TIMEOUT )
02649         {
02650             MBEDTLS_SSL_DEBUG_MSG( 2, ( "timeout" ) );
02651             ssl_set_timer( ssl, 0 );
02652 
02653             if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
02654             {
02655                 if( ssl_double_retransmit_timeout( ssl ) != 0 )
02656                 {
02657                     MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake timeout" ) );
02658                     return( MBEDTLS_ERR_SSL_TIMEOUT );
02659                 }
02660 
02661                 if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )
02662                 {
02663                     MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend", ret );
02664                     return( ret );
02665                 }
02666 
02667                 return( MBEDTLS_ERR_SSL_WANT_READ );
02668             }
02669 #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
02670             else if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
02671                      ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
02672             {
02673                 if( ( ret = ssl_resend_hello_request( ssl ) ) != 0 )
02674                 {
02675                     MBEDTLS_SSL_DEBUG_RET( 1, "ssl_resend_hello_request", ret );
02676                     return( ret );
02677                 }
02678 
02679                 return( MBEDTLS_ERR_SSL_WANT_READ );
02680             }
02681 #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
02682         }
02683 
02684         if( ret < 0 )
02685             return( ret );
02686 
02687         ssl->in_left = ret;
02688     }
02689     else
02690 #endif
02691     {
02692         MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d",
02693                        ssl->in_left, nb_want ) );
02694 
02695         while( ssl->in_left < nb_want )
02696         {
02697             len = nb_want - ssl->in_left;
02698 
02699             if( ssl_check_timer( ssl ) != 0 )
02700                 ret = MBEDTLS_ERR_SSL_TIMEOUT;
02701             else
02702             {
02703                 if( ssl->f_recv_timeout != NULL )
02704                 {
02705                     ret = ssl->f_recv_timeout( ssl->p_bio,
02706                                                ssl->in_hdr + ssl->in_left, len,
02707                                                ssl->conf->read_timeout );
02708                 }
02709                 else
02710                 {
02711                     ret = ssl->f_recv( ssl->p_bio,
02712                                        ssl->in_hdr + ssl->in_left, len );
02713                 }
02714             }
02715 
02716             MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d",
02717                                         ssl->in_left, nb_want ) );
02718             MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_recv(_timeout)", ret );
02719 
02720             if( ret == 0 )
02721                 return( MBEDTLS_ERR_SSL_CONN_EOF );
02722 
02723             if( ret < 0 )
02724                 return( ret );
02725 
02726             if ( (size_t)ret > len || ( INT_MAX > SIZE_MAX && ret > SIZE_MAX ) )
02727             {
02728                 MBEDTLS_SSL_DEBUG_MSG( 1,
02729                     ( "f_recv returned %d bytes but only %lu were requested",
02730                     ret, (unsigned long)len ) );
02731                 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
02732             }
02733 
02734             ssl->in_left += ret;
02735         }
02736     }
02737 
02738     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= fetch input" ) );
02739 
02740     return( 0 );
02741 }
02742 
02743 /*
02744  * Flush any data not yet written
02745  */
02746 int mbedtls_ssl_flush_output( mbedtls_ssl_context *ssl )
02747 {
02748     int ret;
02749     unsigned char *buf;
02750 
02751     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> flush output" ) );
02752 
02753     if( ssl->f_send == NULL )
02754     {
02755         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Bad usage of mbedtls_ssl_set_bio() "
02756                             "or mbedtls_ssl_set_bio()" ) );
02757         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
02758     }
02759 
02760     /* Avoid incrementing counter if data is flushed */
02761     if( ssl->out_left == 0 )
02762     {
02763         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= flush output" ) );
02764         return( 0 );
02765     }
02766 
02767     while( ssl->out_left > 0 )
02768     {
02769         MBEDTLS_SSL_DEBUG_MSG( 2, ( "message length: %d, out_left: %d",
02770                        mbedtls_ssl_hdr_len( ssl ) + ssl->out_msglen, ssl->out_left ) );
02771 
02772         buf = ssl->out_hdr - ssl->out_left;
02773         ret = ssl->f_send( ssl->p_bio, buf, ssl->out_left );
02774 
02775         MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_send", ret );
02776 
02777         if( ret <= 0 )
02778             return( ret );
02779 
02780         if( (size_t)ret > ssl->out_left || ( INT_MAX > SIZE_MAX && ret > SIZE_MAX ) )
02781         {
02782             MBEDTLS_SSL_DEBUG_MSG( 1,
02783                 ( "f_send returned %d bytes but only %lu bytes were sent",
02784                 ret, (unsigned long)ssl->out_left ) );
02785             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
02786         }
02787 
02788         ssl->out_left -= ret;
02789     }
02790 
02791 #if defined(MBEDTLS_SSL_PROTO_DTLS)
02792     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
02793     {
02794         ssl->out_hdr = ssl->out_buf;
02795     }
02796     else
02797 #endif
02798     {
02799         ssl->out_hdr = ssl->out_buf + 8;
02800     }
02801     ssl_update_out_pointers( ssl, ssl->transform_out );
02802 
02803     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= flush output" ) );
02804 
02805     return( 0 );
02806 }
02807 
02808 /*
02809  * Functions to handle the DTLS retransmission state machine
02810  */
02811 #if defined(MBEDTLS_SSL_PROTO_DTLS)
02812 /*
02813  * Append current handshake message to current outgoing flight
02814  */
02815 static int ssl_flight_append( mbedtls_ssl_context *ssl )
02816 {
02817     mbedtls_ssl_flight_item *msg;
02818     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> ssl_flight_append" ) );
02819     MBEDTLS_SSL_DEBUG_BUF( 4, "message appended to flight",
02820                            ssl->out_msg, ssl->out_msglen );
02821 
02822     /* Allocate space for current message */
02823     if( ( msg = mbedtls_calloc( 1, sizeof(  mbedtls_ssl_flight_item ) ) ) == NULL )
02824     {
02825         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc %d bytes failed",
02826                             sizeof( mbedtls_ssl_flight_item ) ) );
02827         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
02828     }
02829 
02830     if( ( msg->p = mbedtls_calloc( 1, ssl->out_msglen ) ) == NULL )
02831     {
02832         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc %d bytes failed", ssl->out_msglen ) );
02833         mbedtls_free( msg );
02834         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
02835     }
02836 
02837     /* Copy current handshake message with headers */
02838     memcpy( msg->p, ssl->out_msg, ssl->out_msglen );
02839     msg->len = ssl->out_msglen;
02840     msg->type = ssl->out_msgtype;
02841     msg->next = NULL;
02842 
02843     /* Append to the current flight */
02844     if( ssl->handshake->flight == NULL )
02845         ssl->handshake->flight = msg;
02846     else
02847     {
02848         mbedtls_ssl_flight_item *cur = ssl->handshake->flight;
02849         while( cur->next != NULL )
02850             cur = cur->next;
02851         cur->next = msg;
02852     }
02853 
02854     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= ssl_flight_append" ) );
02855     return( 0 );
02856 }
02857 
02858 /*
02859  * Free the current flight of handshake messages
02860  */
02861 static void ssl_flight_free( mbedtls_ssl_flight_item *flight )
02862 {
02863     mbedtls_ssl_flight_item *cur = flight;
02864     mbedtls_ssl_flight_item *next;
02865 
02866     while( cur != NULL )
02867     {
02868         next = cur->next;
02869 
02870         mbedtls_free( cur->p );
02871         mbedtls_free( cur );
02872 
02873         cur = next;
02874     }
02875 }
02876 
02877 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
02878 static void ssl_dtls_replay_reset( mbedtls_ssl_context *ssl );
02879 #endif
02880 
02881 /*
02882  * Swap transform_out and out_ctr with the alternative ones
02883  */
02884 static void ssl_swap_epochs( mbedtls_ssl_context *ssl )
02885 {
02886     mbedtls_ssl_transform *tmp_transform;
02887     unsigned char tmp_out_ctr[8];
02888 
02889     if( ssl->transform_out == ssl->handshake->alt_transform_out )
02890     {
02891         MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip swap epochs" ) );
02892         return;
02893     }
02894 
02895     MBEDTLS_SSL_DEBUG_MSG( 3, ( "swap epochs" ) );
02896 
02897     /* Swap transforms */
02898     tmp_transform                     = ssl->transform_out;
02899     ssl->transform_out                = ssl->handshake->alt_transform_out;
02900     ssl->handshake->alt_transform_out = tmp_transform;
02901 
02902     /* Swap epoch + sequence_number */
02903     memcpy( tmp_out_ctr,                 ssl->cur_out_ctr,            8 );
02904     memcpy( ssl->cur_out_ctr,            ssl->handshake->alt_out_ctr, 8 );
02905     memcpy( ssl->handshake->alt_out_ctr, tmp_out_ctr,                 8 );
02906 
02907     /* Adjust to the newly activated transform */
02908     ssl_update_out_pointers( ssl, ssl->transform_out );
02909 
02910 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
02911     if( mbedtls_ssl_hw_record_activate != NULL )
02912     {
02913         if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_OUTBOUND ) ) != 0 )
02914         {
02915             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret );
02916             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
02917         }
02918     }
02919 #endif
02920 }
02921 
02922 /*
02923  * Retransmit the current flight of messages.
02924  */
02925 int mbedtls_ssl_resend( mbedtls_ssl_context *ssl )
02926 {
02927     int ret = 0;
02928 
02929     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> mbedtls_ssl_resend" ) );
02930 
02931     ret = mbedtls_ssl_flight_transmit( ssl );
02932 
02933     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= mbedtls_ssl_resend" ) );
02934 
02935     return( ret );
02936 }
02937 
02938 /*
02939  * Transmit or retransmit the current flight of messages.
02940  *
02941  * Need to remember the current message in case flush_output returns
02942  * WANT_WRITE, causing us to exit this function and come back later.
02943  * This function must be called until state is no longer SENDING.
02944  */
02945 int mbedtls_ssl_flight_transmit( mbedtls_ssl_context *ssl )
02946 {
02947     int ret;
02948     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> mbedtls_ssl_flight_transmit" ) );
02949 
02950     if( ssl->handshake->retransmit_state != MBEDTLS_SSL_RETRANS_SENDING )
02951     {
02952         MBEDTLS_SSL_DEBUG_MSG( 2, ( "initialise flight transmission" ) );
02953 
02954         ssl->handshake->cur_msg = ssl->handshake->flight;
02955         ssl->handshake->cur_msg_p = ssl->handshake->flight->p + 12;
02956         ssl_swap_epochs( ssl );
02957 
02958         ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_SENDING;
02959     }
02960 
02961     while( ssl->handshake->cur_msg != NULL )
02962     {
02963         size_t max_frag_len;
02964         const mbedtls_ssl_flight_item * const cur = ssl->handshake->cur_msg;
02965 
02966         int const is_finished =
02967             ( cur->type == MBEDTLS_SSL_MSG_HANDSHAKE &&
02968               cur->p[0] == MBEDTLS_SSL_HS_FINISHED );
02969 
02970         uint8_t const force_flush = ssl->disable_datagram_packing == 1 ?
02971             SSL_FORCE_FLUSH : SSL_DONT_FORCE_FLUSH;
02972 
02973         /* Swap epochs before sending Finished: we can't do it after
02974          * sending ChangeCipherSpec, in case write returns WANT_READ.
02975          * Must be done before copying, may change out_msg pointer */
02976         if( is_finished && ssl->handshake->cur_msg_p == ( cur->p + 12 ) )
02977         {
02978             MBEDTLS_SSL_DEBUG_MSG( 2, ( "swap epochs to send finished message" ) );
02979             ssl_swap_epochs( ssl );
02980         }
02981 
02982         ret = ssl_get_remaining_payload_in_datagram( ssl );
02983         if( ret < 0 )
02984             return( ret );
02985         max_frag_len = (size_t) ret;
02986 
02987         /* CCS is copied as is, while HS messages may need fragmentation */
02988         if( cur->type == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC )
02989         {
02990             if( max_frag_len == 0 )
02991             {
02992                 if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
02993                     return( ret );
02994 
02995                 continue;
02996             }
02997 
02998             memcpy( ssl->out_msg, cur->p, cur->len );
02999             ssl->out_msglen  = cur->len;
03000             ssl->out_msgtype = cur->type;
03001 
03002             /* Update position inside current message */
03003             ssl->handshake->cur_msg_p += cur->len;
03004         }
03005         else
03006         {
03007             const unsigned char * const p = ssl->handshake->cur_msg_p;
03008             const size_t hs_len = cur->len - 12;
03009             const size_t frag_off = p - ( cur->p + 12 );
03010             const size_t rem_len = hs_len - frag_off;
03011             size_t cur_hs_frag_len, max_hs_frag_len;
03012 
03013             if( ( max_frag_len < 12 ) || ( max_frag_len == 12 && hs_len != 0 ) )
03014             {
03015                 if( is_finished )
03016                     ssl_swap_epochs( ssl );
03017 
03018                 if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
03019                     return( ret );
03020 
03021                 continue;
03022             }
03023             max_hs_frag_len = max_frag_len - 12;
03024 
03025             cur_hs_frag_len = rem_len > max_hs_frag_len ?
03026                 max_hs_frag_len : rem_len;
03027 
03028             if( frag_off == 0 && cur_hs_frag_len != hs_len )
03029             {
03030                 MBEDTLS_SSL_DEBUG_MSG( 2, ( "fragmenting handshake message (%u > %u)",
03031                                             (unsigned) cur_hs_frag_len,
03032                                             (unsigned) max_hs_frag_len ) );
03033             }
03034 
03035             /* Messages are stored with handshake headers as if not fragmented,
03036              * copy beginning of headers then fill fragmentation fields.
03037              * Handshake headers: type(1) len(3) seq(2) f_off(3) f_len(3) */
03038             memcpy( ssl->out_msg, cur->p, 6 );
03039 
03040             ssl->out_msg[6] = ( ( frag_off >> 16 ) & 0xff );
03041             ssl->out_msg[7] = ( ( frag_off >>  8 ) & 0xff );
03042             ssl->out_msg[8] = ( ( frag_off       ) & 0xff );
03043 
03044             ssl->out_msg[ 9] = ( ( cur_hs_frag_len >> 16 ) & 0xff );
03045             ssl->out_msg[10] = ( ( cur_hs_frag_len >>  8 ) & 0xff );
03046             ssl->out_msg[11] = ( ( cur_hs_frag_len       ) & 0xff );
03047 
03048             MBEDTLS_SSL_DEBUG_BUF( 3, "handshake header", ssl->out_msg, 12 );
03049 
03050             /* Copy the handshake message content and set records fields */
03051             memcpy( ssl->out_msg + 12, p, cur_hs_frag_len );
03052             ssl->out_msglen = cur_hs_frag_len + 12;
03053             ssl->out_msgtype = cur->type;
03054 
03055             /* Update position inside current message */
03056             ssl->handshake->cur_msg_p += cur_hs_frag_len;
03057         }
03058 
03059         /* If done with the current message move to the next one if any */
03060         if( ssl->handshake->cur_msg_p >= cur->p + cur->len )
03061         {
03062             if( cur->next != NULL )
03063             {
03064                 ssl->handshake->cur_msg = cur->next;
03065                 ssl->handshake->cur_msg_p = cur->next->p + 12;
03066             }
03067             else
03068             {
03069                 ssl->handshake->cur_msg = NULL;
03070                 ssl->handshake->cur_msg_p = NULL;
03071             }
03072         }
03073 
03074         /* Actually send the message out */
03075         if( ( ret = mbedtls_ssl_write_record( ssl, force_flush ) ) != 0 )
03076         {
03077             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
03078             return( ret );
03079         }
03080     }
03081 
03082     if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
03083         return( ret );
03084 
03085     /* Update state and set timer */
03086     if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )
03087         ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
03088     else
03089     {
03090         ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
03091         ssl_set_timer( ssl, ssl->handshake->retransmit_timeout );
03092     }
03093 
03094     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= mbedtls_ssl_flight_transmit" ) );
03095 
03096     return( 0 );
03097 }
03098 
03099 /*
03100  * To be called when the last message of an incoming flight is received.
03101  */
03102 void mbedtls_ssl_recv_flight_completed( mbedtls_ssl_context *ssl )
03103 {
03104     /* We won't need to resend that one any more */
03105     ssl_flight_free( ssl->handshake->flight );
03106     ssl->handshake->flight = NULL;
03107     ssl->handshake->cur_msg = NULL;
03108 
03109     /* The next incoming flight will start with this msg_seq */
03110     ssl->handshake->in_flight_start_seq = ssl->handshake->in_msg_seq;
03111 
03112     /* We don't want to remember CCS's across flight boundaries. */
03113     ssl->handshake->buffering.seen_ccs = 0;
03114 
03115     /* Clear future message buffering structure. */
03116     ssl_buffering_free( ssl );
03117 
03118     /* Cancel timer */
03119     ssl_set_timer( ssl, 0 );
03120 
03121     if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
03122         ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED )
03123     {
03124         ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
03125     }
03126     else
03127         ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_PREPARING;
03128 }
03129 
03130 /*
03131  * To be called when the last message of an outgoing flight is send.
03132  */
03133 void mbedtls_ssl_send_flight_completed( mbedtls_ssl_context *ssl )
03134 {
03135     ssl_reset_retransmit_timeout( ssl );
03136     ssl_set_timer( ssl, ssl->handshake->retransmit_timeout );
03137 
03138     if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
03139         ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED )
03140     {
03141         ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
03142     }
03143     else
03144         ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
03145 }
03146 #endif /* MBEDTLS_SSL_PROTO_DTLS */
03147 
03148 /*
03149  * Handshake layer functions
03150  */
03151 
03152 /*
03153  * Write (DTLS: or queue) current handshake (including CCS) message.
03154  *
03155  *  - fill in handshake headers
03156  *  - update handshake checksum
03157  *  - DTLS: save message for resending
03158  *  - then pass to the record layer
03159  *
03160  * DTLS: except for HelloRequest, messages are only queued, and will only be
03161  * actually sent when calling flight_transmit() or resend().
03162  *
03163  * Inputs:
03164  *  - ssl->out_msglen: 4 + actual handshake message len
03165  *      (4 is the size of handshake headers for TLS)
03166  *  - ssl->out_msg[0]: the handshake type (ClientHello, ServerHello, etc)
03167  *  - ssl->out_msg + 4: the handshake message body
03168  *
03169  * Outputs, ie state before passing to flight_append() or write_record():
03170  *   - ssl->out_msglen: the length of the record contents
03171  *      (including handshake headers but excluding record headers)
03172  *   - ssl->out_msg: the record contents (handshake headers + content)
03173  */
03174 int mbedtls_ssl_write_handshake_msg( mbedtls_ssl_context *ssl )
03175 {
03176     int ret;
03177     const size_t hs_len = ssl->out_msglen - 4;
03178     const unsigned char hs_type = ssl->out_msg[0];
03179 
03180     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write handshake message" ) );
03181 
03182     /*
03183      * Sanity checks
03184      */
03185     if( ssl->out_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE          &&
03186         ssl->out_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC )
03187     {
03188         /* In SSLv3, the client might send a NoCertificate alert. */
03189 #if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_CLI_C)
03190         if( ! ( ssl->minor_ver      == MBEDTLS_SSL_MINOR_VERSION_0 &&
03191                 ssl->out_msgtype    == MBEDTLS_SSL_MSG_ALERT       &&
03192                 ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ) )
03193 #endif /* MBEDTLS_SSL_PROTO_SSL3 && MBEDTLS_SSL_SRV_C */
03194         {
03195             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
03196             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
03197         }
03198     }
03199 
03200     if( ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
03201         hs_type != MBEDTLS_SSL_HS_HELLO_REQUEST &&
03202         ssl->handshake == NULL )
03203     {
03204         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
03205         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
03206     }
03207 
03208 #if defined(MBEDTLS_SSL_PROTO_DTLS)
03209     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
03210         ssl->handshake != NULL &&
03211         ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING )
03212     {
03213         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
03214         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
03215     }
03216 #endif
03217 
03218     /* Double-check that we did not exceed the bounds
03219      * of the outgoing record buffer.
03220      * This should never fail as the various message
03221      * writing functions must obey the bounds of the
03222      * outgoing record buffer, but better be safe.
03223      *
03224      * Note: We deliberately do not check for the MTU or MFL here.
03225      */
03226     if( ssl->out_msglen > MBEDTLS_SSL_OUT_CONTENT_LEN )
03227     {
03228         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Record too large: "
03229                                     "size %u, maximum %u",
03230                                     (unsigned) ssl->out_msglen,
03231                                     (unsigned) MBEDTLS_SSL_OUT_CONTENT_LEN ) );
03232         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
03233     }
03234 
03235     /*
03236      * Fill handshake headers
03237      */
03238     if( ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE )
03239     {
03240         ssl->out_msg[1] = (unsigned char)( hs_len >> 16 );
03241         ssl->out_msg[2] = (unsigned char)( hs_len >>  8 );
03242         ssl->out_msg[3] = (unsigned char)( hs_len       );
03243 
03244         /*
03245          * DTLS has additional fields in the Handshake layer,
03246          * between the length field and the actual payload:
03247          *      uint16 message_seq;
03248          *      uint24 fragment_offset;
03249          *      uint24 fragment_length;
03250          */
03251 #if defined(MBEDTLS_SSL_PROTO_DTLS)
03252         if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
03253         {
03254             /* Make room for the additional DTLS fields */
03255             if( MBEDTLS_SSL_OUT_CONTENT_LEN - ssl->out_msglen < 8 )
03256             {
03257                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS handshake message too large: "
03258                               "size %u, maximum %u",
03259                                (unsigned) ( hs_len ),
03260                                (unsigned) ( MBEDTLS_SSL_OUT_CONTENT_LEN - 12 ) ) );
03261                 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
03262             }
03263 
03264             memmove( ssl->out_msg + 12, ssl->out_msg + 4, hs_len );
03265             ssl->out_msglen += 8;
03266 
03267             /* Write message_seq and update it, except for HelloRequest */
03268             if( hs_type != MBEDTLS_SSL_HS_HELLO_REQUEST )
03269             {
03270                 ssl->out_msg[4] = ( ssl->handshake->out_msg_seq >> 8 ) & 0xFF;
03271                 ssl->out_msg[5] = ( ssl->handshake->out_msg_seq      ) & 0xFF;
03272                 ++( ssl->handshake->out_msg_seq );
03273             }
03274             else
03275             {
03276                 ssl->out_msg[4] = 0;
03277                 ssl->out_msg[5] = 0;
03278             }
03279 
03280             /* Handshake hashes are computed without fragmentation,
03281              * so set frag_offset = 0 and frag_len = hs_len for now */
03282             memset( ssl->out_msg + 6, 0x00, 3 );
03283             memcpy( ssl->out_msg + 9, ssl->out_msg + 1, 3 );
03284         }
03285 #endif /* MBEDTLS_SSL_PROTO_DTLS */
03286 
03287         /* Update running hashes of handshake messages seen */
03288         if( hs_type != MBEDTLS_SSL_HS_HELLO_REQUEST )
03289             ssl->handshake->update_checksum( ssl, ssl->out_msg, ssl->out_msglen );
03290     }
03291 
03292     /* Either send now, or just save to be sent (and resent) later */
03293 #if defined(MBEDTLS_SSL_PROTO_DTLS)
03294     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
03295         ( ssl->out_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ||
03296           hs_type != MBEDTLS_SSL_HS_HELLO_REQUEST ) )
03297     {
03298         if( ( ret = ssl_flight_append( ssl ) ) != 0 )
03299         {
03300             MBEDTLS_SSL_DEBUG_RET( 1, "ssl_flight_append", ret );
03301             return( ret );
03302         }
03303     }
03304     else
03305 #endif
03306     {
03307         if( ( ret = mbedtls_ssl_write_record( ssl, SSL_FORCE_FLUSH ) ) != 0 )
03308         {
03309             MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_record", ret );
03310             return( ret );
03311         }
03312     }
03313 
03314     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write handshake message" ) );
03315 
03316     return( 0 );
03317 }
03318 
03319 /*
03320  * Record layer functions
03321  */
03322 
03323 /*
03324  * Write current record.
03325  *
03326  * Uses:
03327  *  - ssl->out_msgtype: type of the message (AppData, Handshake, Alert, CCS)
03328  *  - ssl->out_msglen: length of the record content (excl headers)
03329  *  - ssl->out_msg: record content
03330  */
03331 int mbedtls_ssl_write_record( mbedtls_ssl_context *ssl, uint8_t force_flush )
03332 {
03333     int ret, done = 0;
03334     size_t len = ssl->out_msglen;
03335     uint8_t flush = force_flush;
03336 
03337     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write record" ) );
03338 
03339 #if defined(MBEDTLS_ZLIB_SUPPORT)
03340     if( ssl->transform_out != NULL &&
03341         ssl->session_out->compression == MBEDTLS_SSL_COMPRESS_DEFLATE )
03342     {
03343         if( ( ret = ssl_compress_buf( ssl ) ) != 0 )
03344         {
03345             MBEDTLS_SSL_DEBUG_RET( 1, "ssl_compress_buf", ret );
03346             return( ret );
03347         }
03348 
03349         len = ssl->out_msglen;
03350     }
03351 #endif /*MBEDTLS_ZLIB_SUPPORT */
03352 
03353 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
03354     if( mbedtls_ssl_hw_record_write != NULL )
03355     {
03356         MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_write()" ) );
03357 
03358         ret = mbedtls_ssl_hw_record_write( ssl );
03359         if( ret != 0 && ret != MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH )
03360         {
03361             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_write", ret );
03362             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
03363         }
03364 
03365         if( ret == 0 )
03366             done = 1;
03367     }
03368 #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
03369     if( !done )
03370     {
03371         unsigned i;
03372         size_t protected_record_size;
03373 
03374         ssl->out_hdr[0] = (unsigned char) ssl->out_msgtype;
03375         mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,
03376                            ssl->conf->transport, ssl->out_hdr + 1 );
03377 
03378         memcpy( ssl->out_ctr, ssl->cur_out_ctr, 8 );
03379         ssl->out_len[0] = (unsigned char)( len >> 8 );
03380         ssl->out_len[1] = (unsigned char)( len      );
03381 
03382         if( ssl->transform_out != NULL )
03383         {
03384             if( ( ret = ssl_encrypt_buf( ssl ) ) != 0 )
03385             {
03386                 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_encrypt_buf", ret );
03387                 return( ret );
03388             }
03389 
03390             len = ssl->out_msglen;
03391             ssl->out_len[0] = (unsigned char)( len >> 8 );
03392             ssl->out_len[1] = (unsigned char)( len      );
03393         }
03394 
03395         protected_record_size = len + mbedtls_ssl_hdr_len( ssl );
03396 
03397 #if defined(MBEDTLS_SSL_PROTO_DTLS)
03398         /* In case of DTLS, double-check that we don't exceed
03399          * the remaining space in the datagram. */
03400         if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
03401         {
03402             ret = ssl_get_remaining_space_in_datagram( ssl );
03403             if( ret < 0 )
03404                 return( ret );
03405 
03406             if( protected_record_size > (size_t) ret )
03407             {
03408                 /* Should never happen */
03409                 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
03410             }
03411         }
03412 #endif /* MBEDTLS_SSL_PROTO_DTLS */
03413 
03414         MBEDTLS_SSL_DEBUG_MSG( 3, ( "output record: msgtype = %d, "
03415                                     "version = [%d:%d], msglen = %d",
03416                                     ssl->out_hdr[0], ssl->out_hdr[1],
03417                                     ssl->out_hdr[2], len ) );
03418 
03419         MBEDTLS_SSL_DEBUG_BUF( 4, "output record sent to network",
03420                                ssl->out_hdr, protected_record_size );
03421 
03422         ssl->out_left += protected_record_size;
03423         ssl->out_hdr  += protected_record_size;
03424         ssl_update_out_pointers( ssl, ssl->transform_out );
03425 
03426         for( i = 8; i > ssl_ep_len( ssl ); i-- )
03427             if( ++ssl->cur_out_ctr[i - 1] != 0 )
03428                 break;
03429 
03430         /* The loop goes to its end iff the counter is wrapping */
03431         if( i == ssl_ep_len( ssl ) )
03432         {
03433             MBEDTLS_SSL_DEBUG_MSG( 1, ( "outgoing message counter would wrap" ) );
03434             return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
03435         }
03436     }
03437 
03438 #if defined(MBEDTLS_SSL_PROTO_DTLS)
03439     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
03440         flush == SSL_DONT_FORCE_FLUSH )
03441     {
03442         size_t remaining;
03443         ret = ssl_get_remaining_payload_in_datagram( ssl );
03444         if( ret < 0 )
03445         {
03446             MBEDTLS_SSL_DEBUG_RET( 1, "ssl_get_remaining_payload_in_datagram",
03447                                    ret );
03448             return( ret );
03449         }
03450 
03451         remaining = (size_t) ret;
03452         if( remaining == 0 )
03453         {
03454             flush = SSL_FORCE_FLUSH;
03455         }
03456         else
03457         {
03458             MBEDTLS_SSL_DEBUG_MSG( 2, ( "Still %u bytes available in current datagram", (unsigned) remaining ) );
03459         }
03460     }
03461 #endif /* MBEDTLS_SSL_PROTO_DTLS */
03462 
03463     if( ( flush == SSL_FORCE_FLUSH ) &&
03464         ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
03465     {
03466         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flush_output", ret );
03467         return( ret );
03468     }
03469 
03470     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write record" ) );
03471 
03472     return( 0 );
03473 }
03474 
03475 #if defined(MBEDTLS_SSL_PROTO_DTLS)
03476 
03477 static int ssl_hs_is_proper_fragment( mbedtls_ssl_context *ssl )
03478 {
03479     if( ssl->in_msglen < ssl->in_hslen ||
03480         memcmp( ssl->in_msg + 6, "\0\0\0",        3 ) != 0 ||
03481         memcmp( ssl->in_msg + 9, ssl->in_msg + 1, 3 ) != 0 )
03482     {
03483         return( 1 );
03484     }
03485     return( 0 );
03486 }
03487 
03488 static uint32_t ssl_get_hs_frag_len( mbedtls_ssl_context const *ssl )
03489 {
03490     return( ( ssl->in_msg[9] << 16  ) |
03491             ( ssl->in_msg[10] << 8  ) |
03492               ssl->in_msg[11] );
03493 }
03494 
03495 static uint32_t ssl_get_hs_frag_off( mbedtls_ssl_context const *ssl )
03496 {
03497     return( ( ssl->in_msg[6] << 16 ) |
03498             ( ssl->in_msg[7] << 8  ) |
03499               ssl->in_msg[8] );
03500 }
03501 
03502 static int ssl_check_hs_header( mbedtls_ssl_context const *ssl )
03503 {
03504     uint32_t msg_len, frag_off, frag_len;
03505 
03506     msg_len  = ssl_get_hs_total_len( ssl );
03507     frag_off = ssl_get_hs_frag_off( ssl );
03508     frag_len = ssl_get_hs_frag_len( ssl );
03509 
03510     if( frag_off > msg_len )
03511         return( -1 );
03512 
03513     if( frag_len > msg_len - frag_off )
03514         return( -1 );
03515 
03516     if( frag_len + 12 > ssl->in_msglen )
03517         return( -1 );
03518 
03519     return( 0 );
03520 }
03521 
03522 /*
03523  * Mark bits in bitmask (used for DTLS HS reassembly)
03524  */
03525 static void ssl_bitmask_set( unsigned char *mask, size_t offset, size_t len )
03526 {
03527     unsigned int start_bits, end_bits;
03528 
03529     start_bits = 8 - ( offset % 8 );
03530     if( start_bits != 8 )
03531     {
03532         size_t first_byte_idx = offset / 8;
03533 
03534         /* Special case */
03535         if( len <= start_bits )
03536         {
03537             for( ; len != 0; len-- )
03538                 mask[first_byte_idx] |= 1 << ( start_bits - len );
03539 
03540             /* Avoid potential issues with offset or len becoming invalid */
03541             return;
03542         }
03543 
03544         offset += start_bits; /* Now offset % 8 == 0 */
03545         len -= start_bits;
03546 
03547         for( ; start_bits != 0; start_bits-- )
03548             mask[first_byte_idx] |= 1 << ( start_bits - 1 );
03549     }
03550 
03551     end_bits = len % 8;
03552     if( end_bits != 0 )
03553     {
03554         size_t last_byte_idx = ( offset + len ) / 8;
03555 
03556         len -= end_bits; /* Now len % 8 == 0 */
03557 
03558         for( ; end_bits != 0; end_bits-- )
03559             mask[last_byte_idx] |= 1 << ( 8 - end_bits );
03560     }
03561 
03562     memset( mask + offset / 8, 0xFF, len / 8 );
03563 }
03564 
03565 /*
03566  * Check that bitmask is full
03567  */
03568 static int ssl_bitmask_check( unsigned char *mask, size_t len )
03569 {
03570     size_t i;
03571 
03572     for( i = 0; i < len / 8; i++ )
03573         if( mask[i] != 0xFF )
03574             return( -1 );
03575 
03576     for( i = 0; i < len % 8; i++ )
03577         if( ( mask[len / 8] & ( 1 << ( 7 - i ) ) ) == 0 )
03578             return( -1 );
03579 
03580     return( 0 );
03581 }
03582 
03583 /* msg_len does not include the handshake header */
03584 static size_t ssl_get_reassembly_buffer_size( size_t msg_len,
03585                                               unsigned add_bitmap )
03586 {
03587     size_t alloc_len;
03588 
03589     alloc_len  = 12;                                 /* Handshake header */
03590     alloc_len += msg_len;                            /* Content buffer   */
03591 
03592     if( add_bitmap )
03593         alloc_len += msg_len / 8 + ( msg_len % 8 != 0 ); /* Bitmap       */
03594 
03595     return( alloc_len );
03596 }
03597 
03598 #endif /* MBEDTLS_SSL_PROTO_DTLS */
03599 
03600 static uint32_t ssl_get_hs_total_len( mbedtls_ssl_context const *ssl )
03601 {
03602     return( ( ssl->in_msg[1] << 16 ) |
03603             ( ssl->in_msg[2] << 8  ) |
03604               ssl->in_msg[3] );
03605 }
03606 
03607 int mbedtls_ssl_prepare_handshake_record( mbedtls_ssl_context *ssl )
03608 {
03609     if( ssl->in_msglen < mbedtls_ssl_hs_hdr_len( ssl ) )
03610     {
03611         MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake message too short: %d",
03612                             ssl->in_msglen ) );
03613         return( MBEDTLS_ERR_SSL_INVALID_RECORD );
03614     }
03615 
03616     ssl->in_hslen = mbedtls_ssl_hs_hdr_len( ssl ) + ssl_get_hs_total_len( ssl );
03617 
03618     MBEDTLS_SSL_DEBUG_MSG( 3, ( "handshake message: msglen ="
03619                         " %d, type = %d, hslen = %d",
03620                         ssl->in_msglen, ssl->in_msg[0], ssl->in_hslen ) );
03621 
03622 #if defined(MBEDTLS_SSL_PROTO_DTLS)
03623     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
03624     {
03625         int ret;
03626         unsigned int recv_msg_seq = ( ssl->in_msg[4] << 8 ) | ssl->in_msg[5];
03627 
03628         if( ssl_check_hs_header( ssl ) != 0 )
03629         {
03630             MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid handshake header" ) );
03631             return( MBEDTLS_ERR_SSL_INVALID_RECORD );
03632         }
03633 
03634         if( ssl->handshake != NULL &&
03635             ( ( ssl->state   != MBEDTLS_SSL_HANDSHAKE_OVER &&
03636                 recv_msg_seq != ssl->handshake->in_msg_seq ) ||
03637               ( ssl->state  == MBEDTLS_SSL_HANDSHAKE_OVER &&
03638                 ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_HELLO ) ) )
03639         {
03640             if( recv_msg_seq > ssl->handshake->in_msg_seq )
03641             {
03642                 MBEDTLS_SSL_DEBUG_MSG( 2, ( "received future handshake message of sequence number %u (next %u)",
03643                                             recv_msg_seq,
03644                                             ssl->handshake->in_msg_seq ) );
03645                 return( MBEDTLS_ERR_SSL_EARLY_MESSAGE );
03646             }
03647 
03648             /* Retransmit only on last message from previous flight, to avoid
03649              * too many retransmissions.
03650              * Besides, No sane server ever retransmits HelloVerifyRequest */
03651             if( recv_msg_seq == ssl->handshake->in_flight_start_seq - 1 &&
03652                 ssl->in_msg[0] != MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST )
03653             {
03654                 MBEDTLS_SSL_DEBUG_MSG( 2, ( "received message from last flight, "
03655                                     "message_seq = %d, start_of_flight = %d",
03656                                     recv_msg_seq,
03657                                     ssl->handshake->in_flight_start_seq ) );
03658 
03659                 if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )
03660                 {
03661                     MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend", ret );
03662                     return( ret );
03663                 }
03664             }
03665             else
03666             {
03667                 MBEDTLS_SSL_DEBUG_MSG( 2, ( "dropping out-of-sequence message: "
03668                                     "message_seq = %d, expected = %d",
03669                                     recv_msg_seq,
03670                                     ssl->handshake->in_msg_seq ) );
03671             }
03672 
03673             return( MBEDTLS_ERR_SSL_CONTINUE_PROCESSING );
03674         }
03675         /* Wait until message completion to increment in_msg_seq */
03676 
03677         /* Message reassembly is handled alongside buffering of future
03678          * messages; the commonality is that both handshake fragments and
03679          * future messages cannot be forwarded immediately to the
03680          * handshake logic layer. */
03681         if( ssl_hs_is_proper_fragment( ssl ) == 1 )
03682         {
03683             MBEDTLS_SSL_DEBUG_MSG( 2, ( "found fragmented DTLS handshake message" ) );
03684             return( MBEDTLS_ERR_SSL_EARLY_MESSAGE );
03685         }
03686     }
03687     else
03688 #endif /* MBEDTLS_SSL_PROTO_DTLS */
03689     /* With TLS we don't handle fragmentation (for now) */
03690     if( ssl->in_msglen < ssl->in_hslen )
03691     {
03692         MBEDTLS_SSL_DEBUG_MSG( 1, ( "TLS handshake fragmentation not supported" ) );
03693         return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
03694     }
03695 
03696     return( 0 );
03697 }
03698 
03699 void mbedtls_ssl_update_handshake_status( mbedtls_ssl_context *ssl )
03700 {
03701     mbedtls_ssl_handshake_params * const hs = ssl->handshake;
03702 
03703     if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER && hs != NULL )
03704     {
03705         ssl->handshake->update_checksum( ssl, ssl->in_msg, ssl->in_hslen );
03706     }
03707 
03708     /* Handshake message is complete, increment counter */
03709 #if defined(MBEDTLS_SSL_PROTO_DTLS)
03710     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
03711         ssl->handshake != NULL )
03712     {
03713         unsigned offset;
03714         mbedtls_ssl_hs_buffer *hs_buf;
03715 
03716         /* Increment handshake sequence number */
03717         hs->in_msg_seq++;
03718 
03719         /*
03720          * Clear up handshake buffering and reassembly structure.
03721          */
03722 
03723         /* Free first entry */
03724         ssl_buffering_free_slot( ssl, 0 );
03725 
03726         /* Shift all other entries */
03727         for( offset = 0, hs_buf = &hs->buffering.hs[0];
03728              offset + 1 < MBEDTLS_SSL_MAX_BUFFERED_HS;
03729              offset++, hs_buf++ )
03730         {
03731             *hs_buf = *(hs_buf + 1);
03732         }
03733 
03734         /* Create a fresh last entry */
03735         memset( hs_buf, 0, sizeof( mbedtls_ssl_hs_buffer ) );
03736     }
03737 #endif
03738 }
03739 
03740 /*
03741  * DTLS anti-replay: RFC 6347 4.1.2.6
03742  *
03743  * in_window is a field of bits numbered from 0 (lsb) to 63 (msb).
03744  * Bit n is set iff record number in_window_top - n has been seen.
03745  *
03746  * Usually, in_window_top is the last record number seen and the lsb of
03747  * in_window is set. The only exception is the initial state (record number 0
03748  * not seen yet).
03749  */
03750 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
03751 static void ssl_dtls_replay_reset( mbedtls_ssl_context *ssl )
03752 {
03753     ssl->in_window_top = 0;
03754     ssl->in_window = 0;
03755 }
03756 
03757 static inline uint64_t ssl_load_six_bytes( unsigned char *buf )
03758 {
03759     return( ( (uint64_t) buf[0] << 40 ) |
03760             ( (uint64_t) buf[1] << 32 ) |
03761             ( (uint64_t) buf[2] << 24 ) |
03762             ( (uint64_t) buf[3] << 16 ) |
03763             ( (uint64_t) buf[4] <<  8 ) |
03764             ( (uint64_t) buf[5]       ) );
03765 }
03766 
03767 /*
03768  * Return 0 if sequence number is acceptable, -1 otherwise
03769  */
03770 int mbedtls_ssl_dtls_replay_check( mbedtls_ssl_context *ssl )
03771 {
03772     uint64_t rec_seqnum = ssl_load_six_bytes( ssl->in_ctr + 2 );
03773     uint64_t bit;
03774 
03775     if( ssl->conf->anti_replay == MBEDTLS_SSL_ANTI_REPLAY_DISABLED )
03776         return( 0 );
03777 
03778     if( rec_seqnum > ssl->in_window_top )
03779         return( 0 );
03780 
03781     bit = ssl->in_window_top - rec_seqnum;
03782 
03783     if( bit >= 64 )
03784         return( -1 );
03785 
03786     if( ( ssl->in_window & ( (uint64_t) 1 << bit ) ) != 0 )
03787         return( -1 );
03788 
03789     return( 0 );
03790 }
03791 
03792 /*
03793  * Update replay window on new validated record
03794  */
03795 void mbedtls_ssl_dtls_replay_update( mbedtls_ssl_context *ssl )
03796 {
03797     uint64_t rec_seqnum = ssl_load_six_bytes( ssl->in_ctr + 2 );
03798 
03799     if( ssl->conf->anti_replay == MBEDTLS_SSL_ANTI_REPLAY_DISABLED )
03800         return;
03801 
03802     if( rec_seqnum > ssl->in_window_top )
03803     {
03804         /* Update window_top and the contents of the window */
03805         uint64_t shift = rec_seqnum - ssl->in_window_top;
03806 
03807         if( shift >= 64 )
03808             ssl->in_window = 1;
03809         else
03810         {
03811             ssl->in_window <<= shift;
03812             ssl->in_window |= 1;
03813         }
03814 
03815         ssl->in_window_top = rec_seqnum;
03816     }
03817     else
03818     {
03819         /* Mark that number as seen in the current window */
03820         uint64_t bit = ssl->in_window_top - rec_seqnum;
03821 
03822         if( bit < 64 ) /* Always true, but be extra sure */
03823             ssl->in_window |= (uint64_t) 1 << bit;
03824     }
03825 }
03826 #endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */
03827 
03828 #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
03829 /* Forward declaration */
03830 static int ssl_session_reset_int( mbedtls_ssl_context *ssl, int partial );
03831 
03832 /*
03833  * Without any SSL context, check if a datagram looks like a ClientHello with
03834  * a valid cookie, and if it doesn't, generate a HelloVerifyRequest message.
03835  * Both input and output include full DTLS headers.
03836  *
03837  * - if cookie is valid, return 0
03838  * - if ClientHello looks superficially valid but cookie is not,
03839  *   fill obuf and set olen, then
03840  *   return MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED
03841  * - otherwise return a specific error code
03842  */
03843 static int ssl_check_dtls_clihlo_cookie(
03844                            mbedtls_ssl_cookie_write_t *f_cookie_write,
03845                            mbedtls_ssl_cookie_check_t *f_cookie_check,
03846                            void *p_cookie,
03847                            const unsigned char *cli_id, size_t cli_id_len,
03848                            const unsigned char *in, size_t in_len,
03849                            unsigned char *obuf, size_t buf_len, size_t *olen )
03850 {
03851     size_t sid_len, cookie_len;
03852     unsigned char *p;
03853 
03854     if( f_cookie_write == NULL || f_cookie_check == NULL )
03855         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
03856 
03857     /*
03858      * Structure of ClientHello with record and handshake headers,
03859      * and expected values. We don't need to check a lot, more checks will be
03860      * done when actually parsing the ClientHello - skipping those checks
03861      * avoids code duplication and does not make cookie forging any easier.
03862      *
03863      *  0-0  ContentType type;                  copied, must be handshake
03864      *  1-2  ProtocolVersion version;           copied
03865      *  3-4  uint16 epoch;                      copied, must be 0
03866      *  5-10 uint48 sequence_number;            copied
03867      * 11-12 uint16 length;                     (ignored)
03868      *
03869      * 13-13 HandshakeType msg_type;            (ignored)
03870      * 14-16 uint24 length;                     (ignored)
03871      * 17-18 uint16 message_seq;                copied
03872      * 19-21 uint24 fragment_offset;            copied, must be 0
03873      * 22-24 uint24 fragment_length;            (ignored)
03874      *
03875      * 25-26 ProtocolVersion client_version;    (ignored)
03876      * 27-58 Random random;                     (ignored)
03877      * 59-xx SessionID session_id;              1 byte len + sid_len content
03878      * 60+   opaque cookie<0..2^8-1>;           1 byte len + content
03879      *       ...
03880      *
03881      * Minimum length is 61 bytes.
03882      */
03883     if( in_len < 61 ||
03884         in[0] != MBEDTLS_SSL_MSG_HANDSHAKE ||
03885         in[3] != 0 || in[4] != 0 ||
03886         in[19] != 0 || in[20] != 0 || in[21] != 0 )
03887     {
03888         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
03889     }
03890 
03891     sid_len = in[59];
03892     if( sid_len > in_len - 61 )
03893         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
03894 
03895     cookie_len = in[60 + sid_len];
03896     if( cookie_len > in_len - 60 )
03897         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
03898 
03899     if( f_cookie_check( p_cookie, in + sid_len + 61, cookie_len,
03900                         cli_id, cli_id_len ) == 0 )
03901     {
03902         /* Valid cookie */
03903         return( 0 );
03904     }
03905 
03906     /*
03907      * If we get here, we've got an invalid cookie, let's prepare HVR.
03908      *
03909      *  0-0  ContentType type;                  copied
03910      *  1-2  ProtocolVersion version;           copied
03911      *  3-4  uint16 epoch;                      copied
03912      *  5-10 uint48 sequence_number;            copied
03913      * 11-12 uint16 length;                     olen - 13
03914      *
03915      * 13-13 HandshakeType msg_type;            hello_verify_request
03916      * 14-16 uint24 length;                     olen - 25
03917      * 17-18 uint16 message_seq;                copied
03918      * 19-21 uint24 fragment_offset;            copied
03919      * 22-24 uint24 fragment_length;            olen - 25
03920      *
03921      * 25-26 ProtocolVersion server_version;    0xfe 0xff
03922      * 27-27 opaque cookie<0..2^8-1>;           cookie_len = olen - 27, cookie
03923      *
03924      * Minimum length is 28.
03925      */
03926     if( buf_len < 28 )
03927         return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
03928 
03929     /* Copy most fields and adapt others */
03930     memcpy( obuf, in, 25 );
03931     obuf[13] = MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST;
03932     obuf[25] = 0xfe;
03933     obuf[26] = 0xff;
03934 
03935     /* Generate and write actual cookie */
03936     p = obuf + 28;
03937     if( f_cookie_write( p_cookie,
03938                         &p, obuf + buf_len, cli_id, cli_id_len ) != 0 )
03939     {
03940         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
03941     }
03942 
03943     *olen = p - obuf;
03944 
03945     /* Go back and fill length fields */
03946     obuf[27] = (unsigned char)( *olen - 28 );
03947 
03948     obuf[14] = obuf[22] = (unsigned char)( ( *olen - 25 ) >> 16 );
03949     obuf[15] = obuf[23] = (unsigned char)( ( *olen - 25 ) >>  8 );
03950     obuf[16] = obuf[24] = (unsigned char)( ( *olen - 25 )       );
03951 
03952     obuf[11] = (unsigned char)( ( *olen - 13 ) >>  8 );
03953     obuf[12] = (unsigned char)( ( *olen - 13 )       );
03954 
03955     return( MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED );
03956 }
03957 
03958 /*
03959  * Handle possible client reconnect with the same UDP quadruplet
03960  * (RFC 6347 Section 4.2.8).
03961  *
03962  * Called by ssl_parse_record_header() in case we receive an epoch 0 record
03963  * that looks like a ClientHello.
03964  *
03965  * - if the input looks like a ClientHello without cookies,
03966  *   send back HelloVerifyRequest, then
03967  *   return MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED
03968  * - if the input looks like a ClientHello with a valid cookie,
03969  *   reset the session of the current context, and
03970  *   return MBEDTLS_ERR_SSL_CLIENT_RECONNECT
03971  * - if anything goes wrong, return a specific error code
03972  *
03973  * mbedtls_ssl_read_record() will ignore the record if anything else than
03974  * MBEDTLS_ERR_SSL_CLIENT_RECONNECT or 0 is returned, although this function
03975  * cannot not return 0.
03976  */
03977 static int ssl_handle_possible_reconnect( mbedtls_ssl_context *ssl )
03978 {
03979     int ret;
03980     size_t len;
03981 
03982     ret = ssl_check_dtls_clihlo_cookie(
03983             ssl->conf->f_cookie_write,
03984             ssl->conf->f_cookie_check,
03985             ssl->conf->p_cookie,
03986             ssl->cli_id, ssl->cli_id_len,
03987             ssl->in_buf, ssl->in_left,
03988             ssl->out_buf, MBEDTLS_SSL_OUT_CONTENT_LEN, &len );
03989 
03990     MBEDTLS_SSL_DEBUG_RET( 2, "ssl_check_dtls_clihlo_cookie", ret );
03991 
03992     if( ret == MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED )
03993     {
03994         /* Don't check write errors as we can't do anything here.
03995          * If the error is permanent we'll catch it later,
03996          * if it's not, then hopefully it'll work next time. */
03997         (void) ssl->f_send( ssl->p_bio, ssl->out_buf, len );
03998 
03999         return( MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED );
04000     }
04001 
04002     if( ret == 0 )
04003     {
04004         /* Got a valid cookie, partially reset context */
04005         if( ( ret = ssl_session_reset_int( ssl, 1 ) ) != 0 )
04006         {
04007             MBEDTLS_SSL_DEBUG_RET( 1, "reset", ret );
04008             return( ret );
04009         }
04010 
04011         return( MBEDTLS_ERR_SSL_CLIENT_RECONNECT );
04012     }
04013 
04014     return( ret );
04015 }
04016 #endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */
04017 
04018 /*
04019  * ContentType type;
04020  * ProtocolVersion version;
04021  * uint16 epoch;            // DTLS only
04022  * uint48 sequence_number;  // DTLS only
04023  * uint16 length;
04024  *
04025  * Return 0 if header looks sane (and, for DTLS, the record is expected)
04026  * MBEDTLS_ERR_SSL_INVALID_RECORD if the header looks bad,
04027  * MBEDTLS_ERR_SSL_UNEXPECTED_RECORD (DTLS only) if sane but unexpected.
04028  *
04029  * With DTLS, mbedtls_ssl_read_record() will:
04030  * 1. proceed with the record if this function returns 0
04031  * 2. drop only the current record if this function returns UNEXPECTED_RECORD
04032  * 3. return CLIENT_RECONNECT if this function return that value
04033  * 4. drop the whole datagram if this function returns anything else.
04034  * Point 2 is needed when the peer is resending, and we have already received
04035  * the first record from a datagram but are still waiting for the others.
04036  */
04037 static int ssl_parse_record_header( mbedtls_ssl_context *ssl )
04038 {
04039     int major_ver, minor_ver;
04040 
04041     MBEDTLS_SSL_DEBUG_BUF( 4, "input record header", ssl->in_hdr, mbedtls_ssl_hdr_len( ssl ) );
04042 
04043     ssl->in_msgtype =  ssl->in_hdr[0];
04044     ssl->in_msglen = ( ssl->in_len[0] << 8 ) | ssl->in_len[1];
04045     mbedtls_ssl_read_version( &major_ver, &minor_ver, ssl->conf->transport, ssl->in_hdr + 1 );
04046 
04047     MBEDTLS_SSL_DEBUG_MSG( 3, ( "input record: msgtype = %d, "
04048                         "version = [%d:%d], msglen = %d",
04049                         ssl->in_msgtype,
04050                         major_ver, minor_ver, ssl->in_msglen ) );
04051 
04052     /* Check record type */
04053     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE &&
04054         ssl->in_msgtype != MBEDTLS_SSL_MSG_ALERT &&
04055         ssl->in_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC &&
04056         ssl->in_msgtype != MBEDTLS_SSL_MSG_APPLICATION_DATA )
04057     {
04058         MBEDTLS_SSL_DEBUG_MSG( 1, ( "unknown record type" ) );
04059 
04060 #if defined(MBEDTLS_SSL_PROTO_DTLS)
04061         /* Silently ignore invalid DTLS records as recommended by RFC 6347
04062          * Section 4.1.2.7 */
04063         if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM )
04064 #endif /* MBEDTLS_SSL_PROTO_DTLS */
04065             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
04066                                     MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
04067 
04068         return( MBEDTLS_ERR_SSL_INVALID_RECORD );
04069     }
04070 
04071     /* Check version */
04072     if( major_ver != ssl->major_ver )
04073     {
04074         MBEDTLS_SSL_DEBUG_MSG( 1, ( "major version mismatch" ) );
04075         return( MBEDTLS_ERR_SSL_INVALID_RECORD );
04076     }
04077 
04078     if( minor_ver > ssl->conf->max_minor_ver )
04079     {
04080         MBEDTLS_SSL_DEBUG_MSG( 1, ( "minor version mismatch" ) );
04081         return( MBEDTLS_ERR_SSL_INVALID_RECORD );
04082     }
04083 
04084     /* Check length against the size of our buffer */
04085     if( ssl->in_msglen > MBEDTLS_SSL_IN_BUFFER_LEN
04086                          - (size_t)( ssl->in_msg - ssl->in_buf ) )
04087     {
04088         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
04089         return( MBEDTLS_ERR_SSL_INVALID_RECORD );
04090     }
04091 
04092     /*
04093      * DTLS-related tests.
04094      * Check epoch before checking length constraint because
04095      * the latter varies with the epoch. E.g., if a ChangeCipherSpec
04096      * message gets duplicated before the corresponding Finished message,
04097      * the second ChangeCipherSpec should be discarded because it belongs
04098      * to an old epoch, but not because its length is shorter than
04099      * the minimum record length for packets using the new record transform.
04100      * Note that these two kinds of failures are handled differently,
04101      * as an unexpected record is silently skipped but an invalid
04102      * record leads to the entire datagram being dropped.
04103      */
04104 #if defined(MBEDTLS_SSL_PROTO_DTLS)
04105     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
04106     {
04107         unsigned int rec_epoch = ( ssl->in_ctr[0] << 8 ) | ssl->in_ctr[1];
04108 
04109         /* Check epoch (and sequence number) with DTLS */
04110         if( rec_epoch != ssl->in_epoch )
04111         {
04112             MBEDTLS_SSL_DEBUG_MSG( 1, ( "record from another epoch: "
04113                                         "expected %d, received %d",
04114                                         ssl->in_epoch, rec_epoch ) );
04115 
04116 #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
04117             /*
04118              * Check for an epoch 0 ClientHello. We can't use in_msg here to
04119              * access the first byte of record content (handshake type), as we
04120              * have an active transform (possibly iv_len != 0), so use the
04121              * fact that the record header len is 13 instead.
04122              */
04123             if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
04124                 ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER &&
04125                 rec_epoch == 0 &&
04126                 ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
04127                 ssl->in_left > 13 &&
04128                 ssl->in_buf[13] == MBEDTLS_SSL_HS_CLIENT_HELLO )
04129             {
04130                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "possible client reconnect "
04131                                             "from the same port" ) );
04132                 return( ssl_handle_possible_reconnect( ssl ) );
04133             }
04134             else
04135 #endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */
04136             {
04137                 /* Consider buffering the record. */
04138                 if( rec_epoch == (unsigned int) ssl->in_epoch + 1 )
04139                 {
04140                     MBEDTLS_SSL_DEBUG_MSG( 2, ( "Consider record for buffering" ) );
04141                     return( MBEDTLS_ERR_SSL_EARLY_MESSAGE );
04142                 }
04143 
04144                 return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD );
04145             }
04146         }
04147 
04148 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
04149         /* Replay detection only works for the current epoch */
04150         if( rec_epoch == ssl->in_epoch &&
04151             mbedtls_ssl_dtls_replay_check( ssl ) != 0 )
04152         {
04153             MBEDTLS_SSL_DEBUG_MSG( 1, ( "replayed record" ) );
04154             return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD );
04155         }
04156 #endif
04157 
04158         /* Drop unexpected ApplicationData records,
04159          * except at the beginning of renegotiations */
04160         if( ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA &&
04161             ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER
04162 #if defined(MBEDTLS_SSL_RENEGOTIATION)
04163             && ! ( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
04164                    ssl->state == MBEDTLS_SSL_SERVER_HELLO )
04165 #endif
04166             )
04167         {
04168             MBEDTLS_SSL_DEBUG_MSG( 1, ( "dropping unexpected ApplicationData" ) );
04169             return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD );
04170         }
04171     }
04172 #endif /* MBEDTLS_SSL_PROTO_DTLS */
04173 
04174 
04175     /* Check length against bounds of the current transform and version */
04176     if( ssl->transform_in == NULL )
04177     {
04178         if( ssl->in_msglen < 1 ||
04179             ssl->in_msglen > MBEDTLS_SSL_IN_CONTENT_LEN )
04180         {
04181             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
04182             return( MBEDTLS_ERR_SSL_INVALID_RECORD );
04183         }
04184     }
04185     else
04186     {
04187         if( ssl->in_msglen < ssl->transform_in->minlen )
04188         {
04189             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
04190             return( MBEDTLS_ERR_SSL_INVALID_RECORD );
04191         }
04192 
04193 #if defined(MBEDTLS_SSL_PROTO_SSL3)
04194         if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 &&
04195             ssl->in_msglen > ssl->transform_in->minlen + MBEDTLS_SSL_IN_CONTENT_LEN )
04196         {
04197             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
04198             return( MBEDTLS_ERR_SSL_INVALID_RECORD );
04199         }
04200 #endif
04201 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
04202     defined(MBEDTLS_SSL_PROTO_TLS1_2)
04203         /*
04204          * TLS encrypted messages can have up to 256 bytes of padding
04205          */
04206         if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 &&
04207             ssl->in_msglen > ssl->transform_in->minlen +
04208                              MBEDTLS_SSL_IN_CONTENT_LEN + 256 )
04209         {
04210             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
04211             return( MBEDTLS_ERR_SSL_INVALID_RECORD );
04212         }
04213 #endif
04214     }
04215 
04216     return( 0 );
04217 }
04218 
04219 /*
04220  * If applicable, decrypt (and decompress) record content
04221  */
04222 static int ssl_prepare_record_content( mbedtls_ssl_context *ssl )
04223 {
04224     int ret, done = 0;
04225 
04226     MBEDTLS_SSL_DEBUG_BUF( 4, "input record from network",
04227                    ssl->in_hdr, mbedtls_ssl_hdr_len( ssl ) + ssl->in_msglen );
04228 
04229 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
04230     if( mbedtls_ssl_hw_record_read != NULL )
04231     {
04232         MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_read()" ) );
04233 
04234         ret = mbedtls_ssl_hw_record_read( ssl );
04235         if( ret != 0 && ret != MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH )
04236         {
04237             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_read", ret );
04238             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
04239         }
04240 
04241         if( ret == 0 )
04242             done = 1;
04243     }
04244 #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
04245     if( !done && ssl->transform_in != NULL )
04246     {
04247         if( ( ret = ssl_decrypt_buf( ssl ) ) != 0 )
04248         {
04249             MBEDTLS_SSL_DEBUG_RET( 1, "ssl_decrypt_buf", ret );
04250             return( ret );
04251         }
04252 
04253         MBEDTLS_SSL_DEBUG_BUF( 4, "input payload after decrypt",
04254                        ssl->in_msg, ssl->in_msglen );
04255 
04256         if( ssl->in_msglen > MBEDTLS_SSL_IN_CONTENT_LEN )
04257         {
04258             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
04259             return( MBEDTLS_ERR_SSL_INVALID_RECORD );
04260         }
04261     }
04262 
04263 #if defined(MBEDTLS_ZLIB_SUPPORT)
04264     if( ssl->transform_in != NULL &&
04265         ssl->session_in->compression == MBEDTLS_SSL_COMPRESS_DEFLATE )
04266     {
04267         if( ( ret = ssl_decompress_buf( ssl ) ) != 0 )
04268         {
04269             MBEDTLS_SSL_DEBUG_RET( 1, "ssl_decompress_buf", ret );
04270             return( ret );
04271         }
04272     }
04273 #endif /* MBEDTLS_ZLIB_SUPPORT */
04274 
04275 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
04276     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
04277     {
04278         mbedtls_ssl_dtls_replay_update( ssl );
04279     }
04280 #endif
04281 
04282     return( 0 );
04283 }
04284 
04285 static void ssl_handshake_wrapup_free_hs_transform( mbedtls_ssl_context *ssl );
04286 
04287 /*
04288  * Read a record.
04289  *
04290  * Silently ignore non-fatal alert (and for DTLS, invalid records as well,
04291  * RFC 6347 4.1.2.7) and continue reading until a valid record is found.
04292  *
04293  */
04294 
04295 /* Helper functions for mbedtls_ssl_read_record(). */
04296 static int ssl_consume_current_message( mbedtls_ssl_context *ssl );
04297 static int ssl_get_next_record( mbedtls_ssl_context *ssl );
04298 static int ssl_record_is_in_progress( mbedtls_ssl_context *ssl );
04299 
04300 int mbedtls_ssl_read_record( mbedtls_ssl_context *ssl,
04301                              unsigned update_hs_digest )
04302 {
04303     int ret;
04304 
04305     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> read record" ) );
04306 
04307     if( ssl->keep_current_message == 0 )
04308     {
04309         do {
04310 
04311             ret = ssl_consume_current_message( ssl );
04312             if( ret != 0 )
04313                 return( ret );
04314 
04315             if( ssl_record_is_in_progress( ssl ) == 0 )
04316             {
04317 #if defined(MBEDTLS_SSL_PROTO_DTLS)
04318                 int have_buffered = 0;
04319 
04320                 /* We only check for buffered messages if the
04321                  * current datagram is fully consumed. */
04322                 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
04323                     ssl_next_record_is_in_datagram( ssl ) == 0 )
04324                 {
04325                     if( ssl_load_buffered_message( ssl ) == 0 )
04326                         have_buffered = 1;
04327                 }
04328 
04329                 if( have_buffered == 0 )
04330 #endif /* MBEDTLS_SSL_PROTO_DTLS */
04331                 {
04332                     ret = ssl_get_next_record( ssl );
04333                     if( ret == MBEDTLS_ERR_SSL_CONTINUE_PROCESSING )
04334                         continue;
04335 
04336                     if( ret != 0 )
04337                     {
04338                         MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_get_next_record" ), ret );
04339                         return( ret );
04340                     }
04341                 }
04342             }
04343 
04344             ret = mbedtls_ssl_handle_message_type( ssl );
04345 
04346 #if defined(MBEDTLS_SSL_PROTO_DTLS)
04347             if( ret == MBEDTLS_ERR_SSL_EARLY_MESSAGE )
04348             {
04349                 /* Buffer future message */
04350                 ret = ssl_buffer_message( ssl );
04351                 if( ret != 0 )
04352                     return( ret );
04353 
04354                 ret = MBEDTLS_ERR_SSL_CONTINUE_PROCESSING;
04355             }
04356 #endif /* MBEDTLS_SSL_PROTO_DTLS */
04357 
04358         } while( MBEDTLS_ERR_SSL_NON_FATAL           == ret  ||
04359                  MBEDTLS_ERR_SSL_CONTINUE_PROCESSING == ret );
04360 
04361         if( 0 != ret )
04362         {
04363             MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ssl_handle_message_type" ), ret );
04364             return( ret );
04365         }
04366 
04367         if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
04368             update_hs_digest == 1 )
04369         {
04370             mbedtls_ssl_update_handshake_status( ssl );
04371         }
04372     }
04373     else
04374     {
04375         MBEDTLS_SSL_DEBUG_MSG( 2, ( "reuse previously read message" ) );
04376         ssl->keep_current_message = 0;
04377     }
04378 
04379     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= read record" ) );
04380 
04381     return( 0 );
04382 }
04383 
04384 #if defined(MBEDTLS_SSL_PROTO_DTLS)
04385 static int ssl_next_record_is_in_datagram( mbedtls_ssl_context *ssl )
04386 {
04387     if( ssl->in_left > ssl->next_record_offset )
04388         return( 1 );
04389 
04390     return( 0 );
04391 }
04392 
04393 static int ssl_load_buffered_message( mbedtls_ssl_context *ssl )
04394 {
04395     mbedtls_ssl_handshake_params * const hs = ssl->handshake;
04396     mbedtls_ssl_hs_buffer * hs_buf;
04397     int ret = 0;
04398 
04399     if( hs == NULL )
04400         return( -1 );
04401 
04402     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> ssl_load_buffered_messsage" ) );
04403 
04404     if( ssl->state == MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC ||
04405         ssl->state == MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC )
04406     {
04407         /* Check if we have seen a ChangeCipherSpec before.
04408          * If yes, synthesize a CCS record. */
04409         if( !hs->buffering.seen_ccs )
04410         {
04411             MBEDTLS_SSL_DEBUG_MSG( 2, ( "CCS not seen in the current flight" ) );
04412             ret = -1;
04413             goto exit;
04414         }
04415 
04416         MBEDTLS_SSL_DEBUG_MSG( 2, ( "Injecting buffered CCS message" ) );
04417         ssl->in_msgtype = MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC;
04418         ssl->in_msglen = 1;
04419         ssl->in_msg[0] = 1;
04420 
04421         /* As long as they are equal, the exact value doesn't matter. */
04422         ssl->in_left            = 0;
04423         ssl->next_record_offset = 0;
04424 
04425         hs->buffering.seen_ccs = 0;
04426         goto exit;
04427     }
04428 
04429 #if defined(MBEDTLS_DEBUG_C)
04430     /* Debug only */
04431     {
04432         unsigned offset;
04433         for( offset = 1; offset < MBEDTLS_SSL_MAX_BUFFERED_HS; offset++ )
04434         {
04435             hs_buf = &hs->buffering.hs[offset];
04436             if( hs_buf->is_valid == 1 )
04437             {
04438                 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Future message with sequence number %u %s buffered.",
04439                             hs->in_msg_seq + offset,
04440                             hs_buf->is_complete ? "fully" : "partially" ) );
04441             }
04442         }
04443     }
04444 #endif /* MBEDTLS_DEBUG_C */
04445 
04446     /* Check if we have buffered and/or fully reassembled the
04447      * next handshake message. */
04448     hs_buf = &hs->buffering.hs[0];
04449     if( ( hs_buf->is_valid == 1 ) && ( hs_buf->is_complete == 1 ) )
04450     {
04451         /* Synthesize a record containing the buffered HS message. */
04452         size_t msg_len = ( hs_buf->data[1] << 16 ) |
04453                          ( hs_buf->data[2] << 8  ) |
04454                            hs_buf->data[3];
04455 
04456         /* Double-check that we haven't accidentally buffered
04457          * a message that doesn't fit into the input buffer. */
04458         if( msg_len + 12 > MBEDTLS_SSL_IN_CONTENT_LEN )
04459         {
04460             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
04461             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
04462         }
04463 
04464         MBEDTLS_SSL_DEBUG_MSG( 2, ( "Next handshake message has been buffered - load" ) );
04465         MBEDTLS_SSL_DEBUG_BUF( 3, "Buffered handshake message (incl. header)",
04466                                hs_buf->data, msg_len + 12 );
04467 
04468         ssl->in_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
04469         ssl->in_hslen   = msg_len + 12;
04470         ssl->in_msglen  = msg_len + 12;
04471         memcpy( ssl->in_msg, hs_buf->data, ssl->in_hslen );
04472 
04473         ret = 0;
04474         goto exit;
04475     }
04476     else
04477     {
04478         MBEDTLS_SSL_DEBUG_MSG( 2, ( "Next handshake message %u not or only partially bufffered",
04479                                     hs->in_msg_seq ) );
04480     }
04481 
04482     ret = -1;
04483 
04484 exit:
04485 
04486     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= ssl_load_buffered_message" ) );
04487     return( ret );
04488 }
04489 
04490 static int ssl_buffer_make_space( mbedtls_ssl_context *ssl,
04491                                   size_t desired )
04492 {
04493     int offset;
04494     mbedtls_ssl_handshake_params * const hs = ssl->handshake;
04495     MBEDTLS_SSL_DEBUG_MSG( 2, ( "Attempt to free buffered messages to have %u bytes available",
04496                                 (unsigned) desired ) );
04497 
04498     /* Get rid of future records epoch first, if such exist. */
04499     ssl_free_buffered_record( ssl );
04500 
04501     /* Check if we have enough space available now. */
04502     if( desired <= ( MBEDTLS_SSL_DTLS_MAX_BUFFERING -
04503                      hs->buffering.total_bytes_buffered ) )
04504     {
04505         MBEDTLS_SSL_DEBUG_MSG( 2, ( "Enough space available after freeing future epoch record" ) );
04506         return( 0 );
04507     }
04508 
04509     /* We don't have enough space to buffer the next expected handshake
04510      * message. Remove buffers used for future messages to gain space,
04511      * starting with the most distant one. */
04512     for( offset = MBEDTLS_SSL_MAX_BUFFERED_HS - 1;
04513          offset >= 0; offset-- )
04514     {
04515         MBEDTLS_SSL_DEBUG_MSG( 2, ( "Free buffering slot %d to make space for reassembly of next handshake message",
04516                                     offset ) );
04517 
04518         ssl_buffering_free_slot( ssl, (uint8_t) offset );
04519 
04520         /* Check if we have enough space available now. */
04521         if( desired <= ( MBEDTLS_SSL_DTLS_MAX_BUFFERING -
04522                          hs->buffering.total_bytes_buffered ) )
04523         {
04524             MBEDTLS_SSL_DEBUG_MSG( 2, ( "Enough space available after freeing buffered HS messages" ) );
04525             return( 0 );
04526         }
04527     }
04528 
04529     return( -1 );
04530 }
04531 
04532 static int ssl_buffer_message( mbedtls_ssl_context *ssl )
04533 {
04534     int ret = 0;
04535     mbedtls_ssl_handshake_params * const hs = ssl->handshake;
04536 
04537     if( hs == NULL )
04538         return( 0 );
04539 
04540     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> ssl_buffer_message" ) );
04541 
04542     switch( ssl->in_msgtype )
04543     {
04544         case MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC:
04545             MBEDTLS_SSL_DEBUG_MSG( 2, ( "Remember CCS message" ) );
04546 
04547             hs->buffering.seen_ccs = 1;
04548             break;
04549 
04550         case MBEDTLS_SSL_MSG_HANDSHAKE:
04551         {
04552             unsigned recv_msg_seq_offset;
04553             unsigned recv_msg_seq = ( ssl->in_msg[4] << 8 ) | ssl->in_msg[5];
04554             mbedtls_ssl_hs_buffer *hs_buf;
04555             size_t msg_len = ssl->in_hslen - 12;
04556 
04557             /* We should never receive an old handshake
04558              * message - double-check nonetheless. */
04559             if( recv_msg_seq < ssl->handshake->in_msg_seq )
04560             {
04561                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
04562                 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
04563             }
04564 
04565             recv_msg_seq_offset = recv_msg_seq - ssl->handshake->in_msg_seq;
04566             if( recv_msg_seq_offset >= MBEDTLS_SSL_MAX_BUFFERED_HS )
04567             {
04568                 /* Silently ignore -- message too far in the future */
04569                 MBEDTLS_SSL_DEBUG_MSG( 2,
04570                  ( "Ignore future HS message with sequence number %u, "
04571                    "buffering window %u - %u",
04572                    recv_msg_seq, ssl->handshake->in_msg_seq,
04573                    ssl->handshake->in_msg_seq + MBEDTLS_SSL_MAX_BUFFERED_HS - 1 ) );
04574 
04575                 goto exit;
04576             }
04577 
04578             MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffering HS message with sequence number %u, offset %u ",
04579                                         recv_msg_seq, recv_msg_seq_offset ) );
04580 
04581             hs_buf = &hs->buffering.hs[ recv_msg_seq_offset ];
04582 
04583             /* Check if the buffering for this seq nr has already commenced. */
04584             if( !hs_buf->is_valid )
04585             {
04586                 size_t reassembly_buf_sz;
04587 
04588                 hs_buf->is_fragmented =
04589                     ( ssl_hs_is_proper_fragment( ssl ) == 1 );
04590 
04591                 /* We copy the message back into the input buffer
04592                  * after reassembly, so check that it's not too large.
04593                  * This is an implementation-specific limitation
04594                  * and not one from the standard, hence it is not
04595                  * checked in ssl_check_hs_header(). */
04596                 if( msg_len + 12 > MBEDTLS_SSL_IN_CONTENT_LEN )
04597                 {
04598                     /* Ignore message */
04599                     goto exit;
04600                 }
04601 
04602                 /* Check if we have enough space to buffer the message. */
04603                 if( hs->buffering.total_bytes_buffered >
04604                     MBEDTLS_SSL_DTLS_MAX_BUFFERING )
04605                 {
04606                     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
04607                     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
04608                 }
04609 
04610                 reassembly_buf_sz = ssl_get_reassembly_buffer_size( msg_len,
04611                                                        hs_buf->is_fragmented );
04612 
04613                 if( reassembly_buf_sz > ( MBEDTLS_SSL_DTLS_MAX_BUFFERING -
04614                                           hs->buffering.total_bytes_buffered ) )
04615                 {
04616                     if( recv_msg_seq_offset > 0 )
04617                     {
04618                         /* If we can't buffer a future message because
04619                          * of space limitations -- ignore. */
04620                         MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffering of future message of size %u would exceed the compile-time limit %u (already %u bytes buffered) -- ignore\n",
04621                              (unsigned) msg_len, MBEDTLS_SSL_DTLS_MAX_BUFFERING,
04622                              (unsigned) hs->buffering.total_bytes_buffered ) );
04623                         goto exit;
04624                     }
04625                     else
04626                     {
04627                         MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffering of future message of size %u would exceed the compile-time limit %u (already %u bytes buffered) -- attempt to make space by freeing buffered future messages\n",
04628                              (unsigned) msg_len, MBEDTLS_SSL_DTLS_MAX_BUFFERING,
04629                              (unsigned) hs->buffering.total_bytes_buffered ) );
04630                     }
04631 
04632                     if( ssl_buffer_make_space( ssl, reassembly_buf_sz ) != 0 )
04633                     {
04634                         MBEDTLS_SSL_DEBUG_MSG( 2, ( "Reassembly of next message of size %u (%u with bitmap) would exceed the compile-time limit %u (already %u bytes buffered) -- fail\n",
04635                              (unsigned) msg_len,
04636                              (unsigned) reassembly_buf_sz,
04637                              MBEDTLS_SSL_DTLS_MAX_BUFFERING,
04638                              (unsigned) hs->buffering.total_bytes_buffered ) );
04639                         ret = MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
04640                         goto exit;
04641                     }
04642                 }
04643 
04644                 MBEDTLS_SSL_DEBUG_MSG( 2, ( "initialize reassembly, total length = %d",
04645                                             msg_len ) );
04646 
04647                 hs_buf->data = mbedtls_calloc( 1, reassembly_buf_sz );
04648                 if( hs_buf->data == NULL )
04649                 {
04650                     ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
04651                     goto exit;
04652                 }
04653                 hs_buf->data_len = reassembly_buf_sz;
04654 
04655                 /* Prepare final header: copy msg_type, length and message_seq,
04656                  * then add standardised fragment_offset and fragment_length */
04657                 memcpy( hs_buf->data, ssl->in_msg, 6 );
04658                 memset( hs_buf->data + 6, 0, 3 );
04659                 memcpy( hs_buf->data + 9, hs_buf->data + 1, 3 );
04660 
04661                 hs_buf->is_valid = 1;
04662 
04663                 hs->buffering.total_bytes_buffered += reassembly_buf_sz;
04664             }
04665             else
04666             {
04667                 /* Make sure msg_type and length are consistent */
04668                 if( memcmp( hs_buf->data, ssl->in_msg, 4 ) != 0 )
04669                 {
04670                     MBEDTLS_SSL_DEBUG_MSG( 1, ( "Fragment header mismatch - ignore" ) );
04671                     /* Ignore */
04672                     goto exit;
04673                 }
04674             }
04675 
04676             if( !hs_buf->is_complete )
04677             {
04678                 size_t frag_len, frag_off;
04679                 unsigned char * const msg = hs_buf->data + 12;
04680 
04681                 /*
04682                  * Check and copy current fragment
04683                  */
04684 
04685                 /* Validation of header fields already done in
04686                  * mbedtls_ssl_prepare_handshake_record(). */
04687                 frag_off = ssl_get_hs_frag_off( ssl );
04688                 frag_len = ssl_get_hs_frag_len( ssl );
04689 
04690                 MBEDTLS_SSL_DEBUG_MSG( 2, ( "adding fragment, offset = %d, length = %d",
04691                                             frag_off, frag_len ) );
04692                 memcpy( msg + frag_off, ssl->in_msg + 12, frag_len );
04693 
04694                 if( hs_buf->is_fragmented )
04695                 {
04696                     unsigned char * const bitmask = msg + msg_len;
04697                     ssl_bitmask_set( bitmask, frag_off, frag_len );
04698                     hs_buf->is_complete = ( ssl_bitmask_check( bitmask,
04699                                                                msg_len ) == 0 );
04700                 }
04701                 else
04702                 {
04703                     hs_buf->is_complete = 1;
04704                 }
04705 
04706                 MBEDTLS_SSL_DEBUG_MSG( 2, ( "message %scomplete",
04707                                    hs_buf->is_complete ? "" : "not yet " ) );
04708             }
04709 
04710             break;
04711         }
04712 
04713         default:
04714             /* We don't buffer other types of messages. */
04715             break;
04716     }
04717 
04718 exit:
04719 
04720     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= ssl_buffer_message" ) );
04721     return( ret );
04722 }
04723 #endif /* MBEDTLS_SSL_PROTO_DTLS */
04724 
04725 static int ssl_consume_current_message( mbedtls_ssl_context *ssl )
04726 {
04727     /*
04728      * Consume last content-layer message and potentially
04729      * update in_msglen which keeps track of the contents'
04730      * consumption state.
04731      *
04732      * (1) Handshake messages:
04733      *     Remove last handshake message, move content
04734      *     and adapt in_msglen.
04735      *
04736      * (2) Alert messages:
04737      *     Consume whole record content, in_msglen = 0.
04738      *
04739      * (3) Change cipher spec:
04740      *     Consume whole record content, in_msglen = 0.
04741      *
04742      * (4) Application data:
04743      *     Don't do anything - the record layer provides
04744      *     the application data as a stream transport
04745      *     and consumes through mbedtls_ssl_read only.
04746      *
04747      */
04748 
04749     /* Case (1): Handshake messages */
04750     if( ssl->in_hslen != 0 )
04751     {
04752         /* Hard assertion to be sure that no application data
04753          * is in flight, as corrupting ssl->in_msglen during
04754          * ssl->in_offt != NULL is fatal. */
04755         if( ssl->in_offt != NULL )
04756         {
04757             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
04758             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
04759         }
04760 
04761         /*
04762          * Get next Handshake message in the current record
04763          */
04764 
04765         /* Notes:
04766          * (1) in_hslen is not necessarily the size of the
04767          *     current handshake content: If DTLS handshake
04768          *     fragmentation is used, that's the fragment
04769          *     size instead. Using the total handshake message
04770          *     size here is faulty and should be changed at
04771          *     some point.
04772          * (2) While it doesn't seem to cause problems, one
04773          *     has to be very careful not to assume that in_hslen
04774          *     is always <= in_msglen in a sensible communication.
04775          *     Again, it's wrong for DTLS handshake fragmentation.
04776          *     The following check is therefore mandatory, and
04777          *     should not be treated as a silently corrected assertion.
04778          *     Additionally, ssl->in_hslen might be arbitrarily out of
04779          *     bounds after handling a DTLS message with an unexpected
04780          *     sequence number, see mbedtls_ssl_prepare_handshake_record.
04781          */
04782         if( ssl->in_hslen < ssl->in_msglen )
04783         {
04784             ssl->in_msglen -= ssl->in_hslen;
04785             memmove( ssl->in_msg, ssl->in_msg + ssl->in_hslen,
04786                      ssl->in_msglen );
04787 
04788             MBEDTLS_SSL_DEBUG_BUF( 4, "remaining content in record",
04789                                    ssl->in_msg, ssl->in_msglen );
04790         }
04791         else
04792         {
04793             ssl->in_msglen = 0;
04794         }
04795 
04796         ssl->in_hslen   = 0;
04797     }
04798     /* Case (4): Application data */
04799     else if( ssl->in_offt != NULL )
04800     {
04801         return( 0 );
04802     }
04803     /* Everything else (CCS & Alerts) */
04804     else
04805     {
04806         ssl->in_msglen = 0;
04807     }
04808 
04809     return( 0 );
04810 }
04811 
04812 static int ssl_record_is_in_progress( mbedtls_ssl_context *ssl )
04813 {
04814     if( ssl->in_msglen > 0 )
04815         return( 1 );
04816 
04817     return( 0 );
04818 }
04819 
04820 #if defined(MBEDTLS_SSL_PROTO_DTLS)
04821 
04822 static void ssl_free_buffered_record( mbedtls_ssl_context *ssl )
04823 {
04824     mbedtls_ssl_handshake_params * const hs = ssl->handshake;
04825     if( hs == NULL )
04826         return;
04827 
04828     if( hs->buffering.future_record.data != NULL )
04829     {
04830         hs->buffering.total_bytes_buffered -=
04831             hs->buffering.future_record.len;
04832 
04833         mbedtls_free( hs->buffering.future_record.data );
04834         hs->buffering.future_record.data = NULL;
04835     }
04836 }
04837 
04838 static int ssl_load_buffered_record( mbedtls_ssl_context *ssl )
04839 {
04840     mbedtls_ssl_handshake_params * const hs = ssl->handshake;
04841     unsigned char * rec;
04842     size_t rec_len;
04843     unsigned rec_epoch;
04844 
04845     if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM )
04846         return( 0 );
04847 
04848     if( hs == NULL )
04849         return( 0 );
04850 
04851     rec       = hs->buffering.future_record.data;
04852     rec_len   = hs->buffering.future_record.len;
04853     rec_epoch = hs->buffering.future_record.epoch;
04854 
04855     if( rec == NULL )
04856         return( 0 );
04857 
04858     /* Only consider loading future records if the
04859      * input buffer is empty. */
04860     if( ssl_next_record_is_in_datagram( ssl ) == 1 )
04861         return( 0 );
04862 
04863     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> ssl_load_buffered_record" ) );
04864 
04865     if( rec_epoch != ssl->in_epoch )
04866     {
04867         MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffered record not from current epoch." ) );
04868         goto exit;
04869     }
04870 
04871     MBEDTLS_SSL_DEBUG_MSG( 2, ( "Found buffered record from current epoch - load" ) );
04872 
04873     /* Double-check that the record is not too large */
04874     if( rec_len > MBEDTLS_SSL_IN_BUFFER_LEN -
04875         (size_t)( ssl->in_hdr - ssl->in_buf ) )
04876     {
04877         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
04878         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
04879     }
04880 
04881     memcpy( ssl->in_hdr, rec, rec_len );
04882     ssl->in_left = rec_len;
04883     ssl->next_record_offset = 0;
04884 
04885     ssl_free_buffered_record( ssl );
04886 
04887 exit:
04888     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= ssl_load_buffered_record" ) );
04889     return( 0 );
04890 }
04891 
04892 static int ssl_buffer_future_record( mbedtls_ssl_context *ssl )
04893 {
04894     mbedtls_ssl_handshake_params * const hs = ssl->handshake;
04895     size_t const rec_hdr_len = 13;
04896     size_t const total_buf_sz = rec_hdr_len + ssl->in_msglen;
04897 
04898     /* Don't buffer future records outside handshakes. */
04899     if( hs == NULL )
04900         return( 0 );
04901 
04902     /* Only buffer handshake records (we are only interested
04903      * in Finished messages). */
04904     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
04905         return( 0 );
04906 
04907     /* Don't buffer more than one future epoch record. */
04908     if( hs->buffering.future_record.data != NULL )
04909         return( 0 );
04910 
04911     /* Don't buffer record if there's not enough buffering space remaining. */
04912     if( total_buf_sz > ( MBEDTLS_SSL_DTLS_MAX_BUFFERING -
04913                          hs->buffering.total_bytes_buffered ) )
04914     {
04915         MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffering of future epoch record of size %u would exceed the compile-time limit %u (already %u bytes buffered) -- ignore\n",
04916                         (unsigned) total_buf_sz, MBEDTLS_SSL_DTLS_MAX_BUFFERING,
04917                         (unsigned) hs->buffering.total_bytes_buffered ) );
04918         return( 0 );
04919     }
04920 
04921     /* Buffer record */
04922     MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffer record from epoch %u",
04923                                 ssl->in_epoch + 1 ) );
04924     MBEDTLS_SSL_DEBUG_BUF( 3, "Buffered record", ssl->in_hdr,
04925                            rec_hdr_len + ssl->in_msglen );
04926 
04927     /* ssl_parse_record_header() only considers records
04928      * of the next epoch as candidates for buffering. */
04929     hs->buffering.future_record.epoch = ssl->in_epoch + 1;
04930     hs->buffering.future_record.len   = total_buf_sz;
04931 
04932     hs->buffering.future_record.data =
04933         mbedtls_calloc( 1, hs->buffering.future_record.len );
04934     if( hs->buffering.future_record.data == NULL )
04935     {
04936         /* If we run out of RAM trying to buffer a
04937          * record from the next epoch, just ignore. */
04938         return( 0 );
04939     }
04940 
04941     memcpy( hs->buffering.future_record.data, ssl->in_hdr, total_buf_sz );
04942 
04943     hs->buffering.total_bytes_buffered += total_buf_sz;
04944     return( 0 );
04945 }
04946 
04947 #endif /* MBEDTLS_SSL_PROTO_DTLS */
04948 
04949 static int ssl_get_next_record( mbedtls_ssl_context *ssl )
04950 {
04951     int ret;
04952 
04953 #if defined(MBEDTLS_SSL_PROTO_DTLS)
04954     /* We might have buffered a future record; if so,
04955      * and if the epoch matches now, load it.
04956      * On success, this call will set ssl->in_left to
04957      * the length of the buffered record, so that
04958      * the calls to ssl_fetch_input() below will
04959      * essentially be no-ops. */
04960     ret = ssl_load_buffered_record( ssl );
04961     if( ret != 0 )
04962         return( ret );
04963 #endif /* MBEDTLS_SSL_PROTO_DTLS */
04964 
04965     if( ( ret = mbedtls_ssl_fetch_input( ssl, mbedtls_ssl_hdr_len( ssl ) ) ) != 0 )
04966     {
04967         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret );
04968         return( ret );
04969     }
04970 
04971     if( ( ret = ssl_parse_record_header( ssl ) ) != 0 )
04972     {
04973 #if defined(MBEDTLS_SSL_PROTO_DTLS)
04974         if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
04975             ret != MBEDTLS_ERR_SSL_CLIENT_RECONNECT )
04976         {
04977             if( ret == MBEDTLS_ERR_SSL_EARLY_MESSAGE )
04978             {
04979                 ret = ssl_buffer_future_record( ssl );
04980                 if( ret != 0 )
04981                     return( ret );
04982 
04983                 /* Fall through to handling of unexpected records */
04984                 ret = MBEDTLS_ERR_SSL_UNEXPECTED_RECORD;
04985             }
04986 
04987             if( ret == MBEDTLS_ERR_SSL_UNEXPECTED_RECORD )
04988             {
04989                 /* Skip unexpected record (but not whole datagram) */
04990                 ssl->next_record_offset = ssl->in_msglen
04991                                         + mbedtls_ssl_hdr_len( ssl );
04992 
04993                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding unexpected record "
04994                                             "(header)" ) );
04995             }
04996             else
04997             {
04998                 /* Skip invalid record and the rest of the datagram */
04999                 ssl->next_record_offset = 0;
05000                 ssl->in_left = 0;
05001 
05002                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding invalid record "
05003                                             "(header)" ) );
05004             }
05005 
05006             /* Get next record */
05007             return( MBEDTLS_ERR_SSL_CONTINUE_PROCESSING );
05008         }
05009 #endif
05010         return( ret );
05011     }
05012 
05013     /*
05014      * Read and optionally decrypt the message contents
05015      */
05016     if( ( ret = mbedtls_ssl_fetch_input( ssl,
05017                                  mbedtls_ssl_hdr_len( ssl ) + ssl->in_msglen ) ) != 0 )
05018     {
05019         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret );
05020         return( ret );
05021     }
05022 
05023     /* Done reading this record, get ready for the next one */
05024 #if defined(MBEDTLS_SSL_PROTO_DTLS)
05025     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
05026     {
05027         ssl->next_record_offset = ssl->in_msglen + mbedtls_ssl_hdr_len( ssl );
05028         if( ssl->next_record_offset < ssl->in_left )
05029         {
05030             MBEDTLS_SSL_DEBUG_MSG( 3, ( "more than one record within datagram" ) );
05031         }
05032     }
05033     else
05034 #endif
05035         ssl->in_left = 0;
05036 
05037     if( ( ret = ssl_prepare_record_content( ssl ) ) != 0 )
05038     {
05039 #if defined(MBEDTLS_SSL_PROTO_DTLS)
05040         if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
05041         {
05042             /* Silently discard invalid records */
05043             if( ret == MBEDTLS_ERR_SSL_INVALID_RECORD ||
05044                 ret == MBEDTLS_ERR_SSL_INVALID_MAC )
05045             {
05046                 /* Except when waiting for Finished as a bad mac here
05047                  * probably means something went wrong in the handshake
05048                  * (eg wrong psk used, mitm downgrade attempt, etc.) */
05049                 if( ssl->state == MBEDTLS_SSL_CLIENT_FINISHED ||
05050                     ssl->state == MBEDTLS_SSL_SERVER_FINISHED )
05051                 {
05052 #if defined(MBEDTLS_SSL_ALL_ALERT_MESSAGES)
05053                     if( ret == MBEDTLS_ERR_SSL_INVALID_MAC )
05054                     {
05055                         mbedtls_ssl_send_alert_message( ssl,
05056                                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
05057                                 MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC );
05058                     }
05059 #endif
05060                     return( ret );
05061                 }
05062 
05063 #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT)
05064                 if( ssl->conf->badmac_limit != 0 &&
05065                     ++ssl->badmac_seen >= ssl->conf->badmac_limit )
05066                 {
05067                     MBEDTLS_SSL_DEBUG_MSG( 1, ( "too many records with bad MAC" ) );
05068                     return( MBEDTLS_ERR_SSL_INVALID_MAC );
05069                 }
05070 #endif
05071 
05072                 /* As above, invalid records cause
05073                  * dismissal of the whole datagram. */
05074 
05075                 ssl->next_record_offset = 0;
05076                 ssl->in_left = 0;
05077 
05078                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding invalid record (mac)" ) );
05079                 return( MBEDTLS_ERR_SSL_CONTINUE_PROCESSING );
05080             }
05081 
05082             return( ret );
05083         }
05084         else
05085 #endif
05086         {
05087             /* Error out (and send alert) on invalid records */
05088 #if defined(MBEDTLS_SSL_ALL_ALERT_MESSAGES)
05089             if( ret == MBEDTLS_ERR_SSL_INVALID_MAC )
05090             {
05091                 mbedtls_ssl_send_alert_message( ssl,
05092                         MBEDTLS_SSL_ALERT_LEVEL_FATAL,
05093                         MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC );
05094             }
05095 #endif
05096             return( ret );
05097         }
05098     }
05099 
05100     return( 0 );
05101 }
05102 
05103 int mbedtls_ssl_handle_message_type( mbedtls_ssl_context *ssl )
05104 {
05105     int ret;
05106 
05107     /*
05108      * Handle particular types of records
05109      */
05110     if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE )
05111     {
05112         if( ( ret = mbedtls_ssl_prepare_handshake_record( ssl ) ) != 0 )
05113         {
05114             return( ret );
05115         }
05116     }
05117 
05118     if( ssl->in_msgtype == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC )
05119     {
05120         if( ssl->in_msglen != 1 )
05121         {
05122             MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid CCS message, len: %d",
05123                            ssl->in_msglen ) );
05124             return( MBEDTLS_ERR_SSL_INVALID_RECORD );
05125         }
05126 
05127         if( ssl->in_msg[0] != 1 )
05128         {
05129             MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid CCS message, content: %02x",
05130                                         ssl->in_msg[0] ) );
05131             return( MBEDTLS_ERR_SSL_INVALID_RECORD );
05132         }
05133 
05134 #if defined(MBEDTLS_SSL_PROTO_DTLS)
05135         if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
05136             ssl->state != MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC    &&
05137             ssl->state != MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC )
05138         {
05139             if( ssl->handshake == NULL )
05140             {
05141                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "dropping ChangeCipherSpec outside handshake" ) );
05142                 return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD );
05143             }
05144 
05145             MBEDTLS_SSL_DEBUG_MSG( 1, ( "received out-of-order ChangeCipherSpec - remember" ) );
05146             return( MBEDTLS_ERR_SSL_EARLY_MESSAGE );
05147         }
05148 #endif
05149     }
05150 
05151     if( ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT )
05152     {
05153         if( ssl->in_msglen != 2 )
05154         {
05155             /* Note: Standard allows for more than one 2 byte alert
05156                to be packed in a single message, but Mbed TLS doesn't
05157                currently support this. */
05158             MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid alert message, len: %d",
05159                            ssl->in_msglen ) );
05160             return( MBEDTLS_ERR_SSL_INVALID_RECORD );
05161         }
05162 
05163         MBEDTLS_SSL_DEBUG_MSG( 2, ( "got an alert message, type: [%d:%d]",
05164                        ssl->in_msg[0], ssl->in_msg[1] ) );
05165 
05166         /*
05167          * Ignore non-fatal alerts, except close_notify and no_renegotiation
05168          */
05169         if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_FATAL )
05170         {
05171             MBEDTLS_SSL_DEBUG_MSG( 1, ( "is a fatal alert message (msg %d)",
05172                            ssl->in_msg[1] ) );
05173             return( MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE );
05174         }
05175 
05176         if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&
05177             ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY )
05178         {
05179             MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a close notify message" ) );
05180             return( MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY );
05181         }
05182 
05183 #if defined(MBEDTLS_SSL_RENEGOTIATION_ENABLED)
05184         if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&
05185             ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION )
05186         {
05187             MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a SSLv3 no renegotiation alert" ) );
05188             /* Will be handled when trying to parse ServerHello */
05189             return( 0 );
05190         }
05191 #endif
05192 
05193 #if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_SRV_C)
05194         if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 &&
05195             ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
05196             ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&
05197             ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_CERT )
05198         {
05199             MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a SSLv3 no_cert" ) );
05200             /* Will be handled in mbedtls_ssl_parse_certificate() */
05201             return( 0 );
05202         }
05203 #endif /* MBEDTLS_SSL_PROTO_SSL3 && MBEDTLS_SSL_SRV_C */
05204 
05205         /* Silently ignore: fetch new message */
05206         return MBEDTLS_ERR_SSL_NON_FATAL;
05207     }
05208 
05209 #if defined(MBEDTLS_SSL_PROTO_DTLS)
05210     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
05211         ssl->handshake != NULL &&
05212         ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER  )
05213     {
05214         ssl_handshake_wrapup_free_hs_transform( ssl );
05215     }
05216 #endif
05217 
05218     return( 0 );
05219 }
05220 
05221 int mbedtls_ssl_send_fatal_handshake_failure( mbedtls_ssl_context *ssl )
05222 {
05223     int ret;
05224 
05225     if( ( ret = mbedtls_ssl_send_alert_message( ssl,
05226                     MBEDTLS_SSL_ALERT_LEVEL_FATAL,
05227                     MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ) ) != 0 )
05228     {
05229         return( ret );
05230     }
05231 
05232     return( 0 );
05233 }
05234 
05235 int mbedtls_ssl_send_alert_message( mbedtls_ssl_context *ssl,
05236                             unsigned char level,
05237                             unsigned char message )
05238 {
05239     int ret;
05240 
05241     if( ssl == NULL || ssl->conf == NULL )
05242         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
05243 
05244     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> send alert message" ) );
05245     MBEDTLS_SSL_DEBUG_MSG( 3, ( "send alert level=%u message=%u", level, message ));
05246 
05247     ssl->out_msgtype = MBEDTLS_SSL_MSG_ALERT;
05248     ssl->out_msglen = 2;
05249     ssl->out_msg[0] = level;
05250     ssl->out_msg[1] = message;
05251 
05252     if( ( ret = mbedtls_ssl_write_record( ssl, SSL_FORCE_FLUSH ) ) != 0 )
05253     {
05254         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
05255         return( ret );
05256     }
05257     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= send alert message" ) );
05258 
05259     return( 0 );
05260 }
05261 
05262 /*
05263  * Handshake functions
05264  */
05265 #if !defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)         && \
05266     !defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)     && \
05267     !defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)     && \
05268     !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED)   && \
05269     !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) && \
05270     !defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED)    && \
05271     !defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
05272 /* No certificate support -> dummy functions */
05273 int mbedtls_ssl_write_certificate( mbedtls_ssl_context *ssl )
05274 {
05275     const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
05276 
05277     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate" ) );
05278 
05279     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
05280         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
05281         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
05282         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
05283     {
05284         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) );
05285         ssl->state++;
05286         return( 0 );
05287     }
05288 
05289     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
05290     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
05291 }
05292 
05293 int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl )
05294 {
05295     const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
05296 
05297     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) );
05298 
05299     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
05300         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
05301         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
05302         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
05303     {
05304         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
05305         ssl->state++;
05306         return( 0 );
05307     }
05308 
05309     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
05310     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
05311 }
05312 
05313 #else
05314 /* Some certificate support -> implement write and parse */
05315 
05316 int mbedtls_ssl_write_certificate( mbedtls_ssl_context *ssl )
05317 {
05318     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
05319     size_t i, n;
05320     const mbedtls_x509_crt *crt;
05321     const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
05322 
05323     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate" ) );
05324 
05325     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
05326         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
05327         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
05328         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
05329     {
05330         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) );
05331         ssl->state++;
05332         return( 0 );
05333     }
05334 
05335 #if defined(MBEDTLS_SSL_CLI_C)
05336     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
05337     {
05338         if( ssl->client_auth == 0 )
05339         {
05340             MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) );
05341             ssl->state++;
05342             return( 0 );
05343         }
05344 
05345 #if defined(MBEDTLS_SSL_PROTO_SSL3)
05346         /*
05347          * If using SSLv3 and got no cert, send an Alert message
05348          * (otherwise an empty Certificate message will be sent).
05349          */
05350         if( mbedtls_ssl_own_cert( ssl )  == NULL &&
05351             ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
05352         {
05353             ssl->out_msglen  = 2;
05354             ssl->out_msgtype = MBEDTLS_SSL_MSG_ALERT;
05355             ssl->out_msg[0]  = MBEDTLS_SSL_ALERT_LEVEL_WARNING;
05356             ssl->out_msg[1]  = MBEDTLS_SSL_ALERT_MSG_NO_CERT;
05357 
05358             MBEDTLS_SSL_DEBUG_MSG( 2, ( "got no certificate to send" ) );
05359             goto write_msg;
05360         }
05361 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
05362     }
05363 #endif /* MBEDTLS_SSL_CLI_C */
05364 #if defined(MBEDTLS_SSL_SRV_C)
05365     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
05366     {
05367         if( mbedtls_ssl_own_cert( ssl ) == NULL )
05368         {
05369             MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no certificate to send" ) );
05370             return( MBEDTLS_ERR_SSL_CERTIFICATE_REQUIRED );
05371         }
05372     }
05373 #endif
05374 
05375     MBEDTLS_SSL_DEBUG_CRT( 3, "own certificate", mbedtls_ssl_own_cert( ssl ) );
05376 
05377     /*
05378      *     0  .  0    handshake type
05379      *     1  .  3    handshake length
05380      *     4  .  6    length of all certs
05381      *     7  .  9    length of cert. 1
05382      *    10  . n-1   peer certificate
05383      *     n  . n+2   length of cert. 2
05384      *    n+3 . ...   upper level cert, etc.
05385      */
05386     i = 7;
05387     crt = mbedtls_ssl_own_cert( ssl );
05388 
05389     while( crt != NULL )
05390     {
05391         n = crt->raw.len;
05392         if( n > MBEDTLS_SSL_OUT_CONTENT_LEN - 3 - i )
05393         {
05394             MBEDTLS_SSL_DEBUG_MSG( 1, ( "certificate too large, %d > %d",
05395                            i + 3 + n, MBEDTLS_SSL_OUT_CONTENT_LEN ) );
05396             return( MBEDTLS_ERR_SSL_CERTIFICATE_TOO_LARGE );
05397         }
05398 
05399         ssl->out_msg[i    ] = (unsigned char)( n >> 16 );
05400         ssl->out_msg[i + 1] = (unsigned char)( n >>  8 );
05401         ssl->out_msg[i + 2] = (unsigned char)( n       );
05402 
05403         i += 3; memcpy( ssl->out_msg + i, crt->raw.p, n );
05404         i += n; crt = crt->next;
05405     }
05406 
05407     ssl->out_msg[4]  = (unsigned char)( ( i - 7 ) >> 16 );
05408     ssl->out_msg[5]  = (unsigned char)( ( i - 7 ) >>  8 );
05409     ssl->out_msg[6]  = (unsigned char)( ( i - 7 )       );
05410 
05411     ssl->out_msglen  = i;
05412     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
05413     ssl->out_msg[0]  = MBEDTLS_SSL_HS_CERTIFICATE;
05414 
05415 #if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_CLI_C)
05416 write_msg:
05417 #endif
05418 
05419     ssl->state++;
05420 
05421     if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
05422     {
05423         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
05424         return( ret );
05425     }
05426 
05427     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write certificate" ) );
05428 
05429     return( ret );
05430 }
05431 
05432 int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl )
05433 {
05434     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
05435     size_t i, n;
05436     const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
05437     int authmode = ssl->conf->authmode;
05438     uint8_t alert;
05439 
05440     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) );
05441 
05442     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
05443         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
05444         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
05445         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
05446     {
05447         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
05448         ssl->state++;
05449         return( 0 );
05450     }
05451 
05452 #if defined(MBEDTLS_SSL_SRV_C)
05453     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
05454         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
05455     {
05456         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
05457         ssl->state++;
05458         return( 0 );
05459     }
05460 
05461 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
05462     if( ssl->handshake->sni_authmode != MBEDTLS_SSL_VERIFY_UNSET )
05463         authmode = ssl->handshake->sni_authmode;
05464 #endif
05465 
05466     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
05467         authmode == MBEDTLS_SSL_VERIFY_NONE )
05468     {
05469         ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_SKIP_VERIFY;
05470         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
05471         ssl->state++;
05472         return( 0 );
05473     }
05474 #endif
05475 
05476     if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
05477     {
05478         /* mbedtls_ssl_read_record may have sent an alert already. We
05479            let it decide whether to alert. */
05480         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
05481         return( ret );
05482     }
05483 
05484     ssl->state++;
05485 
05486 #if defined(MBEDTLS_SSL_SRV_C)
05487 #if defined(MBEDTLS_SSL_PROTO_SSL3)
05488     /*
05489      * Check if the client sent an empty certificate
05490      */
05491     if( ssl->conf->endpoint  == MBEDTLS_SSL_IS_SERVER &&
05492         ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
05493     {
05494         if( ssl->in_msglen  == 2                        &&
05495             ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT            &&
05496             ssl->in_msg[0]  == MBEDTLS_SSL_ALERT_LEVEL_WARNING  &&
05497             ssl->in_msg[1]  == MBEDTLS_SSL_ALERT_MSG_NO_CERT )
05498         {
05499             MBEDTLS_SSL_DEBUG_MSG( 1, ( "SSLv3 client has no certificate" ) );
05500 
05501             /* The client was asked for a certificate but didn't send
05502                one. The client should know what's going on, so we
05503                don't send an alert. */
05504             ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_MISSING;
05505             if( authmode == MBEDTLS_SSL_VERIFY_OPTIONAL )
05506                 return( 0 );
05507             else
05508                 return( MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE );
05509         }
05510     }
05511 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
05512 
05513 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
05514     defined(MBEDTLS_SSL_PROTO_TLS1_2)
05515     if( ssl->conf->endpoint  == MBEDTLS_SSL_IS_SERVER &&
05516         ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_0 )
05517     {
05518         if( ssl->in_hslen   == 3 + mbedtls_ssl_hs_hdr_len( ssl ) &&
05519             ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE    &&
05520             ssl->in_msg[0]  == MBEDTLS_SSL_HS_CERTIFICATE   &&
05521             memcmp( ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ), "\0\0\0", 3 ) == 0 )
05522         {
05523             MBEDTLS_SSL_DEBUG_MSG( 1, ( "TLSv1 client has no certificate" ) );
05524 
05525             /* The client was asked for a certificate but didn't send
05526                one. The client should know what's going on, so we
05527                don't send an alert. */
05528             ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_MISSING;
05529             if( authmode == MBEDTLS_SSL_VERIFY_OPTIONAL )
05530                 return( 0 );
05531             else
05532                 return( MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE );
05533         }
05534     }
05535 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
05536           MBEDTLS_SSL_PROTO_TLS1_2 */
05537 #endif /* MBEDTLS_SSL_SRV_C */
05538 
05539     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
05540     {
05541         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
05542         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
05543                                         MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
05544         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
05545     }
05546 
05547     if( ssl->in_msg[0] != MBEDTLS_SSL_HS_CERTIFICATE ||
05548         ssl->in_hslen < mbedtls_ssl_hs_hdr_len( ssl ) + 3 + 3 )
05549     {
05550         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
05551         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
05552                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
05553         return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
05554     }
05555 
05556     i = mbedtls_ssl_hs_hdr_len( ssl );
05557 
05558     /*
05559      * Same message structure as in mbedtls_ssl_write_certificate()
05560      */
05561     n = ( ssl->in_msg[i+1] << 8 ) | ssl->in_msg[i+2];
05562 
05563     if( ssl->in_msg[i] != 0 ||
05564         ssl->in_hslen != n + 3 + mbedtls_ssl_hs_hdr_len( ssl ) )
05565     {
05566         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
05567         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
05568                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
05569         return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
05570     }
05571 
05572     /* In case we tried to reuse a session but it failed */
05573     if( ssl->session_negotiate->peer_cert != NULL )
05574     {
05575         mbedtls_x509_crt_free( ssl->session_negotiate->peer_cert );
05576         mbedtls_free( ssl->session_negotiate->peer_cert );
05577     }
05578 
05579     if( ( ssl->session_negotiate->peer_cert = mbedtls_calloc( 1,
05580                     sizeof( mbedtls_x509_crt ) ) ) == NULL )
05581     {
05582         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed",
05583                        sizeof( mbedtls_x509_crt ) ) );
05584         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
05585                                         MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
05586         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
05587     }
05588 
05589     mbedtls_x509_crt_init( ssl->session_negotiate->peer_cert );
05590 
05591     i += 3;
05592 
05593     while( i < ssl->in_hslen )
05594     {
05595         if ( i + 3 > ssl->in_hslen ) {
05596             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
05597             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
05598                                            MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
05599             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
05600         }
05601         if( ssl->in_msg[i] != 0 )
05602         {
05603             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
05604             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
05605                                             MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
05606             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
05607         }
05608 
05609         n = ( (unsigned int) ssl->in_msg[i + 1] << 8 )
05610             | (unsigned int) ssl->in_msg[i + 2];
05611         i += 3;
05612 
05613         if( n < 128 || i + n > ssl->in_hslen )
05614         {
05615             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
05616             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
05617                                             MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
05618             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
05619         }
05620 
05621         ret = mbedtls_x509_crt_parse_der( ssl->session_negotiate->peer_cert,
05622                                   ssl->in_msg + i, n );
05623         switch( ret )
05624         {
05625         case 0: /*ok*/
05626         case MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG + MBEDTLS_ERR_OID_NOT_FOUND:
05627             /* Ignore certificate with an unknown algorithm: maybe a
05628                prior certificate was already trusted. */
05629             break;
05630 
05631         case MBEDTLS_ERR_X509_ALLOC_FAILED:
05632             alert = MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR;
05633             goto crt_parse_der_failed;
05634 
05635         case MBEDTLS_ERR_X509_UNKNOWN_VERSION:
05636             alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
05637             goto crt_parse_der_failed;
05638 
05639         default:
05640             alert = MBEDTLS_SSL_ALERT_MSG_BAD_CERT;
05641         crt_parse_der_failed:
05642             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, alert );
05643             MBEDTLS_SSL_DEBUG_RET( 1, " mbedtls_x509_crt_parse_der", ret );
05644             return( ret );
05645         }
05646 
05647         i += n;
05648     }
05649 
05650     MBEDTLS_SSL_DEBUG_CRT( 3, "peer certificate", ssl->session_negotiate->peer_cert );
05651 
05652     /*
05653      * On client, make sure the server cert doesn't change during renego to
05654      * avoid "triple handshake" attack: https://secure-resumption.com/
05655      */
05656 #if defined(MBEDTLS_SSL_RENEGOTIATION) && defined(MBEDTLS_SSL_CLI_C)
05657     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&
05658         ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
05659     {
05660         if( ssl->session->peer_cert == NULL )
05661         {
05662             MBEDTLS_SSL_DEBUG_MSG( 1, ( "new server cert during renegotiation" ) );
05663             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
05664                                             MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED );
05665             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
05666         }
05667 
05668         if( ssl->session->peer_cert->raw.len !=
05669             ssl->session_negotiate->peer_cert->raw.len ||
05670             memcmp( ssl->session->peer_cert->raw.p,
05671                     ssl->session_negotiate->peer_cert->raw.p,
05672                     ssl->session->peer_cert->raw.len ) != 0 )
05673         {
05674             MBEDTLS_SSL_DEBUG_MSG( 1, ( "server cert changed during renegotiation" ) );
05675             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
05676                                             MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED );
05677             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
05678         }
05679     }
05680 #endif /* MBEDTLS_SSL_RENEGOTIATION && MBEDTLS_SSL_CLI_C */
05681 
05682     if( authmode != MBEDTLS_SSL_VERIFY_NONE )
05683     {
05684         mbedtls_x509_crt *ca_chain;
05685         mbedtls_x509_crl *ca_crl;
05686 
05687 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
05688         if( ssl->handshake->sni_ca_chain != NULL )
05689         {
05690             ca_chain = ssl->handshake->sni_ca_chain;
05691             ca_crl   = ssl->handshake->sni_ca_crl;
05692         }
05693         else
05694 #endif
05695         {
05696             ca_chain = ssl->conf->ca_chain;
05697             ca_crl   = ssl->conf->ca_crl;
05698         }
05699 
05700         /*
05701          * Main check: verify certificate
05702          */
05703         ret = mbedtls_x509_crt_verify_with_profile(
05704                                 ssl->session_negotiate->peer_cert,
05705                                 ca_chain, ca_crl,
05706                                 ssl->conf->cert_profile,
05707                                 ssl->hostname,
05708                                &ssl->session_negotiate->verify_result,
05709                                 ssl->conf->f_vrfy, ssl->conf->p_vrfy );
05710 
05711         if( ret != 0 )
05712         {
05713             MBEDTLS_SSL_DEBUG_RET( 1, "x509_verify_cert", ret );
05714         }
05715 
05716         /*
05717          * Secondary checks: always done, but change 'ret' only if it was 0
05718          */
05719 
05720 #if defined(MBEDTLS_ECP_C)
05721         {
05722             const mbedtls_pk_context *pk = &ssl->session_negotiate->peer_cert->pk;
05723 
05724             /* If certificate uses an EC key, make sure the curve is OK */
05725             if( mbedtls_pk_can_do( pk, MBEDTLS_PK_ECKEY ) &&
05726                 mbedtls_ssl_check_curve( ssl, mbedtls_pk_ec( *pk )->grp .id  ) != 0 )
05727             {
05728                 ssl->session_negotiate->verify_result |= MBEDTLS_X509_BADCERT_BAD_KEY;
05729 
05730                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate (EC key curve)" ) );
05731                 if( ret == 0 )
05732                     ret = MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE;
05733             }
05734         }
05735 #endif /* MBEDTLS_ECP_C */
05736 
05737         if( mbedtls_ssl_check_cert_usage( ssl->session_negotiate->peer_cert,
05738                                  ciphersuite_info,
05739                                  ! ssl->conf->endpoint,
05740                                  &ssl->session_negotiate->verify_result ) != 0 )
05741         {
05742             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate (usage extensions)" ) );
05743             if( ret == 0 )
05744                 ret = MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE;
05745         }
05746 
05747         /* mbedtls_x509_crt_verify_with_profile is supposed to report a
05748          * verification failure through MBEDTLS_ERR_X509_CERT_VERIFY_FAILED,
05749          * with details encoded in the verification flags. All other kinds
05750          * of error codes, including those from the user provided f_vrfy
05751          * functions, are treated as fatal and lead to a failure of
05752          * ssl_parse_certificate even if verification was optional. */
05753         if( authmode == MBEDTLS_SSL_VERIFY_OPTIONAL &&
05754             ( ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED ||
05755               ret == MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE ) )
05756         {
05757             ret = 0;
05758         }
05759 
05760         if( ca_chain == NULL && authmode == MBEDTLS_SSL_VERIFY_REQUIRED )
05761         {
05762             MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no CA chain" ) );
05763             ret = MBEDTLS_ERR_SSL_CA_CHAIN_REQUIRED;
05764         }
05765 
05766         if( ret != 0 )
05767         {
05768             /* The certificate may have been rejected for several reasons.
05769                Pick one and send the corresponding alert. Which alert to send
05770                may be a subject of debate in some cases. */
05771             if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_OTHER )
05772                 alert = MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED;
05773             else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_CN_MISMATCH )
05774                 alert = MBEDTLS_SSL_ALERT_MSG_BAD_CERT;
05775             else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_KEY_USAGE )
05776                 alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
05777             else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_EXT_KEY_USAGE )
05778                 alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
05779             else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_NS_CERT_TYPE )
05780                 alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
05781             else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_BAD_PK )
05782                 alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
05783             else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_BAD_KEY )
05784                 alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
05785             else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_EXPIRED )
05786                 alert = MBEDTLS_SSL_ALERT_MSG_CERT_EXPIRED;
05787             else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_REVOKED )
05788                 alert = MBEDTLS_SSL_ALERT_MSG_CERT_REVOKED;
05789             else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_NOT_TRUSTED )
05790                 alert = MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA;
05791             else
05792                 alert = MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN;
05793             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
05794                                             alert );
05795         }
05796 
05797 #if defined(MBEDTLS_DEBUG_C)
05798         if( ssl->session_negotiate->verify_result != 0 )
05799         {
05800             MBEDTLS_SSL_DEBUG_MSG( 3, ( "! Certificate verification flags %x",
05801                                         ssl->session_negotiate->verify_result ) );
05802         }
05803         else
05804         {
05805             MBEDTLS_SSL_DEBUG_MSG( 3, ( "Certificate verification flags clear" ) );
05806         }
05807 #endif /* MBEDTLS_DEBUG_C */
05808     }
05809 
05810     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse certificate" ) );
05811 
05812     return( ret );
05813 }
05814 #endif /* !MBEDTLS_KEY_EXCHANGE_RSA_ENABLED
05815           !MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED
05816           !MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED
05817           !MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED
05818           !MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
05819           !MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED
05820           !MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
05821 
05822 int mbedtls_ssl_write_change_cipher_spec( mbedtls_ssl_context *ssl )
05823 {
05824     int ret;
05825 
05826     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write change cipher spec" ) );
05827 
05828     ssl->out_msgtype = MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC;
05829     ssl->out_msglen  = 1;
05830     ssl->out_msg[0]  = 1;
05831 
05832     ssl->state++;
05833 
05834     if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
05835     {
05836         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
05837         return( ret );
05838     }
05839 
05840     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write change cipher spec" ) );
05841 
05842     return( 0 );
05843 }
05844 
05845 int mbedtls_ssl_parse_change_cipher_spec( mbedtls_ssl_context *ssl )
05846 {
05847     int ret;
05848 
05849     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse change cipher spec" ) );
05850 
05851     if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
05852     {
05853         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
05854         return( ret );
05855     }
05856 
05857     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC )
05858     {
05859         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad change cipher spec message" ) );
05860         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
05861                                         MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
05862         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
05863     }
05864 
05865     /* CCS records are only accepted if they have length 1 and content '1',
05866      * so we don't need to check this here. */
05867 
05868     /*
05869      * Switch to our negotiated transform and session parameters for inbound
05870      * data.
05871      */
05872     MBEDTLS_SSL_DEBUG_MSG( 3, ( "switching to new transform spec for inbound data" ) );
05873     ssl->transform_in = ssl->transform_negotiate;
05874     ssl->session_in = ssl->session_negotiate;
05875 
05876 #if defined(MBEDTLS_SSL_PROTO_DTLS)
05877     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
05878     {
05879 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
05880         ssl_dtls_replay_reset( ssl );
05881 #endif
05882 
05883         /* Increment epoch */
05884         if( ++ssl->in_epoch == 0 )
05885         {
05886             MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS epoch would wrap" ) );
05887             /* This is highly unlikely to happen for legitimate reasons, so
05888                treat it as an attack and don't send an alert. */
05889             return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
05890         }
05891     }
05892     else
05893 #endif /* MBEDTLS_SSL_PROTO_DTLS */
05894     memset( ssl->in_ctr, 0, 8 );
05895 
05896     ssl_update_in_pointers( ssl, ssl->transform_negotiate );
05897 
05898 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
05899     if( mbedtls_ssl_hw_record_activate != NULL )
05900     {
05901         if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_INBOUND ) ) != 0 )
05902         {
05903             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret );
05904             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
05905                                             MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
05906             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
05907         }
05908     }
05909 #endif
05910 
05911     ssl->state++;
05912 
05913     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse change cipher spec" ) );
05914 
05915     return( 0 );
05916 }
05917 
05918 void mbedtls_ssl_optimize_checksum( mbedtls_ssl_context *ssl,
05919                             const mbedtls_ssl_ciphersuite_t *ciphersuite_info )
05920 {
05921     ((void) ciphersuite_info);
05922 
05923 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
05924     defined(MBEDTLS_SSL_PROTO_TLS1_1)
05925     if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 )
05926         ssl->handshake->update_checksum = ssl_update_checksum_md5sha1;
05927     else
05928 #endif
05929 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
05930 #if defined(MBEDTLS_SHA512_C)
05931     if( ciphersuite_info->mac == MBEDTLS_MD_SHA384 )
05932         ssl->handshake->update_checksum = ssl_update_checksum_sha384;
05933     else
05934 #endif
05935 #if defined(MBEDTLS_SHA256_C)
05936     if( ciphersuite_info->mac != MBEDTLS_MD_SHA384 )
05937         ssl->handshake->update_checksum = ssl_update_checksum_sha256;
05938     else
05939 #endif
05940 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
05941     {
05942         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
05943         return;
05944     }
05945 }
05946 
05947 void mbedtls_ssl_reset_checksum( mbedtls_ssl_context *ssl )
05948 {
05949 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
05950     defined(MBEDTLS_SSL_PROTO_TLS1_1)
05951      mbedtls_md5_starts_ret( &ssl->handshake->fin_md5  );
05952     mbedtls_sha1_starts_ret( &ssl->handshake->fin_sha1 );
05953 #endif
05954 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
05955 #if defined(MBEDTLS_SHA256_C)
05956     mbedtls_sha256_starts_ret( &ssl->handshake->fin_sha256, 0 );
05957 #endif
05958 #if defined(MBEDTLS_SHA512_C)
05959     mbedtls_sha512_starts_ret( &ssl->handshake->fin_sha512, 1 );
05960 #endif
05961 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
05962 }
05963 
05964 static void ssl_update_checksum_start( mbedtls_ssl_context *ssl,
05965                                        const unsigned char *buf, size_t len )
05966 {
05967 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
05968     defined(MBEDTLS_SSL_PROTO_TLS1_1)
05969      mbedtls_md5_update_ret( &ssl->handshake->fin_md5 , buf, len );
05970     mbedtls_sha1_update_ret( &ssl->handshake->fin_sha1, buf, len );
05971 #endif
05972 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
05973 #if defined(MBEDTLS_SHA256_C)
05974     mbedtls_sha256_update_ret( &ssl->handshake->fin_sha256, buf, len );
05975 #endif
05976 #if defined(MBEDTLS_SHA512_C)
05977     mbedtls_sha512_update_ret( &ssl->handshake->fin_sha512, buf, len );
05978 #endif
05979 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
05980 }
05981 
05982 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
05983     defined(MBEDTLS_SSL_PROTO_TLS1_1)
05984 static void ssl_update_checksum_md5sha1( mbedtls_ssl_context *ssl,
05985                                          const unsigned char *buf, size_t len )
05986 {
05987      mbedtls_md5_update_ret( &ssl->handshake->fin_md5 , buf, len );
05988     mbedtls_sha1_update_ret( &ssl->handshake->fin_sha1, buf, len );
05989 }
05990 #endif
05991 
05992 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
05993 #if defined(MBEDTLS_SHA256_C)
05994 static void ssl_update_checksum_sha256( mbedtls_ssl_context *ssl,
05995                                         const unsigned char *buf, size_t len )
05996 {
05997     mbedtls_sha256_update_ret( &ssl->handshake->fin_sha256, buf, len );
05998 }
05999 #endif
06000 
06001 #if defined(MBEDTLS_SHA512_C)
06002 static void ssl_update_checksum_sha384( mbedtls_ssl_context *ssl,
06003                                         const unsigned char *buf, size_t len )
06004 {
06005     mbedtls_sha512_update_ret( &ssl->handshake->fin_sha512, buf, len );
06006 }
06007 #endif
06008 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
06009 
06010 #if defined(MBEDTLS_SSL_PROTO_SSL3)
06011 static void ssl_calc_finished_ssl(
06012                 mbedtls_ssl_context *ssl, unsigned char *buf, int from )
06013 {
06014     const char *sender;
06015     mbedtls_md5_context  md5;
06016     mbedtls_sha1_context sha1;
06017 
06018     unsigned char padbuf[48];
06019     unsigned char md5sum[16];
06020     unsigned char sha1sum[20];
06021 
06022     mbedtls_ssl_session *session = ssl->session_negotiate;
06023     if( !session )
06024         session = ssl->session;
06025 
06026     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc  finished ssl" ) );
06027 
06028     mbedtls_md5_init( &md5 );
06029     mbedtls_sha1_init( &sha1 );
06030 
06031     mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
06032     mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
06033 
06034     /*
06035      * SSLv3:
06036      *   hash =
06037      *      MD5( master + pad2 +
06038      *          MD5( handshake + sender + master + pad1 ) )
06039      *   + SHA1( master + pad2 +
06040      *         SHA1( handshake + sender + master + pad1 ) )
06041      */
06042 
06043 #if !defined(MBEDTLS_MD5_ALT)
06044     MBEDTLS_SSL_DEBUG_BUF( 4, "finished  md5 state", (unsigned char *)
06045                     md5.state , sizeof(  md5.state  ) );
06046 #endif
06047 
06048 #if !defined(MBEDTLS_SHA1_ALT)
06049     MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha1 state", (unsigned char *)
06050                    sha1.state , sizeof( sha1.state  ) );
06051 #endif
06052 
06053     sender = ( from == MBEDTLS_SSL_IS_CLIENT ) ? "CLNT"
06054                                        : "SRVR";
06055 
06056     memset( padbuf, 0x36, 48 );
06057 
06058     mbedtls_md5_update_ret( &md5, (const unsigned char *) sender, 4 );
06059     mbedtls_md5_update_ret( &md5, session->master, 48 );
06060     mbedtls_md5_update_ret( &md5, padbuf, 48 );
06061     mbedtls_md5_finish_ret( &md5, md5sum );
06062 
06063     mbedtls_sha1_update_ret( &sha1, (const unsigned char *) sender, 4 );
06064     mbedtls_sha1_update_ret( &sha1, session->master, 48 );
06065     mbedtls_sha1_update_ret( &sha1, padbuf, 40 );
06066     mbedtls_sha1_finish_ret( &sha1, sha1sum );
06067 
06068     memset( padbuf, 0x5C, 48 );
06069 
06070     mbedtls_md5_starts_ret( &md5 );
06071     mbedtls_md5_update_ret( &md5, session->master, 48 );
06072     mbedtls_md5_update_ret( &md5, padbuf, 48 );
06073     mbedtls_md5_update_ret( &md5, md5sum, 16 );
06074     mbedtls_md5_finish_ret( &md5, buf );
06075 
06076     mbedtls_sha1_starts_ret( &sha1 );
06077     mbedtls_sha1_update_ret( &sha1, session->master, 48 );
06078     mbedtls_sha1_update_ret( &sha1, padbuf , 40 );
06079     mbedtls_sha1_update_ret( &sha1, sha1sum, 20 );
06080     mbedtls_sha1_finish_ret( &sha1, buf + 16 );
06081 
06082     MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, 36 );
06083 
06084     mbedtls_md5_free(  &md5  );
06085     mbedtls_sha1_free( &sha1 );
06086 
06087     mbedtls_platform_zeroize(  padbuf, sizeof(  padbuf ) );
06088     mbedtls_platform_zeroize(  md5sum, sizeof(  md5sum ) );
06089     mbedtls_platform_zeroize( sha1sum, sizeof( sha1sum ) );
06090 
06091     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc  finished" ) );
06092 }
06093 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
06094 
06095 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
06096 static void ssl_calc_finished_tls(
06097                 mbedtls_ssl_context *ssl, unsigned char *buf, int from )
06098 {
06099     int len = 12;
06100     const char *sender;
06101     mbedtls_md5_context  md5;
06102     mbedtls_sha1_context sha1;
06103     unsigned char padbuf[36];
06104 
06105     mbedtls_ssl_session *session = ssl->session_negotiate;
06106     if( !session )
06107         session = ssl->session;
06108 
06109     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc  finished tls" ) );
06110 
06111     mbedtls_md5_init( &md5 );
06112     mbedtls_sha1_init( &sha1 );
06113 
06114     mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
06115     mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
06116 
06117     /*
06118      * TLSv1:
06119      *   hash = PRF( master, finished_label,
06120      *               MD5( handshake ) + SHA1( handshake ) )[0..11]
06121      */
06122 
06123 #if !defined(MBEDTLS_MD5_ALT)
06124     MBEDTLS_SSL_DEBUG_BUF( 4, "finished  md5 state", (unsigned char *)
06125                     md5.state , sizeof(  md5.state  ) );
06126 #endif
06127 
06128 #if !defined(MBEDTLS_SHA1_ALT)
06129     MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha1 state", (unsigned char *)
06130                    sha1.state , sizeof( sha1.state  ) );
06131 #endif
06132 
06133     sender = ( from == MBEDTLS_SSL_IS_CLIENT )
06134              ? "client finished"
06135              : "server finished";
06136 
06137     mbedtls_md5_finish_ret(  &md5, padbuf );
06138     mbedtls_sha1_finish_ret( &sha1, padbuf + 16 );
06139 
06140     ssl->handshake->tls_prf( session->master, 48, sender,
06141                              padbuf, 36, buf, len );
06142 
06143     MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len );
06144 
06145     mbedtls_md5_free(  &md5  );
06146     mbedtls_sha1_free( &sha1 );
06147 
06148     mbedtls_platform_zeroize(  padbuf, sizeof(  padbuf ) );
06149 
06150     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc  finished" ) );
06151 }
06152 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
06153 
06154 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
06155 #if defined(MBEDTLS_SHA256_C)
06156 static void ssl_calc_finished_tls_sha256(
06157                 mbedtls_ssl_context *ssl, unsigned char *buf, int from )
06158 {
06159     int len = 12;
06160     const char *sender;
06161     mbedtls_sha256_context sha256;
06162     unsigned char padbuf[32];
06163 
06164     mbedtls_ssl_session *session = ssl->session_negotiate;
06165     if( !session )
06166         session = ssl->session;
06167 
06168     mbedtls_sha256_init( &sha256 );
06169 
06170     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc  finished tls sha256" ) );
06171 
06172     mbedtls_sha256_clone( &sha256, &ssl->handshake->fin_sha256 );
06173 
06174     /*
06175      * TLSv1.2:
06176      *   hash = PRF( master, finished_label,
06177      *               Hash( handshake ) )[0.11]
06178      */
06179 
06180 #if !defined(MBEDTLS_SHA256_ALT)
06181     MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha2 state", (unsigned char *)
06182                    sha256.state , sizeof( sha256.state  ) );
06183 #endif
06184 
06185     sender = ( from == MBEDTLS_SSL_IS_CLIENT )
06186              ? "client finished"
06187              : "server finished";
06188 
06189     mbedtls_sha256_finish_ret( &sha256, padbuf );
06190 
06191     ssl->handshake->tls_prf( session->master, 48, sender,
06192                              padbuf, 32, buf, len );
06193 
06194     MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len );
06195 
06196     mbedtls_sha256_free( &sha256 );
06197 
06198     mbedtls_platform_zeroize(  padbuf, sizeof(  padbuf ) );
06199 
06200     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc  finished" ) );
06201 }
06202 #endif /* MBEDTLS_SHA256_C */
06203 
06204 #if defined(MBEDTLS_SHA512_C)
06205 static void ssl_calc_finished_tls_sha384(
06206                 mbedtls_ssl_context *ssl, unsigned char *buf, int from )
06207 {
06208     int len = 12;
06209     const char *sender;
06210     mbedtls_sha512_context sha512;
06211     unsigned char padbuf[48];
06212 
06213     mbedtls_ssl_session *session = ssl->session_negotiate;
06214     if( !session )
06215         session = ssl->session;
06216 
06217     mbedtls_sha512_init( &sha512 );
06218 
06219     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc  finished tls sha384" ) );
06220 
06221     mbedtls_sha512_clone( &sha512, &ssl->handshake->fin_sha512 );
06222 
06223     /*
06224      * TLSv1.2:
06225      *   hash = PRF( master, finished_label,
06226      *               Hash( handshake ) )[0.11]
06227      */
06228 
06229 #if !defined(MBEDTLS_SHA512_ALT)
06230     MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha512 state", (unsigned char *)
06231                    sha512.state , sizeof( sha512.state  ) );
06232 #endif
06233 
06234     sender = ( from == MBEDTLS_SSL_IS_CLIENT )
06235              ? "client finished"
06236              : "server finished";
06237 
06238     mbedtls_sha512_finish_ret( &sha512, padbuf );
06239 
06240     ssl->handshake->tls_prf( session->master, 48, sender,
06241                              padbuf, 48, buf, len );
06242 
06243     MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len );
06244 
06245     mbedtls_sha512_free( &sha512 );
06246 
06247     mbedtls_platform_zeroize(  padbuf, sizeof( padbuf ) );
06248 
06249     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc  finished" ) );
06250 }
06251 #endif /* MBEDTLS_SHA512_C */
06252 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
06253 
06254 static void ssl_handshake_wrapup_free_hs_transform( mbedtls_ssl_context *ssl )
06255 {
06256     MBEDTLS_SSL_DEBUG_MSG( 3, ( "=> handshake wrapup: final free" ) );
06257 
06258     /*
06259      * Free our handshake params
06260      */
06261     mbedtls_ssl_handshake_free( ssl );
06262     mbedtls_free( ssl->handshake );
06263     ssl->handshake = NULL;
06264 
06265     /*
06266      * Free the previous transform and swith in the current one
06267      */
06268     if( ssl->transform )
06269     {
06270         mbedtls_ssl_transform_free( ssl->transform );
06271         mbedtls_free( ssl->transform );
06272     }
06273     ssl->transform = ssl->transform_negotiate;
06274     ssl->transform_negotiate = NULL;
06275 
06276     MBEDTLS_SSL_DEBUG_MSG( 3, ( "<= handshake wrapup: final free" ) );
06277 }
06278 
06279 void mbedtls_ssl_handshake_wrapup( mbedtls_ssl_context *ssl )
06280 {
06281     int resume = ssl->handshake->resume;
06282 
06283     MBEDTLS_SSL_DEBUG_MSG( 3, ( "=> handshake wrapup" ) );
06284 
06285 #if defined(MBEDTLS_SSL_RENEGOTIATION)
06286     if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
06287     {
06288         ssl->renego_status =  MBEDTLS_SSL_RENEGOTIATION_DONE;
06289         ssl->renego_records_seen = 0;
06290     }
06291 #endif
06292 
06293     /*
06294      * Free the previous session and switch in the current one
06295      */
06296     if( ssl->session )
06297     {
06298 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
06299         /* RFC 7366 3.1: keep the EtM state */
06300         ssl->session_negotiate->encrypt_then_mac =
06301                   ssl->session->encrypt_then_mac;
06302 #endif
06303 
06304         mbedtls_ssl_session_free( ssl->session );
06305         mbedtls_free( ssl->session );
06306     }
06307     ssl->session = ssl->session_negotiate;
06308     ssl->session_negotiate = NULL;
06309 
06310     /*
06311      * Add cache entry
06312      */
06313     if( ssl->conf->f_set_cache != NULL &&
06314         ssl->session->id_len != 0 &&
06315         resume == 0 )
06316     {
06317         if( ssl->conf->f_set_cache( ssl->conf->p_cache, ssl->session ) != 0 )
06318             MBEDTLS_SSL_DEBUG_MSG( 1, ( "cache did not store session" ) );
06319     }
06320 
06321 #if defined(MBEDTLS_SSL_PROTO_DTLS)
06322     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
06323         ssl->handshake->flight != NULL )
06324     {
06325         /* Cancel handshake timer */
06326         ssl_set_timer( ssl, 0 );
06327 
06328         /* Keep last flight around in case we need to resend it:
06329          * we need the handshake and transform structures for that */
06330         MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip freeing handshake and transform" ) );
06331     }
06332     else
06333 #endif
06334         ssl_handshake_wrapup_free_hs_transform( ssl );
06335 
06336     ssl->state++;
06337 
06338     MBEDTLS_SSL_DEBUG_MSG( 3, ( "<= handshake wrapup" ) );
06339 }
06340 
06341 int mbedtls_ssl_write_finished( mbedtls_ssl_context *ssl )
06342 {
06343     int ret, hash_len;
06344 
06345     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write finished" ) );
06346 
06347     ssl_update_out_pointers( ssl, ssl->transform_negotiate );
06348 
06349     ssl->handshake->calc_finished( ssl, ssl->out_msg + 4, ssl->conf->endpoint );
06350 
06351     /*
06352      * RFC 5246 7.4.9 (Page 63) says 12 is the default length and ciphersuites
06353      * may define some other value. Currently (early 2016), no defined
06354      * ciphersuite does this (and this is unlikely to change as activity has
06355      * moved to TLS 1.3 now) so we can keep the hardcoded 12 here.
06356      */
06357     hash_len = ( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) ? 36 : 12;
06358 
06359 #if defined(MBEDTLS_SSL_RENEGOTIATION)
06360     ssl->verify_data_len = hash_len;
06361     memcpy( ssl->own_verify_data, ssl->out_msg + 4, hash_len );
06362 #endif
06363 
06364     ssl->out_msglen  = 4 + hash_len;
06365     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
06366     ssl->out_msg[0]  = MBEDTLS_SSL_HS_FINISHED;
06367 
06368     /*
06369      * In case of session resuming, invert the client and server
06370      * ChangeCipherSpec messages order.
06371      */
06372     if( ssl->handshake->resume != 0 )
06373     {
06374 #if defined(MBEDTLS_SSL_CLI_C)
06375         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
06376             ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
06377 #endif
06378 #if defined(MBEDTLS_SSL_SRV_C)
06379         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
06380             ssl->state = MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC;
06381 #endif
06382     }
06383     else
06384         ssl->state++;
06385 
06386     /*
06387      * Switch to our negotiated transform and session parameters for outbound
06388      * data.
06389      */
06390     MBEDTLS_SSL_DEBUG_MSG( 3, ( "switching to new transform spec for outbound data" ) );
06391 
06392 #if defined(MBEDTLS_SSL_PROTO_DTLS)
06393     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
06394     {
06395         unsigned char i;
06396 
06397         /* Remember current epoch settings for resending */
06398         ssl->handshake->alt_transform_out = ssl->transform_out;
06399         memcpy( ssl->handshake->alt_out_ctr, ssl->cur_out_ctr, 8 );
06400 
06401         /* Set sequence_number to zero */
06402         memset( ssl->cur_out_ctr + 2, 0, 6 );
06403 
06404         /* Increment epoch */
06405         for( i = 2; i > 0; i-- )
06406             if( ++ssl->cur_out_ctr[i - 1] != 0 )
06407                 break;
06408 
06409         /* The loop goes to its end iff the counter is wrapping */
06410         if( i == 0 )
06411         {
06412             MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS epoch would wrap" ) );
06413             return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
06414         }
06415     }
06416     else
06417 #endif /* MBEDTLS_SSL_PROTO_DTLS */
06418     memset( ssl->cur_out_ctr, 0, 8 );
06419 
06420     ssl->transform_out = ssl->transform_negotiate;
06421     ssl->session_out = ssl->session_negotiate;
06422 
06423 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
06424     if( mbedtls_ssl_hw_record_activate != NULL )
06425     {
06426         if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_OUTBOUND ) ) != 0 )
06427         {
06428             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret );
06429             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
06430         }
06431     }
06432 #endif
06433 
06434 #if defined(MBEDTLS_SSL_PROTO_DTLS)
06435     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
06436         mbedtls_ssl_send_flight_completed( ssl );
06437 #endif
06438 
06439     if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
06440     {
06441         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
06442         return( ret );
06443     }
06444 
06445 #if defined(MBEDTLS_SSL_PROTO_DTLS)
06446     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
06447         ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 )
06448     {
06449         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flight_transmit", ret );
06450         return( ret );
06451     }
06452 #endif
06453 
06454     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write finished" ) );
06455 
06456     return( 0 );
06457 }
06458 
06459 #if defined(MBEDTLS_SSL_PROTO_SSL3)
06460 #define SSL_MAX_HASH_LEN 36
06461 #else
06462 #define SSL_MAX_HASH_LEN 12
06463 #endif
06464 
06465 int mbedtls_ssl_parse_finished( mbedtls_ssl_context *ssl )
06466 {
06467     int ret;
06468     unsigned int hash_len;
06469     unsigned char buf[SSL_MAX_HASH_LEN];
06470 
06471     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse finished" ) );
06472 
06473     ssl->handshake->calc_finished( ssl, buf, ssl->conf->endpoint ^ 1 );
06474 
06475     if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
06476     {
06477         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
06478         return( ret );
06479     }
06480 
06481     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
06482     {
06483         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
06484         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
06485                                         MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
06486         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
06487     }
06488 
06489     /* There is currently no ciphersuite using another length with TLS 1.2 */
06490 #if defined(MBEDTLS_SSL_PROTO_SSL3)
06491     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
06492         hash_len = 36;
06493     else
06494 #endif
06495         hash_len = 12;
06496 
06497     if( ssl->in_msg[0] != MBEDTLS_SSL_HS_FINISHED ||
06498         ssl->in_hslen  != mbedtls_ssl_hs_hdr_len( ssl ) + hash_len )
06499     {
06500         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
06501         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
06502                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
06503         return( MBEDTLS_ERR_SSL_BAD_HS_FINISHED );
06504     }
06505 
06506     if( mbedtls_ssl_safer_memcmp( ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ),
06507                       buf, hash_len ) != 0 )
06508     {
06509         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
06510         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
06511                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
06512         return( MBEDTLS_ERR_SSL_BAD_HS_FINISHED );
06513     }
06514 
06515 #if defined(MBEDTLS_SSL_RENEGOTIATION)
06516     ssl->verify_data_len = hash_len;
06517     memcpy( ssl->peer_verify_data, buf, hash_len );
06518 #endif
06519 
06520     if( ssl->handshake->resume != 0 )
06521     {
06522 #if defined(MBEDTLS_SSL_CLI_C)
06523         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
06524             ssl->state = MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC;
06525 #endif
06526 #if defined(MBEDTLS_SSL_SRV_C)
06527         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
06528             ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
06529 #endif
06530     }
06531     else
06532         ssl->state++;
06533 
06534 #if defined(MBEDTLS_SSL_PROTO_DTLS)
06535     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
06536         mbedtls_ssl_recv_flight_completed( ssl );
06537 #endif
06538 
06539     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse finished" ) );
06540 
06541     return( 0 );
06542 }
06543 
06544 static void ssl_handshake_params_init( mbedtls_ssl_handshake_params *handshake )
06545 {
06546     memset( handshake, 0, sizeof( mbedtls_ssl_handshake_params ) );
06547 
06548 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
06549     defined(MBEDTLS_SSL_PROTO_TLS1_1)
06550      mbedtls_md5_init(   &handshake->fin_md5  );
06551     mbedtls_sha1_init(   &handshake->fin_sha1 );
06552      mbedtls_md5_starts_ret( &handshake->fin_md5  );
06553     mbedtls_sha1_starts_ret( &handshake->fin_sha1 );
06554 #endif
06555 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
06556 #if defined(MBEDTLS_SHA256_C)
06557     mbedtls_sha256_init(   &handshake->fin_sha256    );
06558     mbedtls_sha256_starts_ret( &handshake->fin_sha256, 0 );
06559 #endif
06560 #if defined(MBEDTLS_SHA512_C)
06561     mbedtls_sha512_init(   &handshake->fin_sha512    );
06562     mbedtls_sha512_starts_ret( &handshake->fin_sha512, 1 );
06563 #endif
06564 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
06565 
06566     handshake->update_checksum = ssl_update_checksum_start;
06567 
06568 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
06569     defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
06570     mbedtls_ssl_sig_hash_set_init( &handshake->hash_algs );
06571 #endif
06572 
06573 #if defined(MBEDTLS_DHM_C)
06574     mbedtls_dhm_init( &handshake->dhm_ctx );
06575 #endif
06576 #if defined(MBEDTLS_ECDH_C)
06577     mbedtls_ecdh_init( &handshake->ecdh_ctx );
06578 #endif
06579 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
06580     mbedtls_ecjpake_init( &handshake->ecjpake_ctx );
06581 #if defined(MBEDTLS_SSL_CLI_C)
06582     handshake->ecjpake_cache = NULL;
06583     handshake->ecjpake_cache_len = 0;
06584 #endif
06585 #endif
06586 
06587 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
06588     handshake->sni_authmode = MBEDTLS_SSL_VERIFY_UNSET;
06589 #endif
06590 }
06591 
06592 static void ssl_transform_init( mbedtls_ssl_transform *transform )
06593 {
06594     memset( transform, 0, sizeof(mbedtls_ssl_transform) );
06595 
06596     mbedtls_cipher_init( &transform->cipher_ctx_enc );
06597     mbedtls_cipher_init( &transform->cipher_ctx_dec );
06598 
06599     mbedtls_md_init( &transform->md_ctx_enc );
06600     mbedtls_md_init( &transform->md_ctx_dec );
06601 }
06602 
06603 void mbedtls_ssl_session_init( mbedtls_ssl_session *session )
06604 {
06605     memset( session, 0, sizeof(mbedtls_ssl_session) );
06606 }
06607 
06608 static int ssl_handshake_init( mbedtls_ssl_context *ssl )
06609 {
06610     /* Clear old handshake information if present */
06611     if( ssl->transform_negotiate )
06612         mbedtls_ssl_transform_free( ssl->transform_negotiate );
06613     if( ssl->session_negotiate )
06614         mbedtls_ssl_session_free( ssl->session_negotiate );
06615     if( ssl->handshake )
06616         mbedtls_ssl_handshake_free( ssl );
06617 
06618     /*
06619      * Either the pointers are now NULL or cleared properly and can be freed.
06620      * Now allocate missing structures.
06621      */
06622     if( ssl->transform_negotiate == NULL )
06623     {
06624         ssl->transform_negotiate = mbedtls_calloc( 1, sizeof(mbedtls_ssl_transform) );
06625     }
06626 
06627     if( ssl->session_negotiate == NULL )
06628     {
06629         ssl->session_negotiate = mbedtls_calloc( 1, sizeof(mbedtls_ssl_session) );
06630     }
06631 
06632     if( ssl->handshake == NULL )
06633     {
06634         ssl->handshake = mbedtls_calloc( 1, sizeof(mbedtls_ssl_handshake_params) );
06635     }
06636 
06637     /* All pointers should exist and can be directly freed without issue */
06638     if( ssl->handshake == NULL ||
06639         ssl->transform_negotiate == NULL ||
06640         ssl->session_negotiate == NULL )
06641     {
06642         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc() of ssl sub-contexts failed" ) );
06643 
06644         mbedtls_free( ssl->handshake );
06645         mbedtls_free( ssl->transform_negotiate );
06646         mbedtls_free( ssl->session_negotiate );
06647 
06648         ssl->handshake = NULL;
06649         ssl->transform_negotiate = NULL;
06650         ssl->session_negotiate = NULL;
06651 
06652         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
06653     }
06654 
06655     /* Initialize structures */
06656     mbedtls_ssl_session_init( ssl->session_negotiate );
06657     ssl_transform_init( ssl->transform_negotiate );
06658     ssl_handshake_params_init( ssl->handshake );
06659 
06660 #if defined(MBEDTLS_SSL_PROTO_DTLS)
06661     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
06662     {
06663         ssl->handshake->alt_transform_out = ssl->transform_out;
06664 
06665         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
06666             ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_PREPARING;
06667         else
06668             ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
06669 
06670         ssl_set_timer( ssl, 0 );
06671     }
06672 #endif
06673 
06674     return( 0 );
06675 }
06676 
06677 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
06678 /* Dummy cookie callbacks for defaults */
06679 static int ssl_cookie_write_dummy( void *ctx,
06680                       unsigned char **p, unsigned char *end,
06681                       const unsigned char *cli_id, size_t cli_id_len )
06682 {
06683     ((void) ctx);
06684     ((void) p);
06685     ((void) end);
06686     ((void) cli_id);
06687     ((void) cli_id_len);
06688 
06689     return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
06690 }
06691 
06692 static int ssl_cookie_check_dummy( void *ctx,
06693                       const unsigned char *cookie, size_t cookie_len,
06694                       const unsigned char *cli_id, size_t cli_id_len )
06695 {
06696     ((void) ctx);
06697     ((void) cookie);
06698     ((void) cookie_len);
06699     ((void) cli_id);
06700     ((void) cli_id_len);
06701 
06702     return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
06703 }
06704 #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY && MBEDTLS_SSL_SRV_C */
06705 
06706 /* Once ssl->out_hdr as the address of the beginning of the
06707  * next outgoing record is set, deduce the other pointers.
06708  *
06709  * Note: For TLS, we save the implicit record sequence number
06710  *       (entering MAC computation) in the 8 bytes before ssl->out_hdr,
06711  *       and the caller has to make sure there's space for this.
06712  */
06713 
06714 static void ssl_update_out_pointers( mbedtls_ssl_context *ssl,
06715                                      mbedtls_ssl_transform *transform )
06716 {
06717 #if defined(MBEDTLS_SSL_PROTO_DTLS)
06718     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
06719     {
06720         ssl->out_ctr = ssl->out_hdr +  3;
06721         ssl->out_len = ssl->out_hdr + 11;
06722         ssl->out_iv  = ssl->out_hdr + 13;
06723     }
06724     else
06725 #endif
06726     {
06727         ssl->out_ctr = ssl->out_hdr - 8;
06728         ssl->out_len = ssl->out_hdr + 3;
06729         ssl->out_iv  = ssl->out_hdr + 5;
06730     }
06731 
06732     /* Adjust out_msg to make space for explicit IV, if used. */
06733     if( transform != NULL &&
06734         ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
06735     {
06736         ssl->out_msg = ssl->out_iv + transform->ivlen - transform->fixed_ivlen;
06737     }
06738     else
06739         ssl->out_msg = ssl->out_iv;
06740 }
06741 
06742 /* Once ssl->in_hdr as the address of the beginning of the
06743  * next incoming record is set, deduce the other pointers.
06744  *
06745  * Note: For TLS, we save the implicit record sequence number
06746  *       (entering MAC computation) in the 8 bytes before ssl->in_hdr,
06747  *       and the caller has to make sure there's space for this.
06748  */
06749 
06750 static void ssl_update_in_pointers( mbedtls_ssl_context *ssl,
06751                                     mbedtls_ssl_transform *transform )
06752 {
06753 #if defined(MBEDTLS_SSL_PROTO_DTLS)
06754     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
06755     {
06756         ssl->in_ctr = ssl->in_hdr +  3;
06757         ssl->in_len = ssl->in_hdr + 11;
06758         ssl->in_iv  = ssl->in_hdr + 13;
06759     }
06760     else
06761 #endif
06762     {
06763         ssl->in_ctr = ssl->in_hdr - 8;
06764         ssl->in_len = ssl->in_hdr + 3;
06765         ssl->in_iv  = ssl->in_hdr + 5;
06766     }
06767 
06768     /* Offset in_msg from in_iv to allow space for explicit IV, if used. */
06769     if( transform != NULL &&
06770         ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
06771     {
06772         ssl->in_msg = ssl->in_iv + transform->ivlen - transform->fixed_ivlen;
06773     }
06774     else
06775         ssl->in_msg = ssl->in_iv;
06776 }
06777 
06778 /*
06779  * Initialize an SSL context
06780  */
06781 void mbedtls_ssl_init( mbedtls_ssl_context *ssl )
06782 {
06783     memset( ssl, 0, sizeof( mbedtls_ssl_context ) );
06784 }
06785 
06786 /*
06787  * Setup an SSL context
06788  */
06789 
06790 static void ssl_reset_in_out_pointers( mbedtls_ssl_context *ssl )
06791 {
06792     /* Set the incoming and outgoing record pointers. */
06793 #if defined(MBEDTLS_SSL_PROTO_DTLS)
06794     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
06795     {
06796         ssl->out_hdr = ssl->out_buf;
06797         ssl->in_hdr  = ssl->in_buf;
06798     }
06799     else
06800 #endif /* MBEDTLS_SSL_PROTO_DTLS */
06801     {
06802         ssl->out_hdr = ssl->out_buf + 8;
06803         ssl->in_hdr  = ssl->in_buf  + 8;
06804     }
06805 
06806     /* Derive other internal pointers. */
06807     ssl_update_out_pointers( ssl, NULL /* no transform enabled */ );
06808     ssl_update_in_pointers ( ssl, NULL /* no transform enabled */ );
06809 }
06810 
06811 int mbedtls_ssl_setup( mbedtls_ssl_context *ssl,
06812                        const mbedtls_ssl_config *conf )
06813 {
06814     int ret;
06815 
06816     ssl->conf = conf;
06817 
06818     /*
06819      * Prepare base structures
06820      */
06821 
06822     /* Set to NULL in case of an error condition */
06823     ssl->out_buf = NULL;
06824 
06825     ssl->in_buf = mbedtls_calloc( 1, MBEDTLS_SSL_IN_BUFFER_LEN );
06826     if( ssl->in_buf == NULL )
06827     {
06828         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed", MBEDTLS_SSL_IN_BUFFER_LEN) );
06829         ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
06830         goto error;
06831     }
06832 
06833     ssl->out_buf = mbedtls_calloc( 1, MBEDTLS_SSL_OUT_BUFFER_LEN );
06834     if( ssl->out_buf == NULL )
06835     {
06836         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed", MBEDTLS_SSL_OUT_BUFFER_LEN) );
06837         ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
06838         goto error;
06839     }
06840 
06841     ssl_reset_in_out_pointers( ssl );
06842 
06843     if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
06844         goto error;
06845 
06846     return( 0 );
06847 
06848 error:
06849     mbedtls_free( ssl->in_buf );
06850     mbedtls_free( ssl->out_buf );
06851 
06852     ssl->conf = NULL;
06853 
06854     ssl->in_buf = NULL;
06855     ssl->out_buf = NULL;
06856 
06857     ssl->in_hdr = NULL;
06858     ssl->in_ctr = NULL;
06859     ssl->in_len = NULL;
06860     ssl->in_iv = NULL;
06861     ssl->in_msg = NULL;
06862 
06863     ssl->out_hdr = NULL;
06864     ssl->out_ctr = NULL;
06865     ssl->out_len = NULL;
06866     ssl->out_iv = NULL;
06867     ssl->out_msg = NULL;
06868 
06869     return( ret );
06870 }
06871 
06872 /*
06873  * Reset an initialized and used SSL context for re-use while retaining
06874  * all application-set variables, function pointers and data.
06875  *
06876  * If partial is non-zero, keep data in the input buffer and client ID.
06877  * (Use when a DTLS client reconnects from the same port.)
06878  */
06879 static int ssl_session_reset_int( mbedtls_ssl_context *ssl, int partial )
06880 {
06881     int ret;
06882 
06883 #if !defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) ||     \
06884     !defined(MBEDTLS_SSL_SRV_C)
06885     ((void) partial);
06886 #endif
06887 
06888     ssl->state = MBEDTLS_SSL_HELLO_REQUEST;
06889 
06890     /* Cancel any possibly running timer */
06891     ssl_set_timer( ssl, 0 );
06892 
06893 #if defined(MBEDTLS_SSL_RENEGOTIATION)
06894     ssl->renego_status = MBEDTLS_SSL_INITIAL_HANDSHAKE;
06895     ssl->renego_records_seen = 0;
06896 
06897     ssl->verify_data_len = 0;
06898     memset( ssl->own_verify_data, 0, MBEDTLS_SSL_VERIFY_DATA_MAX_LEN );
06899     memset( ssl->peer_verify_data, 0, MBEDTLS_SSL_VERIFY_DATA_MAX_LEN );
06900 #endif
06901     ssl->secure_renegotiation = MBEDTLS_SSL_LEGACY_RENEGOTIATION;
06902 
06903     ssl->in_offt = NULL;
06904     ssl_reset_in_out_pointers( ssl );
06905 
06906     ssl->in_msgtype = 0;
06907     ssl->in_msglen = 0;
06908 #if defined(MBEDTLS_SSL_PROTO_DTLS)
06909     ssl->next_record_offset = 0;
06910     ssl->in_epoch = 0;
06911 #endif
06912 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
06913     ssl_dtls_replay_reset( ssl );
06914 #endif
06915 
06916     ssl->in_hslen = 0;
06917     ssl->nb_zero = 0;
06918 
06919     ssl->keep_current_message = 0;
06920 
06921     ssl->out_msgtype = 0;
06922     ssl->out_msglen = 0;
06923     ssl->out_left = 0;
06924 #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
06925     if( ssl->split_done != MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED )
06926         ssl->split_done = 0;
06927 #endif
06928 
06929     memset( ssl->cur_out_ctr, 0, sizeof( ssl->cur_out_ctr ) );
06930 
06931     ssl->transform_in = NULL;
06932     ssl->transform_out = NULL;
06933 
06934     ssl->session_in = NULL;
06935     ssl->session_out = NULL;
06936 
06937     memset( ssl->out_buf, 0, MBEDTLS_SSL_OUT_BUFFER_LEN );
06938 
06939 #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
06940     if( partial == 0 )
06941 #endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */
06942     {
06943         ssl->in_left = 0;
06944         memset( ssl->in_buf, 0, MBEDTLS_SSL_IN_BUFFER_LEN );
06945     }
06946 
06947 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
06948     if( mbedtls_ssl_hw_record_reset != NULL )
06949     {
06950         MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_reset()" ) );
06951         if( ( ret = mbedtls_ssl_hw_record_reset( ssl ) ) != 0 )
06952         {
06953             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_reset", ret );
06954             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
06955         }
06956     }
06957 #endif
06958 
06959     if( ssl->transform )
06960     {
06961         mbedtls_ssl_transform_free( ssl->transform );
06962         mbedtls_free( ssl->transform );
06963         ssl->transform = NULL;
06964     }
06965 
06966     if( ssl->session )
06967     {
06968         mbedtls_ssl_session_free( ssl->session );
06969         mbedtls_free( ssl->session );
06970         ssl->session = NULL;
06971     }
06972 
06973 #if defined(MBEDTLS_SSL_ALPN)
06974     ssl->alpn_chosen = NULL;
06975 #endif
06976 
06977 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
06978 #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE)
06979     if( partial == 0 )
06980 #endif
06981     {
06982         mbedtls_free( ssl->cli_id );
06983         ssl->cli_id = NULL;
06984         ssl->cli_id_len = 0;
06985     }
06986 #endif
06987 
06988     if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
06989         return( ret );
06990 
06991     return( 0 );
06992 }
06993 
06994 /*
06995  * Reset an initialized and used SSL context for re-use while retaining
06996  * all application-set variables, function pointers and data.
06997  */
06998 int mbedtls_ssl_session_reset( mbedtls_ssl_context *ssl )
06999 {
07000     return( ssl_session_reset_int( ssl, 0 ) );
07001 }
07002 
07003 /*
07004  * SSL set accessors
07005  */
07006 void mbedtls_ssl_conf_endpoint( mbedtls_ssl_config *conf, int endpoint )
07007 {
07008     conf->endpoint    = endpoint;
07009 }
07010 
07011 void mbedtls_ssl_conf_transport( mbedtls_ssl_config *conf, int transport )
07012 {
07013     conf->transport  = transport;
07014 }
07015 
07016 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
07017 void mbedtls_ssl_conf_dtls_anti_replay( mbedtls_ssl_config *conf, char mode )
07018 {
07019     conf->anti_replay  = mode;
07020 }
07021 #endif
07022 
07023 #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT)
07024 void mbedtls_ssl_conf_dtls_badmac_limit( mbedtls_ssl_config *conf, unsigned limit )
07025 {
07026     conf->badmac_limit  = limit;
07027 }
07028 #endif
07029 
07030 #if defined(MBEDTLS_SSL_PROTO_DTLS)
07031 
07032 void mbedtls_ssl_set_datagram_packing( mbedtls_ssl_context *ssl,
07033                                        unsigned allow_packing )
07034 {
07035     ssl->disable_datagram_packing = !allow_packing;
07036 }
07037 
07038 void mbedtls_ssl_conf_handshake_timeout( mbedtls_ssl_config *conf,
07039                                          uint32_t min, uint32_t max )
07040 {
07041     conf->hs_timeout_min  = min;
07042     conf->hs_timeout_max  = max;
07043 }
07044 #endif
07045 
07046 void mbedtls_ssl_conf_authmode( mbedtls_ssl_config *conf, int authmode )
07047 {
07048     conf->authmode    = authmode;
07049 }
07050 
07051 #if defined(MBEDTLS_X509_CRT_PARSE_C)
07052 void mbedtls_ssl_conf_verify( mbedtls_ssl_config *conf,
07053                      int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
07054                      void *p_vrfy )
07055 {
07056     conf->f_vrfy      = f_vrfy;
07057     conf->p_vrfy       = p_vrfy;
07058 }
07059 #endif /* MBEDTLS_X509_CRT_PARSE_C */
07060 
07061 void mbedtls_ssl_conf_rng( mbedtls_ssl_config *conf,
07062                   int (*f_rng)(void *, unsigned char *, size_t),
07063                   void *p_rng )
07064 {
07065     conf->f_rng      = f_rng;
07066     conf->p_rng       = p_rng;
07067 }
07068 
07069 void mbedtls_ssl_conf_dbg( mbedtls_ssl_config *conf,
07070                   void (*f_dbg)(void *, int, const char *, int, const char *),
07071                   void  *p_dbg )
07072 {
07073     conf->f_dbg      = f_dbg;
07074     conf->p_dbg       = p_dbg;
07075 }
07076 
07077 void mbedtls_ssl_set_bio( mbedtls_ssl_context *ssl,
07078         void *p_bio,
07079         mbedtls_ssl_send_t *f_send,
07080         mbedtls_ssl_recv_t *f_recv,
07081         mbedtls_ssl_recv_timeout_t *f_recv_timeout )
07082 {
07083     ssl->p_bio          = p_bio;
07084     ssl->f_send         = f_send;
07085     ssl->f_recv         = f_recv;
07086     ssl->f_recv_timeout = f_recv_timeout;
07087 }
07088 
07089 #if defined(MBEDTLS_SSL_PROTO_DTLS)
07090 void mbedtls_ssl_set_mtu( mbedtls_ssl_context *ssl, uint16_t mtu )
07091 {
07092     ssl->mtu = mtu;
07093 }
07094 #endif
07095 
07096 void mbedtls_ssl_conf_read_timeout( mbedtls_ssl_config *conf, uint32_t timeout )
07097 {
07098     conf->read_timeout    = timeout;
07099 }
07100 
07101 void mbedtls_ssl_set_timer_cb( mbedtls_ssl_context *ssl,
07102                                void *p_timer,
07103                                mbedtls_ssl_set_timer_t *f_set_timer,
07104                                mbedtls_ssl_get_timer_t *f_get_timer )
07105 {
07106     ssl->p_timer        = p_timer;
07107     ssl->f_set_timer    = f_set_timer;
07108     ssl->f_get_timer    = f_get_timer;
07109 
07110     /* Make sure we start with no timer running */
07111     ssl_set_timer( ssl, 0 );
07112 }
07113 
07114 #if defined(MBEDTLS_SSL_SRV_C)
07115 void mbedtls_ssl_conf_session_cache( mbedtls_ssl_config *conf,
07116         void *p_cache,
07117         int (*f_get_cache)(void *, mbedtls_ssl_session *),
07118         int (*f_set_cache)(void *, const mbedtls_ssl_session *) )
07119 {
07120     conf->p_cache  = p_cache;
07121     conf->f_get_cache = f_get_cache;
07122     conf->f_set_cache = f_set_cache;
07123 }
07124 #endif /* MBEDTLS_SSL_SRV_C */
07125 
07126 #if defined(MBEDTLS_SSL_CLI_C)
07127 int mbedtls_ssl_set_session( mbedtls_ssl_context *ssl, const mbedtls_ssl_session *session )
07128 {
07129     int ret;
07130 
07131     if( ssl == NULL ||
07132         session == NULL ||
07133         ssl->session_negotiate == NULL ||
07134         ssl->conf->endpoint != MBEDTLS_SSL_IS_CLIENT )
07135     {
07136         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
07137     }
07138 
07139     if( ( ret = ssl_session_copy( ssl->session_negotiate, session ) ) != 0 )
07140         return( ret );
07141 
07142     ssl->handshake->resume = 1;
07143 
07144     return( 0 );
07145 }
07146 #endif /* MBEDTLS_SSL_CLI_C */
07147 
07148 void mbedtls_ssl_conf_ciphersuites( mbedtls_ssl_config *conf,
07149                                    const int *ciphersuites )
07150 {
07151     conf->ciphersuite_list [MBEDTLS_SSL_MINOR_VERSION_0] = ciphersuites;
07152     conf->ciphersuite_list [MBEDTLS_SSL_MINOR_VERSION_1] = ciphersuites;
07153     conf->ciphersuite_list [MBEDTLS_SSL_MINOR_VERSION_2] = ciphersuites;
07154     conf->ciphersuite_list [MBEDTLS_SSL_MINOR_VERSION_3] = ciphersuites;
07155 }
07156 
07157 void mbedtls_ssl_conf_ciphersuites_for_version( mbedtls_ssl_config *conf,
07158                                        const int *ciphersuites,
07159                                        int major, int minor )
07160 {
07161     if( major != MBEDTLS_SSL_MAJOR_VERSION_3 )
07162         return;
07163 
07164     if( minor < MBEDTLS_SSL_MINOR_VERSION_0 || minor > MBEDTLS_SSL_MINOR_VERSION_3 )
07165         return;
07166 
07167     conf->ciphersuite_list [minor] = ciphersuites;
07168 }
07169 
07170 #if defined(MBEDTLS_X509_CRT_PARSE_C)
07171 void mbedtls_ssl_conf_cert_profile( mbedtls_ssl_config *conf,
07172                                     const mbedtls_x509_crt_profile *profile )
07173 {
07174     conf->cert_profile  = profile;
07175 }
07176 
07177 /* Append a new keycert entry to a (possibly empty) list */
07178 static int ssl_append_key_cert( mbedtls_ssl_key_cert **head,
07179                                 mbedtls_x509_crt *cert,
07180                                 mbedtls_pk_context *key )
07181 {
07182     mbedtls_ssl_key_cert *new_cert;
07183 
07184     new_cert = mbedtls_calloc( 1, sizeof( mbedtls_ssl_key_cert ) );
07185     if( new_cert == NULL )
07186         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
07187 
07188     new_cert->cert = cert;
07189     new_cert->key  = key;
07190     new_cert->next = NULL;
07191 
07192     /* Update head is the list was null, else add to the end */
07193     if( *head == NULL )
07194     {
07195         *head = new_cert;
07196     }
07197     else
07198     {
07199         mbedtls_ssl_key_cert *cur = *head;
07200         while( cur->next != NULL )
07201             cur = cur->next;
07202         cur->next = new_cert;
07203     }
07204 
07205     return( 0 );
07206 }
07207 
07208 int mbedtls_ssl_conf_own_cert( mbedtls_ssl_config *conf,
07209                               mbedtls_x509_crt *own_cert,
07210                               mbedtls_pk_context *pk_key )
07211 {
07212     return( ssl_append_key_cert( &conf->key_cert , own_cert, pk_key ) );
07213 }
07214 
07215 void mbedtls_ssl_conf_ca_chain( mbedtls_ssl_config *conf,
07216                                mbedtls_x509_crt *ca_chain,
07217                                mbedtls_x509_crl *ca_crl )
07218 {
07219     conf->ca_chain    = ca_chain;
07220     conf->ca_crl      = ca_crl;
07221 }
07222 #endif /* MBEDTLS_X509_CRT_PARSE_C */
07223 
07224 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
07225 int mbedtls_ssl_set_hs_own_cert( mbedtls_ssl_context *ssl,
07226                                  mbedtls_x509_crt *own_cert,
07227                                  mbedtls_pk_context *pk_key )
07228 {
07229     return( ssl_append_key_cert( &ssl->handshake->sni_key_cert,
07230                                  own_cert, pk_key ) );
07231 }
07232 
07233 void mbedtls_ssl_set_hs_ca_chain( mbedtls_ssl_context *ssl,
07234                                   mbedtls_x509_crt *ca_chain,
07235                                   mbedtls_x509_crl *ca_crl )
07236 {
07237     ssl->handshake->sni_ca_chain   = ca_chain;
07238     ssl->handshake->sni_ca_crl     = ca_crl;
07239 }
07240 
07241 void mbedtls_ssl_set_hs_authmode( mbedtls_ssl_context *ssl,
07242                                   int authmode )
07243 {
07244     ssl->handshake->sni_authmode = authmode;
07245 }
07246 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
07247 
07248 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
07249 /*
07250  * Set EC J-PAKE password for current handshake
07251  */
07252 int mbedtls_ssl_set_hs_ecjpake_password( mbedtls_ssl_context *ssl,
07253                                          const unsigned char *pw,
07254                                          size_t pw_len )
07255 {
07256     mbedtls_ecjpake_role role;
07257 
07258     if( ssl->handshake == NULL || ssl->conf == NULL )
07259         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
07260 
07261     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
07262         role = MBEDTLS_ECJPAKE_SERVER;
07263     else
07264         role = MBEDTLS_ECJPAKE_CLIENT;
07265 
07266     return( mbedtls_ecjpake_setup( &ssl->handshake->ecjpake_ctx,
07267                                    role,
07268                                    MBEDTLS_MD_SHA256,
07269                                    MBEDTLS_ECP_DP_SECP256R1,
07270                                    pw, pw_len ) );
07271 }
07272 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
07273 
07274 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
07275 int mbedtls_ssl_conf_psk( mbedtls_ssl_config *conf,
07276                 const unsigned char *psk, size_t psk_len,
07277                 const unsigned char *psk_identity, size_t psk_identity_len )
07278 {
07279     if( psk == NULL || psk_identity == NULL )
07280         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
07281 
07282     if( psk_len > MBEDTLS_PSK_MAX_LEN )
07283         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
07284 
07285     /* Identity len will be encoded on two bytes */
07286     if( ( psk_identity_len >> 16 ) != 0 ||
07287         psk_identity_len > MBEDTLS_SSL_OUT_CONTENT_LEN )
07288     {
07289         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
07290     }
07291 
07292     if( conf->psk  != NULL )
07293     {
07294         mbedtls_platform_zeroize( conf->psk , conf->psk_len  );
07295 
07296         mbedtls_free( conf->psk  );
07297         conf->psk  = NULL;
07298         conf->psk_len  = 0;
07299     }
07300     if( conf->psk_identity  != NULL )
07301     {
07302         mbedtls_free( conf->psk_identity  );
07303         conf->psk_identity  = NULL;
07304         conf->psk_identity_len  = 0;
07305     }
07306 
07307     if( ( conf->psk  = mbedtls_calloc( 1, psk_len ) ) == NULL ||
07308         ( conf->psk_identity  = mbedtls_calloc( 1, psk_identity_len ) ) == NULL )
07309     {
07310         mbedtls_free( conf->psk  );
07311         mbedtls_free( conf->psk_identity  );
07312         conf->psk  = NULL;
07313         conf->psk_identity  = NULL;
07314         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
07315     }
07316 
07317     conf->psk_len  = psk_len;
07318     conf->psk_identity_len  = psk_identity_len;
07319 
07320     memcpy( conf->psk , psk, conf->psk_len  );
07321     memcpy( conf->psk_identity , psk_identity, conf->psk_identity_len  );
07322 
07323     return( 0 );
07324 }
07325 
07326 int mbedtls_ssl_set_hs_psk( mbedtls_ssl_context *ssl,
07327                             const unsigned char *psk, size_t psk_len )
07328 {
07329     if( psk == NULL || ssl->handshake == NULL )
07330         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
07331 
07332     if( psk_len > MBEDTLS_PSK_MAX_LEN )
07333         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
07334 
07335     if( ssl->handshake->psk != NULL )
07336     {
07337         mbedtls_platform_zeroize( ssl->handshake->psk,
07338                                   ssl->handshake->psk_len );
07339         mbedtls_free( ssl->handshake->psk );
07340         ssl->handshake->psk_len = 0;
07341     }
07342 
07343     if( ( ssl->handshake->psk = mbedtls_calloc( 1, psk_len ) ) == NULL )
07344         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
07345 
07346     ssl->handshake->psk_len = psk_len;
07347     memcpy( ssl->handshake->psk, psk, ssl->handshake->psk_len );
07348 
07349     return( 0 );
07350 }
07351 
07352 void mbedtls_ssl_conf_psk_cb( mbedtls_ssl_config *conf,
07353                      int (*f_psk)(void *, mbedtls_ssl_context *, const unsigned char *,
07354                      size_t),
07355                      void *p_psk )
07356 {
07357     conf->f_psk = f_psk;
07358     conf->p_psk  = p_psk;
07359 }
07360 #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
07361 
07362 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
07363 
07364 #if !defined(MBEDTLS_DEPRECATED_REMOVED)
07365 int mbedtls_ssl_conf_dh_param( mbedtls_ssl_config *conf, const char *dhm_P, const char *dhm_G )
07366 {
07367     int ret;
07368 
07369     if( ( ret = mbedtls_mpi_read_string( &conf->dhm_P , 16, dhm_P ) ) != 0 ||
07370         ( ret = mbedtls_mpi_read_string( &conf->dhm_G , 16, dhm_G ) ) != 0 )
07371     {
07372         mbedtls_mpi_free( &conf->dhm_P  );
07373         mbedtls_mpi_free( &conf->dhm_G  );
07374         return( ret );
07375     }
07376 
07377     return( 0 );
07378 }
07379 #endif /* MBEDTLS_DEPRECATED_REMOVED */
07380 
07381 int mbedtls_ssl_conf_dh_param_bin( mbedtls_ssl_config *conf,
07382                                    const unsigned char *dhm_P, size_t P_len,
07383                                    const unsigned char *dhm_G, size_t G_len )
07384 {
07385     int ret;
07386 
07387     if( ( ret = mbedtls_mpi_read_binary( &conf->dhm_P , dhm_P, P_len ) ) != 0 ||
07388         ( ret = mbedtls_mpi_read_binary( &conf->dhm_G , dhm_G, G_len ) ) != 0 )
07389     {
07390         mbedtls_mpi_free( &conf->dhm_P  );
07391         mbedtls_mpi_free( &conf->dhm_G  );
07392         return( ret );
07393     }
07394 
07395     return( 0 );
07396 }
07397 
07398 int mbedtls_ssl_conf_dh_param_ctx( mbedtls_ssl_config *conf, mbedtls_dhm_context *dhm_ctx )
07399 {
07400     int ret;
07401 
07402     if( ( ret = mbedtls_mpi_copy( &conf->dhm_P , &dhm_ctx->P  ) ) != 0 ||
07403         ( ret = mbedtls_mpi_copy( &conf->dhm_G , &dhm_ctx->G  ) ) != 0 )
07404     {
07405         mbedtls_mpi_free( &conf->dhm_P  );
07406         mbedtls_mpi_free( &conf->dhm_G  );
07407         return( ret );
07408     }
07409 
07410     return( 0 );
07411 }
07412 #endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_SRV_C */
07413 
07414 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C)
07415 /*
07416  * Set the minimum length for Diffie-Hellman parameters
07417  */
07418 void mbedtls_ssl_conf_dhm_min_bitlen( mbedtls_ssl_config *conf,
07419                                       unsigned int bitlen )
07420 {
07421     conf->dhm_min_bitlen  = bitlen;
07422 }
07423 #endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_CLI_C */
07424 
07425 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
07426 /*
07427  * Set allowed/preferred hashes for handshake signatures
07428  */
07429 void mbedtls_ssl_conf_sig_hashes( mbedtls_ssl_config *conf,
07430                                   const int *hashes )
07431 {
07432     conf->sig_hashes  = hashes;
07433 }
07434 #endif /* MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
07435 
07436 #if defined(MBEDTLS_ECP_C)
07437 /*
07438  * Set the allowed elliptic curves
07439  */
07440 void mbedtls_ssl_conf_curves( mbedtls_ssl_config *conf,
07441                              const mbedtls_ecp_group_id *curve_list )
07442 {
07443     conf->curve_list  = curve_list;
07444 }
07445 #endif /* MBEDTLS_ECP_C */
07446 
07447 #if defined(MBEDTLS_X509_CRT_PARSE_C)
07448 int mbedtls_ssl_set_hostname( mbedtls_ssl_context *ssl, const char *hostname )
07449 {
07450     /* Initialize to suppress unnecessary compiler warning */
07451     size_t hostname_len = 0;
07452 
07453     /* Check if new hostname is valid before
07454      * making any change to current one */
07455     if( hostname != NULL )
07456     {
07457         hostname_len = strlen( hostname );
07458 
07459         if( hostname_len > MBEDTLS_SSL_MAX_HOST_NAME_LEN )
07460             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
07461     }
07462 
07463     /* Now it's clear that we will overwrite the old hostname,
07464      * so we can free it safely */
07465 
07466     if( ssl->hostname != NULL )
07467     {
07468         mbedtls_platform_zeroize( ssl->hostname, strlen( ssl->hostname ) );
07469         mbedtls_free( ssl->hostname );
07470     }
07471 
07472     /* Passing NULL as hostname shall clear the old one */
07473 
07474     if( hostname == NULL )
07475     {
07476         ssl->hostname = NULL;
07477     }
07478     else
07479     {
07480         ssl->hostname = mbedtls_calloc( 1, hostname_len + 1 );
07481         if( ssl->hostname == NULL )
07482             return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
07483 
07484         memcpy( ssl->hostname, hostname, hostname_len );
07485 
07486         ssl->hostname[hostname_len] = '\0';
07487     }
07488 
07489     return( 0 );
07490 }
07491 #endif /* MBEDTLS_X509_CRT_PARSE_C */
07492 
07493 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
07494 void mbedtls_ssl_conf_sni( mbedtls_ssl_config *conf,
07495                   int (*f_sni)(void *, mbedtls_ssl_context *,
07496                                 const unsigned char *, size_t),
07497                   void *p_sni )
07498 {
07499     conf->f_sni = f_sni;
07500     conf->p_sni  = p_sni;
07501 }
07502 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
07503 
07504 #if defined(MBEDTLS_SSL_ALPN)
07505 int mbedtls_ssl_conf_alpn_protocols( mbedtls_ssl_config *conf, const char **protos )
07506 {
07507     size_t cur_len, tot_len;
07508     const char **p;
07509 
07510     /*
07511      * RFC 7301 3.1: "Empty strings MUST NOT be included and byte strings
07512      * MUST NOT be truncated."
07513      * We check lengths now rather than later.
07514      */
07515     tot_len = 0;
07516     for( p = protos; *p != NULL; p++ )
07517     {
07518         cur_len = strlen( *p );
07519         tot_len += cur_len;
07520 
07521         if( cur_len == 0 || cur_len > 255 || tot_len > 65535 )
07522             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
07523     }
07524 
07525     conf->alpn_list  = protos;
07526 
07527     return( 0 );
07528 }
07529 
07530 const char *mbedtls_ssl_get_alpn_protocol( const mbedtls_ssl_context *ssl )
07531 {
07532     return( ssl->alpn_chosen );
07533 }
07534 #endif /* MBEDTLS_SSL_ALPN */
07535 
07536 void mbedtls_ssl_conf_max_version( mbedtls_ssl_config *conf, int major, int minor )
07537 {
07538     conf->max_major_ver  = major;
07539     conf->max_minor_ver  = minor;
07540 }
07541 
07542 void mbedtls_ssl_conf_min_version( mbedtls_ssl_config *conf, int major, int minor )
07543 {
07544     conf->min_major_ver  = major;
07545     conf->min_minor_ver  = minor;
07546 }
07547 
07548 #if defined(MBEDTLS_SSL_FALLBACK_SCSV) && defined(MBEDTLS_SSL_CLI_C)
07549 void mbedtls_ssl_conf_fallback( mbedtls_ssl_config *conf, char fallback )
07550 {
07551     conf->fallback  = fallback;
07552 }
07553 #endif
07554 
07555 #if defined(MBEDTLS_SSL_SRV_C)
07556 void mbedtls_ssl_conf_cert_req_ca_list( mbedtls_ssl_config *conf,
07557                                           char cert_req_ca_list )
07558 {
07559     conf->cert_req_ca_list  = cert_req_ca_list;
07560 }
07561 #endif
07562 
07563 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
07564 void mbedtls_ssl_conf_encrypt_then_mac( mbedtls_ssl_config *conf, char etm )
07565 {
07566     conf->encrypt_then_mac  = etm;
07567 }
07568 #endif
07569 
07570 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
07571 void mbedtls_ssl_conf_extended_master_secret( mbedtls_ssl_config *conf, char ems )
07572 {
07573     conf->extended_ms  = ems;
07574 }
07575 #endif
07576 
07577 #if defined(MBEDTLS_ARC4_C)
07578 void mbedtls_ssl_conf_arc4_support( mbedtls_ssl_config *conf, char arc4 )
07579 {
07580     conf->arc4_disabled  = arc4;
07581 }
07582 #endif
07583 
07584 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
07585 int mbedtls_ssl_conf_max_frag_len( mbedtls_ssl_config *conf, unsigned char mfl_code )
07586 {
07587     if( mfl_code >= MBEDTLS_SSL_MAX_FRAG_LEN_INVALID ||
07588         ssl_mfl_code_to_length( mfl_code ) > MBEDTLS_TLS_EXT_ADV_CONTENT_LEN )
07589     {
07590         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
07591     }
07592 
07593     conf->mfl_code  = mfl_code;
07594 
07595     return( 0 );
07596 }
07597 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
07598 
07599 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
07600 void mbedtls_ssl_conf_truncated_hmac( mbedtls_ssl_config *conf, int truncate )
07601 {
07602     conf->trunc_hmac  = truncate;
07603 }
07604 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
07605 
07606 #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
07607 void mbedtls_ssl_conf_cbc_record_splitting( mbedtls_ssl_config *conf, char split )
07608 {
07609     conf->cbc_record_splitting  = split;
07610 }
07611 #endif
07612 
07613 void mbedtls_ssl_conf_legacy_renegotiation( mbedtls_ssl_config *conf, int allow_legacy )
07614 {
07615     conf->allow_legacy_renegotiation  = allow_legacy;
07616 }
07617 
07618 #if defined(MBEDTLS_SSL_RENEGOTIATION)
07619 void mbedtls_ssl_conf_renegotiation( mbedtls_ssl_config *conf, int renegotiation )
07620 {
07621     conf->disable_renegotiation  = renegotiation;
07622 }
07623 
07624 void mbedtls_ssl_conf_renegotiation_enforced( mbedtls_ssl_config *conf, int max_records )
07625 {
07626     conf->renego_max_records  = max_records;
07627 }
07628 
07629 void mbedtls_ssl_conf_renegotiation_period( mbedtls_ssl_config *conf,
07630                                    const unsigned char period[8] )
07631 {
07632     memcpy( conf->renego_period , period, 8 );
07633 }
07634 #endif /* MBEDTLS_SSL_RENEGOTIATION */
07635 
07636 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
07637 #if defined(MBEDTLS_SSL_CLI_C)
07638 void mbedtls_ssl_conf_session_tickets( mbedtls_ssl_config *conf, int use_tickets )
07639 {
07640     conf->session_tickets  = use_tickets;
07641 }
07642 #endif
07643 
07644 #if defined(MBEDTLS_SSL_SRV_C)
07645 void mbedtls_ssl_conf_session_tickets_cb( mbedtls_ssl_config *conf,
07646         mbedtls_ssl_ticket_write_t *f_ticket_write,
07647         mbedtls_ssl_ticket_parse_t *f_ticket_parse,
07648         void *p_ticket )
07649 {
07650     conf->f_ticket_write = f_ticket_write;
07651     conf->f_ticket_parse = f_ticket_parse;
07652     conf->p_ticket        = p_ticket;
07653 }
07654 #endif
07655 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
07656 
07657 #if defined(MBEDTLS_SSL_EXPORT_KEYS)
07658 void mbedtls_ssl_conf_export_keys_cb( mbedtls_ssl_config *conf,
07659         mbedtls_ssl_export_keys_t *f_export_keys,
07660         void *p_export_keys )
07661 {
07662     conf->f_export_keys = f_export_keys;
07663     conf->p_export_keys  = p_export_keys;
07664 }
07665 #endif
07666 
07667 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
07668 void mbedtls_ssl_conf_async_private_cb(
07669     mbedtls_ssl_config *conf,
07670     mbedtls_ssl_async_sign_t *f_async_sign,
07671     mbedtls_ssl_async_decrypt_t *f_async_decrypt,
07672     mbedtls_ssl_async_resume_t *f_async_resume,
07673     mbedtls_ssl_async_cancel_t *f_async_cancel,
07674     void *async_config_data )
07675 {
07676     conf->f_async_sign_start  = f_async_sign;
07677     conf->f_async_decrypt_start  = f_async_decrypt;
07678     conf->f_async_resume  = f_async_resume;
07679     conf->f_async_cancel  = f_async_cancel;
07680     conf->p_async_config_data  = async_config_data;
07681 }
07682 
07683 void *mbedtls_ssl_conf_get_async_config_data( const mbedtls_ssl_config *conf )
07684 {
07685     return( conf->p_async_config_data  );
07686 }
07687 
07688 void *mbedtls_ssl_get_async_operation_data( const mbedtls_ssl_context *ssl )
07689 {
07690     if( ssl->handshake == NULL )
07691         return( NULL );
07692     else
07693         return( ssl->handshake->user_async_ctx );
07694 }
07695 
07696 void mbedtls_ssl_set_async_operation_data( mbedtls_ssl_context *ssl,
07697                                  void *ctx )
07698 {
07699     if( ssl->handshake != NULL )
07700         ssl->handshake->user_async_ctx = ctx;
07701 }
07702 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
07703 
07704 /*
07705  * SSL get accessors
07706  */
07707 size_t mbedtls_ssl_get_bytes_avail( const mbedtls_ssl_context *ssl )
07708 {
07709     return( ssl->in_offt == NULL ? 0 : ssl->in_msglen );
07710 }
07711 
07712 int mbedtls_ssl_check_pending( const mbedtls_ssl_context *ssl )
07713 {
07714     /*
07715      * Case A: We're currently holding back
07716      * a message for further processing.
07717      */
07718 
07719     if( ssl->keep_current_message == 1 )
07720     {
07721         MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: record held back for processing" ) );
07722         return( 1 );
07723     }
07724 
07725     /*
07726      * Case B: Further records are pending in the current datagram.
07727      */
07728 
07729 #if defined(MBEDTLS_SSL_PROTO_DTLS)
07730     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
07731         ssl->in_left > ssl->next_record_offset )
07732     {
07733         MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: more records within current datagram" ) );
07734         return( 1 );
07735     }
07736 #endif /* MBEDTLS_SSL_PROTO_DTLS */
07737 
07738     /*
07739      * Case C: A handshake message is being processed.
07740      */
07741 
07742     if( ssl->in_hslen > 0 && ssl->in_hslen < ssl->in_msglen )
07743     {
07744         MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: more handshake messages within current record" ) );
07745         return( 1 );
07746     }
07747 
07748     /*
07749      * Case D: An application data message is being processed
07750      */
07751     if( ssl->in_offt != NULL )
07752     {
07753         MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: application data record is being processed" ) );
07754         return( 1 );
07755     }
07756 
07757     /*
07758      * In all other cases, the rest of the message can be dropped.
07759      * As in ssl_get_next_record, this needs to be adapted if
07760      * we implement support for multiple alerts in single records.
07761      */
07762 
07763     MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: nothing pending" ) );
07764     return( 0 );
07765 }
07766 
07767 uint32_t mbedtls_ssl_get_verify_result( const mbedtls_ssl_context *ssl )
07768 {
07769     if( ssl->session != NULL )
07770         return( ssl->session->verify_result );
07771 
07772     if( ssl->session_negotiate != NULL )
07773         return( ssl->session_negotiate->verify_result );
07774 
07775     return( 0xFFFFFFFF );
07776 }
07777 
07778 const char *mbedtls_ssl_get_ciphersuite( const mbedtls_ssl_context *ssl )
07779 {
07780     if( ssl == NULL || ssl->session == NULL )
07781         return( NULL );
07782 
07783     return mbedtls_ssl_get_ciphersuite_name( ssl->session->ciphersuite );
07784 }
07785 
07786 const char *mbedtls_ssl_get_version( const mbedtls_ssl_context *ssl )
07787 {
07788 #if defined(MBEDTLS_SSL_PROTO_DTLS)
07789     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
07790     {
07791         switch( ssl->minor_ver )
07792         {
07793             case MBEDTLS_SSL_MINOR_VERSION_2:
07794                 return( "DTLSv1.0" );
07795 
07796             case MBEDTLS_SSL_MINOR_VERSION_3:
07797                 return( "DTLSv1.2" );
07798 
07799             default:
07800                 return( "unknown (DTLS)" );
07801         }
07802     }
07803 #endif
07804 
07805     switch( ssl->minor_ver )
07806     {
07807         case MBEDTLS_SSL_MINOR_VERSION_0:
07808             return( "SSLv3.0" );
07809 
07810         case MBEDTLS_SSL_MINOR_VERSION_1:
07811             return( "TLSv1.0" );
07812 
07813         case MBEDTLS_SSL_MINOR_VERSION_2:
07814             return( "TLSv1.1" );
07815 
07816         case MBEDTLS_SSL_MINOR_VERSION_3:
07817             return( "TLSv1.2" );
07818 
07819         default:
07820             return( "unknown" );
07821     }
07822 }
07823 
07824 int mbedtls_ssl_get_record_expansion( const mbedtls_ssl_context *ssl )
07825 {
07826     size_t transform_expansion = 0;
07827     const mbedtls_ssl_transform *transform = ssl->transform_out;
07828     unsigned block_size;
07829 
07830     if( transform == NULL )
07831         return( (int) mbedtls_ssl_hdr_len( ssl ) );
07832 
07833 #if defined(MBEDTLS_ZLIB_SUPPORT)
07834     if( ssl->session_out->compression != MBEDTLS_SSL_COMPRESS_NULL )
07835         return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
07836 #endif
07837 
07838     switch( mbedtls_cipher_get_cipher_mode( &transform->cipher_ctx_enc ) )
07839     {
07840         case MBEDTLS_MODE_GCM:
07841         case MBEDTLS_MODE_CCM:
07842         case MBEDTLS_MODE_CHACHAPOLY:
07843         case MBEDTLS_MODE_STREAM:
07844             transform_expansion = transform->minlen;
07845             break;
07846 
07847         case MBEDTLS_MODE_CBC:
07848 
07849             block_size = mbedtls_cipher_get_block_size(
07850                 &transform->cipher_ctx_enc );
07851 
07852             /* Expansion due to the addition of the MAC. */
07853             transform_expansion += transform->maclen;
07854 
07855             /* Expansion due to the addition of CBC padding;
07856              * Theoretically up to 256 bytes, but we never use
07857              * more than the block size of the underlying cipher. */
07858             transform_expansion += block_size;
07859 
07860             /* For TLS 1.1 or higher, an explicit IV is added
07861              * after the record header. */
07862 #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
07863             if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
07864                 transform_expansion += block_size;
07865 #endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */
07866 
07867             break;
07868 
07869         default:
07870             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
07871             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
07872     }
07873 
07874     return( (int)( mbedtls_ssl_hdr_len( ssl ) + transform_expansion ) );
07875 }
07876 
07877 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
07878 size_t mbedtls_ssl_get_max_frag_len( const mbedtls_ssl_context *ssl )
07879 {
07880     size_t max_len;
07881 
07882     /*
07883      * Assume mfl_code is correct since it was checked when set
07884      */
07885     max_len = ssl_mfl_code_to_length( ssl->conf->mfl_code );
07886 
07887     /* Check if a smaller max length was negotiated */
07888     if( ssl->session_out != NULL &&
07889         ssl_mfl_code_to_length( ssl->session_out->mfl_code ) < max_len )
07890     {
07891         max_len = ssl_mfl_code_to_length( ssl->session_out->mfl_code );
07892     }
07893 
07894     /* During a handshake, use the value being negotiated */
07895     if( ssl->session_negotiate != NULL &&
07896         ssl_mfl_code_to_length( ssl->session_negotiate->mfl_code ) < max_len )
07897     {
07898         max_len = ssl_mfl_code_to_length( ssl->session_negotiate->mfl_code );
07899     }
07900 
07901     return( max_len );
07902 }
07903 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
07904 
07905 #if defined(MBEDTLS_SSL_PROTO_DTLS)
07906 static size_t ssl_get_current_mtu( const mbedtls_ssl_context *ssl )
07907 {
07908     if( ssl->handshake == NULL || ssl->handshake->mtu == 0 )
07909         return( ssl->mtu );
07910 
07911     if( ssl->mtu == 0 )
07912         return( ssl->handshake->mtu );
07913 
07914     return( ssl->mtu < ssl->handshake->mtu ?
07915             ssl->mtu : ssl->handshake->mtu );
07916 }
07917 #endif /* MBEDTLS_SSL_PROTO_DTLS */
07918 
07919 int mbedtls_ssl_get_max_out_record_payload( const mbedtls_ssl_context *ssl )
07920 {
07921     size_t max_len = MBEDTLS_SSL_OUT_CONTENT_LEN;
07922 
07923 #if !defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) && \
07924     !defined(MBEDTLS_SSL_PROTO_DTLS)
07925     (void) ssl;
07926 #endif
07927 
07928 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
07929     const size_t mfl = mbedtls_ssl_get_max_frag_len( ssl );
07930 
07931     if( max_len > mfl )
07932         max_len = mfl;
07933 #endif
07934 
07935 #if defined(MBEDTLS_SSL_PROTO_DTLS)
07936     if( ssl_get_current_mtu( ssl ) != 0 )
07937     {
07938         const size_t mtu = ssl_get_current_mtu( ssl );
07939         const int ret = mbedtls_ssl_get_record_expansion( ssl );
07940         const size_t overhead = (size_t) ret;
07941 
07942         if( ret < 0 )
07943             return( ret );
07944 
07945         if( mtu <= overhead )
07946         {
07947             MBEDTLS_SSL_DEBUG_MSG( 1, ( "MTU too low for record expansion" ) );
07948             return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
07949         }
07950 
07951         if( max_len > mtu - overhead )
07952             max_len = mtu - overhead;
07953     }
07954 #endif /* MBEDTLS_SSL_PROTO_DTLS */
07955 
07956 #if !defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) &&        \
07957     !defined(MBEDTLS_SSL_PROTO_DTLS)
07958     ((void) ssl);
07959 #endif
07960 
07961     return( (int) max_len );
07962 }
07963 
07964 #if defined(MBEDTLS_X509_CRT_PARSE_C)
07965 const mbedtls_x509_crt *mbedtls_ssl_get_peer_cert( const mbedtls_ssl_context *ssl )
07966 {
07967     if( ssl == NULL || ssl->session == NULL )
07968         return( NULL );
07969 
07970     return( ssl->session->peer_cert );
07971 }
07972 #endif /* MBEDTLS_X509_CRT_PARSE_C */
07973 
07974 #if defined(MBEDTLS_SSL_CLI_C)
07975 int mbedtls_ssl_get_session( const mbedtls_ssl_context *ssl, mbedtls_ssl_session *dst )
07976 {
07977     if( ssl == NULL ||
07978         dst == NULL ||
07979         ssl->session == NULL ||
07980         ssl->conf->endpoint != MBEDTLS_SSL_IS_CLIENT )
07981     {
07982         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
07983     }
07984 
07985     return( ssl_session_copy( dst, ssl->session ) );
07986 }
07987 #endif /* MBEDTLS_SSL_CLI_C */
07988 
07989 /*
07990  * Perform a single step of the SSL handshake
07991  */
07992 int mbedtls_ssl_handshake_step( mbedtls_ssl_context *ssl )
07993 {
07994     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
07995 
07996     if( ssl == NULL || ssl->conf == NULL )
07997         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
07998 
07999 #if defined(MBEDTLS_SSL_CLI_C)
08000     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
08001         ret = mbedtls_ssl_handshake_client_step( ssl );
08002 #endif
08003 #if defined(MBEDTLS_SSL_SRV_C)
08004     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
08005         ret = mbedtls_ssl_handshake_server_step( ssl );
08006 #endif
08007 
08008     return( ret );
08009 }
08010 
08011 /*
08012  * Perform the SSL handshake
08013  */
08014 int mbedtls_ssl_handshake( mbedtls_ssl_context *ssl )
08015 {
08016     int ret = 0;
08017 
08018     if( ssl == NULL || ssl->conf == NULL )
08019         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
08020 
08021     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> handshake" ) );
08022 
08023     while( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
08024     {
08025         ret = mbedtls_ssl_handshake_step( ssl );
08026 
08027         if( ret != 0 )
08028             break;
08029     }
08030 
08031     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= handshake" ) );
08032 
08033     return( ret );
08034 }
08035 
08036 #if defined(MBEDTLS_SSL_RENEGOTIATION)
08037 #if defined(MBEDTLS_SSL_SRV_C)
08038 /*
08039  * Write HelloRequest to request renegotiation on server
08040  */
08041 static int ssl_write_hello_request( mbedtls_ssl_context *ssl )
08042 {
08043     int ret;
08044 
08045     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write hello request" ) );
08046 
08047     ssl->out_msglen  = 4;
08048     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
08049     ssl->out_msg[0]  = MBEDTLS_SSL_HS_HELLO_REQUEST;
08050 
08051     if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
08052     {
08053         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
08054         return( ret );
08055     }
08056 
08057     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write hello request" ) );
08058 
08059     return( 0 );
08060 }
08061 #endif /* MBEDTLS_SSL_SRV_C */
08062 
08063 /*
08064  * Actually renegotiate current connection, triggered by either:
08065  * - any side: calling mbedtls_ssl_renegotiate(),
08066  * - client: receiving a HelloRequest during mbedtls_ssl_read(),
08067  * - server: receiving any handshake message on server during mbedtls_ssl_read() after
08068  *   the initial handshake is completed.
08069  * If the handshake doesn't complete due to waiting for I/O, it will continue
08070  * during the next calls to mbedtls_ssl_renegotiate() or mbedtls_ssl_read() respectively.
08071  */
08072 static int ssl_start_renegotiation( mbedtls_ssl_context *ssl )
08073 {
08074     int ret;
08075 
08076     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> renegotiate" ) );
08077 
08078     if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
08079         return( ret );
08080 
08081     /* RFC 6347 4.2.2: "[...] the HelloRequest will have message_seq = 0 and
08082      * the ServerHello will have message_seq = 1" */
08083 #if defined(MBEDTLS_SSL_PROTO_DTLS)
08084     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
08085         ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
08086     {
08087         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
08088             ssl->handshake->out_msg_seq = 1;
08089         else
08090             ssl->handshake->in_msg_seq = 1;
08091     }
08092 #endif
08093 
08094     ssl->state = MBEDTLS_SSL_HELLO_REQUEST;
08095     ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS;
08096 
08097     if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 )
08098     {
08099         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
08100         return( ret );
08101     }
08102 
08103     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= renegotiate" ) );
08104 
08105     return( 0 );
08106 }
08107 
08108 /*
08109  * Renegotiate current connection on client,
08110  * or request renegotiation on server
08111  */
08112 int mbedtls_ssl_renegotiate( mbedtls_ssl_context *ssl )
08113 {
08114     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
08115 
08116     if( ssl == NULL || ssl->conf == NULL )
08117         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
08118 
08119 #if defined(MBEDTLS_SSL_SRV_C)
08120     /* On server, just send the request */
08121     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
08122     {
08123         if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
08124             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
08125 
08126         ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_PENDING;
08127 
08128         /* Did we already try/start sending HelloRequest? */
08129         if( ssl->out_left != 0 )
08130             return( mbedtls_ssl_flush_output( ssl ) );
08131 
08132         return( ssl_write_hello_request( ssl ) );
08133     }
08134 #endif /* MBEDTLS_SSL_SRV_C */
08135 
08136 #if defined(MBEDTLS_SSL_CLI_C)
08137     /*
08138      * On client, either start the renegotiation process or,
08139      * if already in progress, continue the handshake
08140      */
08141     if( ssl->renego_status != MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
08142     {
08143         if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
08144             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
08145 
08146         if( ( ret = ssl_start_renegotiation( ssl ) ) != 0 )
08147         {
08148             MBEDTLS_SSL_DEBUG_RET( 1, "ssl_start_renegotiation", ret );
08149             return( ret );
08150         }
08151     }
08152     else
08153     {
08154         if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 )
08155         {
08156             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
08157             return( ret );
08158         }
08159     }
08160 #endif /* MBEDTLS_SSL_CLI_C */
08161 
08162     return( ret );
08163 }
08164 
08165 /*
08166  * Check record counters and renegotiate if they're above the limit.
08167  */
08168 static int ssl_check_ctr_renegotiate( mbedtls_ssl_context *ssl )
08169 {
08170     size_t ep_len = ssl_ep_len( ssl );
08171     int in_ctr_cmp;
08172     int out_ctr_cmp;
08173 
08174     if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ||
08175         ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING ||
08176         ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED )
08177     {
08178         return( 0 );
08179     }
08180 
08181     in_ctr_cmp = memcmp( ssl->in_ctr + ep_len,
08182                         ssl->conf->renego_period + ep_len, 8 - ep_len );
08183     out_ctr_cmp = memcmp( ssl->cur_out_ctr + ep_len,
08184                           ssl->conf->renego_period + ep_len, 8 - ep_len );
08185 
08186     if( in_ctr_cmp <= 0 && out_ctr_cmp <= 0 )
08187     {
08188         return( 0 );
08189     }
08190 
08191     MBEDTLS_SSL_DEBUG_MSG( 1, ( "record counter limit reached: renegotiate" ) );
08192     return( mbedtls_ssl_renegotiate( ssl ) );
08193 }
08194 #endif /* MBEDTLS_SSL_RENEGOTIATION */
08195 
08196 /*
08197  * Receive application data decrypted from the SSL layer
08198  */
08199 int mbedtls_ssl_read( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len )
08200 {
08201     int ret;
08202     size_t n;
08203 
08204     if( ssl == NULL || ssl->conf == NULL )
08205         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
08206 
08207     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> read" ) );
08208 
08209 #if defined(MBEDTLS_SSL_PROTO_DTLS)
08210     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
08211     {
08212         if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
08213             return( ret );
08214 
08215         if( ssl->handshake != NULL &&
08216             ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING )
08217         {
08218             if( ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 )
08219                 return( ret );
08220         }
08221     }
08222 #endif
08223 
08224     /*
08225      * Check if renegotiation is necessary and/or handshake is
08226      * in process. If yes, perform/continue, and fall through
08227      * if an unexpected packet is received while the client
08228      * is waiting for the ServerHello.
08229      *
08230      * (There is no equivalent to the last condition on
08231      *  the server-side as it is not treated as within
08232      *  a handshake while waiting for the ClientHello
08233      *  after a renegotiation request.)
08234      */
08235 
08236 #if defined(MBEDTLS_SSL_RENEGOTIATION)
08237     ret = ssl_check_ctr_renegotiate( ssl );
08238     if( ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO &&
08239         ret != 0 )
08240     {
08241         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_check_ctr_renegotiate", ret );
08242         return( ret );
08243     }
08244 #endif
08245 
08246     if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
08247     {
08248         ret = mbedtls_ssl_handshake( ssl );
08249         if( ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO &&
08250             ret != 0 )
08251         {
08252             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
08253             return( ret );
08254         }
08255     }
08256 
08257     /* Loop as long as no application data record is available */
08258     while( ssl->in_offt == NULL )
08259     {
08260         /* Start timer if not already running */
08261         if( ssl->f_get_timer != NULL &&
08262             ssl->f_get_timer( ssl->p_timer ) == -1 )
08263         {
08264             ssl_set_timer( ssl, ssl->conf->read_timeout );
08265         }
08266 
08267         if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
08268         {
08269             if( ret == MBEDTLS_ERR_SSL_CONN_EOF )
08270                 return( 0 );
08271 
08272             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
08273             return( ret );
08274         }
08275 
08276         if( ssl->in_msglen  == 0 &&
08277             ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA )
08278         {
08279             /*
08280              * OpenSSL sends empty messages to randomize the IV
08281              */
08282             if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
08283             {
08284                 if( ret == MBEDTLS_ERR_SSL_CONN_EOF )
08285                     return( 0 );
08286 
08287                 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
08288                 return( ret );
08289             }
08290         }
08291 
08292         if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE )
08293         {
08294             MBEDTLS_SSL_DEBUG_MSG( 1, ( "received handshake message" ) );
08295 
08296             /*
08297              * - For client-side, expect SERVER_HELLO_REQUEST.
08298              * - For server-side, expect CLIENT_HELLO.
08299              * - Fail (TLS) or silently drop record (DTLS) in other cases.
08300              */
08301 
08302 #if defined(MBEDTLS_SSL_CLI_C)
08303             if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&
08304                 ( ssl->in_msg[0] != MBEDTLS_SSL_HS_HELLO_REQUEST ||
08305                   ssl->in_hslen  != mbedtls_ssl_hs_hdr_len( ssl ) ) )
08306             {
08307                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake received (not HelloRequest)" ) );
08308 
08309                 /* With DTLS, drop the packet (probably from last handshake) */
08310 #if defined(MBEDTLS_SSL_PROTO_DTLS)
08311                 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
08312                 {
08313                     continue;
08314                 }
08315 #endif
08316                 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
08317             }
08318 #endif /* MBEDTLS_SSL_CLI_C */
08319 
08320 #if defined(MBEDTLS_SSL_SRV_C)
08321             if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
08322                 ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_HELLO )
08323             {
08324                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake received (not ClientHello)" ) );
08325 
08326                 /* With DTLS, drop the packet (probably from last handshake) */
08327 #if defined(MBEDTLS_SSL_PROTO_DTLS)
08328                 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
08329                 {
08330                     continue;
08331                 }
08332 #endif
08333                 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
08334             }
08335 #endif /* MBEDTLS_SSL_SRV_C */
08336 
08337 #if defined(MBEDTLS_SSL_RENEGOTIATION)
08338             /* Determine whether renegotiation attempt should be accepted */
08339             if( ! ( ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED ||
08340                     ( ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
08341                       ssl->conf->allow_legacy_renegotiation ==
08342                                                    MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION ) ) )
08343             {
08344                 /*
08345                  * Accept renegotiation request
08346                  */
08347 
08348                 /* DTLS clients need to know renego is server-initiated */
08349 #if defined(MBEDTLS_SSL_PROTO_DTLS)
08350                 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
08351                     ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
08352                 {
08353                     ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_PENDING;
08354                 }
08355 #endif
08356                 ret = ssl_start_renegotiation( ssl );
08357                 if( ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO &&
08358                     ret != 0 )
08359                 {
08360                     MBEDTLS_SSL_DEBUG_RET( 1, "ssl_start_renegotiation", ret );
08361                     return( ret );
08362                 }
08363             }
08364             else
08365 #endif /* MBEDTLS_SSL_RENEGOTIATION */
08366             {
08367                 /*
08368                  * Refuse renegotiation
08369                  */
08370 
08371                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "refusing renegotiation, sending alert" ) );
08372 
08373 #if defined(MBEDTLS_SSL_PROTO_SSL3)
08374                 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
08375                 {
08376                     /* SSLv3 does not have a "no_renegotiation" warning, so
08377                        we send a fatal alert and abort the connection. */
08378                     mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
08379                                                     MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
08380                     return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
08381                 }
08382                 else
08383 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
08384 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
08385     defined(MBEDTLS_SSL_PROTO_TLS1_2)
08386                 if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 )
08387                 {
08388                     if( ( ret = mbedtls_ssl_send_alert_message( ssl,
08389                                     MBEDTLS_SSL_ALERT_LEVEL_WARNING,
08390                                     MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION ) ) != 0 )
08391                     {
08392                         return( ret );
08393                     }
08394                 }
08395                 else
08396 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 ||
08397           MBEDTLS_SSL_PROTO_TLS1_2 */
08398                 {
08399                     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
08400                     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
08401                 }
08402             }
08403 
08404             /* At this point, we don't know whether the renegotiation has been
08405              * completed or not. The cases to consider are the following:
08406              * 1) The renegotiation is complete. In this case, no new record
08407              *    has been read yet.
08408              * 2) The renegotiation is incomplete because the client received
08409              *    an application data record while awaiting the ServerHello.
08410              * 3) The renegotiation is incomplete because the client received
08411              *    a non-handshake, non-application data message while awaiting
08412              *    the ServerHello.
08413              * In each of these case, looping will be the proper action:
08414              * - For 1), the next iteration will read a new record and check
08415              *   if it's application data.
08416              * - For 2), the loop condition isn't satisfied as application data
08417              *   is present, hence continue is the same as break
08418              * - For 3), the loop condition is satisfied and read_record
08419              *   will re-deliver the message that was held back by the client
08420              *   when expecting the ServerHello.
08421              */
08422             continue;
08423         }
08424 #if defined(MBEDTLS_SSL_RENEGOTIATION)
08425         else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
08426         {
08427             if( ssl->conf->renego_max_records >= 0 )
08428             {
08429                 if( ++ssl->renego_records_seen > ssl->conf->renego_max_records )
08430                 {
08431                     MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation requested, "
08432                                         "but not honored by client" ) );
08433                     return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
08434                 }
08435             }
08436         }
08437 #endif /* MBEDTLS_SSL_RENEGOTIATION */
08438 
08439         /* Fatal and closure alerts handled by mbedtls_ssl_read_record() */
08440         if( ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT )
08441         {
08442             MBEDTLS_SSL_DEBUG_MSG( 2, ( "ignoring non-fatal non-closure alert" ) );
08443             return( MBEDTLS_ERR_SSL_WANT_READ );
08444         }
08445 
08446         if( ssl->in_msgtype != MBEDTLS_SSL_MSG_APPLICATION_DATA )
08447         {
08448             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad application data message" ) );
08449             return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
08450         }
08451 
08452         ssl->in_offt = ssl->in_msg;
08453 
08454         /* We're going to return something now, cancel timer,
08455          * except if handshake (renegotiation) is in progress */
08456         if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )
08457             ssl_set_timer( ssl, 0 );
08458 
08459 #if defined(MBEDTLS_SSL_PROTO_DTLS)
08460         /* If we requested renego but received AppData, resend HelloRequest.
08461          * Do it now, after setting in_offt, to avoid taking this branch
08462          * again if ssl_write_hello_request() returns WANT_WRITE */
08463 #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
08464         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
08465             ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
08466         {
08467             if( ( ret = ssl_resend_hello_request( ssl ) ) != 0 )
08468             {
08469                 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_resend_hello_request", ret );
08470                 return( ret );
08471             }
08472         }
08473 #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
08474 #endif /* MBEDTLS_SSL_PROTO_DTLS */
08475     }
08476 
08477     n = ( len < ssl->in_msglen )
08478         ? len : ssl->in_msglen;
08479 
08480     memcpy( buf, ssl->in_offt, n );
08481     ssl->in_msglen -= n;
08482 
08483     if( ssl->in_msglen == 0 )
08484     {
08485         /* all bytes consumed */
08486         ssl->in_offt = NULL;
08487         ssl->keep_current_message = 0;
08488     }
08489     else
08490     {
08491         /* more data available */
08492         ssl->in_offt += n;
08493     }
08494 
08495     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= read" ) );
08496 
08497     return( (int) n );
08498 }
08499 
08500 /*
08501  * Send application data to be encrypted by the SSL layer, taking care of max
08502  * fragment length and buffer size.
08503  *
08504  * According to RFC 5246 Section 6.2.1:
08505  *
08506  *      Zero-length fragments of Application data MAY be sent as they are
08507  *      potentially useful as a traffic analysis countermeasure.
08508  *
08509  * Therefore, it is possible that the input message length is 0 and the
08510  * corresponding return code is 0 on success.
08511  */
08512 static int ssl_write_real( mbedtls_ssl_context *ssl,
08513                            const unsigned char *buf, size_t len )
08514 {
08515     int ret = mbedtls_ssl_get_max_out_record_payload( ssl );
08516     const size_t max_len = (size_t) ret;
08517 
08518     if( ret < 0 )
08519     {
08520         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_get_max_out_record_payload", ret );
08521         return( ret );
08522     }
08523 
08524     if( len > max_len )
08525     {
08526 #if defined(MBEDTLS_SSL_PROTO_DTLS)
08527         if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
08528         {
08529             MBEDTLS_SSL_DEBUG_MSG( 1, ( "fragment larger than the (negotiated) "
08530                                 "maximum fragment length: %d > %d",
08531                                 len, max_len ) );
08532             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
08533         }
08534         else
08535 #endif
08536             len = max_len;
08537     }
08538 
08539     if( ssl->out_left != 0 )
08540     {
08541         /*
08542          * The user has previously tried to send the data and
08543          * MBEDTLS_ERR_SSL_WANT_WRITE or the message was only partially
08544          * written. In this case, we expect the high-level write function
08545          * (e.g. mbedtls_ssl_write()) to be called with the same parameters
08546          */
08547         if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
08548         {
08549             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flush_output", ret );
08550             return( ret );
08551         }
08552     }
08553     else
08554     {
08555         /*
08556          * The user is trying to send a message the first time, so we need to
08557          * copy the data into the internal buffers and setup the data structure
08558          * to keep track of partial writes
08559          */
08560         ssl->out_msglen  = len;
08561         ssl->out_msgtype = MBEDTLS_SSL_MSG_APPLICATION_DATA;
08562         memcpy( ssl->out_msg, buf, len );
08563 
08564         if( ( ret = mbedtls_ssl_write_record( ssl, SSL_FORCE_FLUSH ) ) != 0 )
08565         {
08566             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
08567             return( ret );
08568         }
08569     }
08570 
08571     return( (int) len );
08572 }
08573 
08574 /*
08575  * Write application data, doing 1/n-1 splitting if necessary.
08576  *
08577  * With non-blocking I/O, ssl_write_real() may return WANT_WRITE,
08578  * then the caller will call us again with the same arguments, so
08579  * remember whether we already did the split or not.
08580  */
08581 #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
08582 static int ssl_write_split( mbedtls_ssl_context *ssl,
08583                             const unsigned char *buf, size_t len )
08584 {
08585     int ret;
08586 
08587     if( ssl->conf->cbc_record_splitting ==
08588             MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED ||
08589         len <= 1 ||
08590         ssl->minor_ver > MBEDTLS_SSL_MINOR_VERSION_1 ||
08591         mbedtls_cipher_get_cipher_mode( &ssl->transform_out->cipher_ctx_enc )
08592                                 != MBEDTLS_MODE_CBC )
08593     {
08594         return( ssl_write_real( ssl, buf, len ) );
08595     }
08596 
08597     if( ssl->split_done == 0 )
08598     {
08599         if( ( ret = ssl_write_real( ssl, buf, 1 ) ) <= 0 )
08600             return( ret );
08601         ssl->split_done = 1;
08602     }
08603 
08604     if( ( ret = ssl_write_real( ssl, buf + 1, len - 1 ) ) <= 0 )
08605         return( ret );
08606     ssl->split_done = 0;
08607 
08608     return( ret + 1 );
08609 }
08610 #endif /* MBEDTLS_SSL_CBC_RECORD_SPLITTING */
08611 
08612 /*
08613  * Write application data (public-facing wrapper)
08614  */
08615 int mbedtls_ssl_write( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len )
08616 {
08617     int ret;
08618 
08619     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write" ) );
08620 
08621     if( ssl == NULL || ssl->conf == NULL )
08622         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
08623 
08624 #if defined(MBEDTLS_SSL_RENEGOTIATION)
08625     if( ( ret = ssl_check_ctr_renegotiate( ssl ) ) != 0 )
08626     {
08627         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_check_ctr_renegotiate", ret );
08628         return( ret );
08629     }
08630 #endif
08631 
08632     if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
08633     {
08634         if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 )
08635         {
08636             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
08637             return( ret );
08638         }
08639     }
08640 
08641 #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
08642     ret = ssl_write_split( ssl, buf, len );
08643 #else
08644     ret = ssl_write_real( ssl, buf, len );
08645 #endif
08646 
08647     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write" ) );
08648 
08649     return( ret );
08650 }
08651 
08652 /*
08653  * Notify the peer that the connection is being closed
08654  */
08655 int mbedtls_ssl_close_notify( mbedtls_ssl_context *ssl )
08656 {
08657     int ret;
08658 
08659     if( ssl == NULL || ssl->conf == NULL )
08660         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
08661 
08662     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write close notify" ) );
08663 
08664     if( ssl->out_left != 0 )
08665         return( mbedtls_ssl_flush_output( ssl ) );
08666 
08667     if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )
08668     {
08669         if( ( ret = mbedtls_ssl_send_alert_message( ssl,
08670                         MBEDTLS_SSL_ALERT_LEVEL_WARNING,
08671                         MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY ) ) != 0 )
08672         {
08673             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_send_alert_message", ret );
08674             return( ret );
08675         }
08676     }
08677 
08678     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write close notify" ) );
08679 
08680     return( 0 );
08681 }
08682 
08683 void mbedtls_ssl_transform_free( mbedtls_ssl_transform *transform )
08684 {
08685     if( transform == NULL )
08686         return;
08687 
08688 #if defined(MBEDTLS_ZLIB_SUPPORT)
08689     deflateEnd( &transform->ctx_deflate );
08690     inflateEnd( &transform->ctx_inflate );
08691 #endif
08692 
08693     mbedtls_cipher_free( &transform->cipher_ctx_enc );
08694     mbedtls_cipher_free( &transform->cipher_ctx_dec );
08695 
08696     mbedtls_md_free( &transform->md_ctx_enc );
08697     mbedtls_md_free( &transform->md_ctx_dec );
08698 
08699     mbedtls_platform_zeroize( transform, sizeof( mbedtls_ssl_transform ) );
08700 }
08701 
08702 #if defined(MBEDTLS_X509_CRT_PARSE_C)
08703 static void ssl_key_cert_free( mbedtls_ssl_key_cert *key_cert )
08704 {
08705     mbedtls_ssl_key_cert *cur = key_cert, *next;
08706 
08707     while( cur != NULL )
08708     {
08709         next = cur->next;
08710         mbedtls_free( cur );
08711         cur = next;
08712     }
08713 }
08714 #endif /* MBEDTLS_X509_CRT_PARSE_C */
08715 
08716 #if defined(MBEDTLS_SSL_PROTO_DTLS)
08717 
08718 static void ssl_buffering_free( mbedtls_ssl_context *ssl )
08719 {
08720     unsigned offset;
08721     mbedtls_ssl_handshake_params * const hs = ssl->handshake;
08722 
08723     if( hs == NULL )
08724         return;
08725 
08726     ssl_free_buffered_record( ssl );
08727 
08728     for( offset = 0; offset < MBEDTLS_SSL_MAX_BUFFERED_HS; offset++ )
08729         ssl_buffering_free_slot( ssl, offset );
08730 }
08731 
08732 static void ssl_buffering_free_slot( mbedtls_ssl_context *ssl,
08733                                      uint8_t slot )
08734 {
08735     mbedtls_ssl_handshake_params * const hs = ssl->handshake;
08736     mbedtls_ssl_hs_buffer * const hs_buf = &hs->buffering.hs[slot];
08737 
08738     if( slot >= MBEDTLS_SSL_MAX_BUFFERED_HS )
08739         return;
08740 
08741     if( hs_buf->is_valid == 1 )
08742     {
08743         hs->buffering.total_bytes_buffered -= hs_buf->data_len;
08744         mbedtls_free( hs_buf->data );
08745         memset( hs_buf, 0, sizeof( mbedtls_ssl_hs_buffer ) );
08746     }
08747 }
08748 
08749 #endif /* MBEDTLS_SSL_PROTO_DTLS */
08750 
08751 void mbedtls_ssl_handshake_free( mbedtls_ssl_context *ssl )
08752 {
08753     mbedtls_ssl_handshake_params *handshake = ssl->handshake;
08754 
08755     if( handshake == NULL )
08756         return;
08757 
08758 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
08759     if( ssl->conf->f_async_cancel != NULL && handshake->async_in_progress != 0 )
08760     {
08761         ssl->conf->f_async_cancel( ssl );
08762         handshake->async_in_progress = 0;
08763     }
08764 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
08765 
08766 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
08767     defined(MBEDTLS_SSL_PROTO_TLS1_1)
08768     mbedtls_md5_free(    &handshake->fin_md5  );
08769     mbedtls_sha1_free(   &handshake->fin_sha1 );
08770 #endif
08771 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
08772 #if defined(MBEDTLS_SHA256_C)
08773     mbedtls_sha256_free(   &handshake->fin_sha256    );
08774 #endif
08775 #if defined(MBEDTLS_SHA512_C)
08776     mbedtls_sha512_free(   &handshake->fin_sha512    );
08777 #endif
08778 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
08779 
08780 #if defined(MBEDTLS_DHM_C)
08781     mbedtls_dhm_free( &handshake->dhm_ctx );
08782 #endif
08783 #if defined(MBEDTLS_ECDH_C)
08784     mbedtls_ecdh_free( &handshake->ecdh_ctx );
08785 #endif
08786 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
08787     mbedtls_ecjpake_free( &handshake->ecjpake_ctx );
08788 #if defined(MBEDTLS_SSL_CLI_C)
08789     mbedtls_free( handshake->ecjpake_cache );
08790     handshake->ecjpake_cache = NULL;
08791     handshake->ecjpake_cache_len = 0;
08792 #endif
08793 #endif
08794 
08795 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
08796     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
08797     /* explicit void pointer cast for buggy MS compiler */
08798     mbedtls_free( (void *) handshake->curves );
08799 #endif
08800 
08801 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
08802     if( handshake->psk != NULL )
08803     {
08804         mbedtls_platform_zeroize( handshake->psk, handshake->psk_len );
08805         mbedtls_free( handshake->psk );
08806     }
08807 #endif
08808 
08809 #if defined(MBEDTLS_X509_CRT_PARSE_C) && \
08810     defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
08811     /*
08812      * Free only the linked list wrapper, not the keys themselves
08813      * since the belong to the SNI callback
08814      */
08815     if( handshake->sni_key_cert != NULL )
08816     {
08817         mbedtls_ssl_key_cert *cur = handshake->sni_key_cert, *next;
08818 
08819         while( cur != NULL )
08820         {
08821             next = cur->next;
08822             mbedtls_free( cur );
08823             cur = next;
08824         }
08825     }
08826 #endif /* MBEDTLS_X509_CRT_PARSE_C && MBEDTLS_SSL_SERVER_NAME_INDICATION */
08827 
08828 #if defined(MBEDTLS_SSL_PROTO_DTLS)
08829     mbedtls_free( handshake->verify_cookie );
08830     ssl_flight_free( handshake->flight );
08831     ssl_buffering_free( ssl );
08832 #endif
08833 
08834     mbedtls_platform_zeroize( handshake,
08835                               sizeof( mbedtls_ssl_handshake_params ) );
08836 }
08837 
08838 void mbedtls_ssl_session_free( mbedtls_ssl_session *session )
08839 {
08840     if( session == NULL )
08841         return;
08842 
08843 #if defined(MBEDTLS_X509_CRT_PARSE_C)
08844     if( session->peer_cert != NULL )
08845     {
08846         mbedtls_x509_crt_free( session->peer_cert );
08847         mbedtls_free( session->peer_cert );
08848     }
08849 #endif
08850 
08851 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
08852     mbedtls_free( session->ticket );
08853 #endif
08854 
08855     mbedtls_platform_zeroize( session, sizeof( mbedtls_ssl_session ) );
08856 }
08857 
08858 /*
08859  * Free an SSL context
08860  */
08861 void mbedtls_ssl_free( mbedtls_ssl_context *ssl )
08862 {
08863     if( ssl == NULL )
08864         return;
08865 
08866     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> free" ) );
08867 
08868     if( ssl->out_buf != NULL )
08869     {
08870         mbedtls_platform_zeroize( ssl->out_buf, MBEDTLS_SSL_OUT_BUFFER_LEN );
08871         mbedtls_free( ssl->out_buf );
08872     }
08873 
08874     if( ssl->in_buf != NULL )
08875     {
08876         mbedtls_platform_zeroize( ssl->in_buf, MBEDTLS_SSL_IN_BUFFER_LEN );
08877         mbedtls_free( ssl->in_buf );
08878     }
08879 
08880 #if defined(MBEDTLS_ZLIB_SUPPORT)
08881     if( ssl->compress_buf != NULL )
08882     {
08883         mbedtls_platform_zeroize( ssl->compress_buf, MBEDTLS_SSL_COMPRESS_BUFFER_LEN );
08884         mbedtls_free( ssl->compress_buf );
08885     }
08886 #endif
08887 
08888     if( ssl->transform )
08889     {
08890         mbedtls_ssl_transform_free( ssl->transform );
08891         mbedtls_free( ssl->transform );
08892     }
08893 
08894     if( ssl->handshake )
08895     {
08896         mbedtls_ssl_handshake_free( ssl );
08897         mbedtls_ssl_transform_free( ssl->transform_negotiate );
08898         mbedtls_ssl_session_free( ssl->session_negotiate );
08899 
08900         mbedtls_free( ssl->handshake );
08901         mbedtls_free( ssl->transform_negotiate );
08902         mbedtls_free( ssl->session_negotiate );
08903     }
08904 
08905     if( ssl->session )
08906     {
08907         mbedtls_ssl_session_free( ssl->session );
08908         mbedtls_free( ssl->session );
08909     }
08910 
08911 #if defined(MBEDTLS_X509_CRT_PARSE_C)
08912     if( ssl->hostname != NULL )
08913     {
08914         mbedtls_platform_zeroize( ssl->hostname, strlen( ssl->hostname ) );
08915         mbedtls_free( ssl->hostname );
08916     }
08917 #endif
08918 
08919 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
08920     if( mbedtls_ssl_hw_record_finish != NULL )
08921     {
08922         MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_finish()" ) );
08923         mbedtls_ssl_hw_record_finish( ssl );
08924     }
08925 #endif
08926 
08927 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
08928     mbedtls_free( ssl->cli_id );
08929 #endif
08930 
08931     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= free" ) );
08932 
08933     /* Actually clear after last debug message */
08934     mbedtls_platform_zeroize( ssl, sizeof( mbedtls_ssl_context ) );
08935 }
08936 
08937 /*
08938  * Initialze mbedtls_ssl_config
08939  */
08940 void mbedtls_ssl_config_init( mbedtls_ssl_config *conf )
08941 {
08942     memset( conf, 0, sizeof( mbedtls_ssl_config ) );
08943 }
08944 
08945 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
08946 static int ssl_preset_default_hashes[] = {
08947 #if defined(MBEDTLS_SHA512_C)
08948     MBEDTLS_MD_SHA512,
08949     MBEDTLS_MD_SHA384,
08950 #endif
08951 #if defined(MBEDTLS_SHA256_C)
08952     MBEDTLS_MD_SHA256,
08953     MBEDTLS_MD_SHA224,
08954 #endif
08955 #if defined(MBEDTLS_SHA1_C) && defined(MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_KEY_EXCHANGE)
08956     MBEDTLS_MD_SHA1,
08957 #endif
08958     MBEDTLS_MD_NONE
08959 };
08960 #endif
08961 
08962 static int ssl_preset_suiteb_ciphersuites[] = {
08963     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
08964     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
08965     0
08966 };
08967 
08968 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
08969 static int ssl_preset_suiteb_hashes[] = {
08970     MBEDTLS_MD_SHA256,
08971     MBEDTLS_MD_SHA384,
08972     MBEDTLS_MD_NONE
08973 };
08974 #endif
08975 
08976 #if defined(MBEDTLS_ECP_C)
08977 static mbedtls_ecp_group_id ssl_preset_suiteb_curves[] = {
08978     MBEDTLS_ECP_DP_SECP256R1,
08979     MBEDTLS_ECP_DP_SECP384R1,
08980     MBEDTLS_ECP_DP_NONE
08981 };
08982 #endif
08983 
08984 /*
08985  * Load default in mbedtls_ssl_config
08986  */
08987 int mbedtls_ssl_config_defaults( mbedtls_ssl_config *conf,
08988                                  int endpoint, int transport, int preset )
08989 {
08990 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
08991     int ret;
08992 #endif
08993 
08994     /* Use the functions here so that they are covered in tests,
08995      * but otherwise access member directly for efficiency */
08996     mbedtls_ssl_conf_endpoint( conf, endpoint );
08997     mbedtls_ssl_conf_transport( conf, transport );
08998 
08999     /*
09000      * Things that are common to all presets
09001      */
09002 #if defined(MBEDTLS_SSL_CLI_C)
09003     if( endpoint == MBEDTLS_SSL_IS_CLIENT )
09004     {
09005         conf->authmode  = MBEDTLS_SSL_VERIFY_REQUIRED;
09006 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
09007         conf->session_tickets  = MBEDTLS_SSL_SESSION_TICKETS_ENABLED;
09008 #endif
09009     }
09010 #endif
09011 
09012 #if defined(MBEDTLS_ARC4_C)
09013     conf->arc4_disabled  = MBEDTLS_SSL_ARC4_DISABLED;
09014 #endif
09015 
09016 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
09017     conf->encrypt_then_mac  = MBEDTLS_SSL_ETM_ENABLED;
09018 #endif
09019 
09020 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
09021     conf->extended_ms  = MBEDTLS_SSL_EXTENDED_MS_ENABLED;
09022 #endif
09023 
09024 #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
09025     conf->cbc_record_splitting  = MBEDTLS_SSL_CBC_RECORD_SPLITTING_ENABLED;
09026 #endif
09027 
09028 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
09029     conf->f_cookie_write = ssl_cookie_write_dummy;
09030     conf->f_cookie_check = ssl_cookie_check_dummy;
09031 #endif
09032 
09033 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
09034     conf->anti_replay  = MBEDTLS_SSL_ANTI_REPLAY_ENABLED;
09035 #endif
09036 
09037 #if defined(MBEDTLS_SSL_SRV_C)
09038     conf->cert_req_ca_list  = MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED;
09039 #endif
09040 
09041 #if defined(MBEDTLS_SSL_PROTO_DTLS)
09042     conf->hs_timeout_min  = MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MIN;
09043     conf->hs_timeout_max  = MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MAX;
09044 #endif
09045 
09046 #if defined(MBEDTLS_SSL_RENEGOTIATION)
09047     conf->renego_max_records  = MBEDTLS_SSL_RENEGO_MAX_RECORDS_DEFAULT;
09048     memset( conf->renego_period ,     0x00, 2 );
09049     memset( conf->renego_period  + 2, 0xFF, 6 );
09050 #endif
09051 
09052 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
09053             if( endpoint == MBEDTLS_SSL_IS_SERVER )
09054             {
09055                 const unsigned char dhm_p[] =
09056                     MBEDTLS_DHM_RFC3526_MODP_2048_P_BIN;
09057                 const unsigned char dhm_g[] =
09058                     MBEDTLS_DHM_RFC3526_MODP_2048_G_BIN;
09059 
09060                 if ( ( ret = mbedtls_ssl_conf_dh_param_bin( conf,
09061                                                dhm_p, sizeof( dhm_p ),
09062                                                dhm_g, sizeof( dhm_g ) ) ) != 0 )
09063                 {
09064                     return( ret );
09065                 }
09066             }
09067 #endif
09068 
09069     /*
09070      * Preset-specific defaults
09071      */
09072     switch( preset )
09073     {
09074         /*
09075          * NSA Suite B
09076          */
09077         case MBEDTLS_SSL_PRESET_SUITEB:
09078             conf->min_major_ver  = MBEDTLS_SSL_MAJOR_VERSION_3;
09079             conf->min_minor_ver  = MBEDTLS_SSL_MINOR_VERSION_3; /* TLS 1.2 */
09080             conf->max_major_ver  = MBEDTLS_SSL_MAX_MAJOR_VERSION;
09081             conf->max_minor_ver  = MBEDTLS_SSL_MAX_MINOR_VERSION;
09082 
09083             conf->ciphersuite_list [MBEDTLS_SSL_MINOR_VERSION_0] =
09084             conf->ciphersuite_list [MBEDTLS_SSL_MINOR_VERSION_1] =
09085             conf->ciphersuite_list [MBEDTLS_SSL_MINOR_VERSION_2] =
09086             conf->ciphersuite_list [MBEDTLS_SSL_MINOR_VERSION_3] =
09087                                    ssl_preset_suiteb_ciphersuites;
09088 
09089 #if defined(MBEDTLS_X509_CRT_PARSE_C)
09090             conf->cert_profile  = &mbedtls_x509_crt_profile_suiteb;
09091 #endif
09092 
09093 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
09094             conf->sig_hashes  = ssl_preset_suiteb_hashes;
09095 #endif
09096 
09097 #if defined(MBEDTLS_ECP_C)
09098             conf->curve_list  = ssl_preset_suiteb_curves;
09099 #endif
09100             break;
09101 
09102         /*
09103          * Default
09104          */
09105         default:
09106             conf->min_major_ver  = ( MBEDTLS_SSL_MIN_MAJOR_VERSION >
09107                                     MBEDTLS_SSL_MIN_VALID_MAJOR_VERSION ) ?
09108                                     MBEDTLS_SSL_MIN_MAJOR_VERSION :
09109                                     MBEDTLS_SSL_MIN_VALID_MAJOR_VERSION;
09110             conf->min_minor_ver  = ( MBEDTLS_SSL_MIN_MINOR_VERSION >
09111                                     MBEDTLS_SSL_MIN_VALID_MINOR_VERSION ) ?
09112                                     MBEDTLS_SSL_MIN_MINOR_VERSION :
09113                                     MBEDTLS_SSL_MIN_VALID_MINOR_VERSION;
09114             conf->max_major_ver  = MBEDTLS_SSL_MAX_MAJOR_VERSION;
09115             conf->max_minor_ver  = MBEDTLS_SSL_MAX_MINOR_VERSION;
09116 
09117 #if defined(MBEDTLS_SSL_PROTO_DTLS)
09118             if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
09119                 conf->min_minor_ver  = MBEDTLS_SSL_MINOR_VERSION_2;
09120 #endif
09121 
09122             conf->ciphersuite_list [MBEDTLS_SSL_MINOR_VERSION_0] =
09123             conf->ciphersuite_list [MBEDTLS_SSL_MINOR_VERSION_1] =
09124             conf->ciphersuite_list [MBEDTLS_SSL_MINOR_VERSION_2] =
09125             conf->ciphersuite_list [MBEDTLS_SSL_MINOR_VERSION_3] =
09126                                    mbedtls_ssl_list_ciphersuites();
09127 
09128 #if defined(MBEDTLS_X509_CRT_PARSE_C)
09129             conf->cert_profile  = &mbedtls_x509_crt_profile_default;
09130 #endif
09131 
09132 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
09133             conf->sig_hashes  = ssl_preset_default_hashes;
09134 #endif
09135 
09136 #if defined(MBEDTLS_ECP_C)
09137             conf->curve_list  = mbedtls_ecp_grp_id_list();
09138 #endif
09139 
09140 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C)
09141             conf->dhm_min_bitlen  = 1024;
09142 #endif
09143     }
09144 
09145     return( 0 );
09146 }
09147 
09148 /*
09149  * Free mbedtls_ssl_config
09150  */
09151 void mbedtls_ssl_config_free( mbedtls_ssl_config *conf )
09152 {
09153 #if defined(MBEDTLS_DHM_C)
09154     mbedtls_mpi_free( &conf->dhm_P  );
09155     mbedtls_mpi_free( &conf->dhm_G  );
09156 #endif
09157 
09158 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
09159     if( conf->psk  != NULL )
09160     {
09161         mbedtls_platform_zeroize( conf->psk , conf->psk_len  );
09162         mbedtls_free( conf->psk  );
09163         conf->psk  = NULL;
09164         conf->psk_len  = 0;
09165     }
09166 
09167     if( conf->psk_identity  != NULL )
09168     {
09169         mbedtls_platform_zeroize( conf->psk_identity , conf->psk_identity_len  );
09170         mbedtls_free( conf->psk_identity  );
09171         conf->psk_identity  = NULL;
09172         conf->psk_identity_len  = 0;
09173     }
09174 #endif
09175 
09176 #if defined(MBEDTLS_X509_CRT_PARSE_C)
09177     ssl_key_cert_free( conf->key_cert  );
09178 #endif
09179 
09180     mbedtls_platform_zeroize( conf, sizeof( mbedtls_ssl_config ) );
09181 }
09182 
09183 #if defined(MBEDTLS_PK_C) && \
09184     ( defined(MBEDTLS_RSA_C) || defined(MBEDTLS_ECDSA_C) )
09185 /*
09186  * Convert between MBEDTLS_PK_XXX and SSL_SIG_XXX
09187  */
09188 unsigned char mbedtls_ssl_sig_from_pk( mbedtls_pk_context *pk )
09189 {
09190 #if defined(MBEDTLS_RSA_C)
09191     if( mbedtls_pk_can_do( pk, MBEDTLS_PK_RSA ) )
09192         return( MBEDTLS_SSL_SIG_RSA );
09193 #endif
09194 #if defined(MBEDTLS_ECDSA_C)
09195     if( mbedtls_pk_can_do( pk, MBEDTLS_PK_ECDSA ) )
09196         return( MBEDTLS_SSL_SIG_ECDSA );
09197 #endif
09198     return( MBEDTLS_SSL_SIG_ANON );
09199 }
09200 
09201 unsigned char mbedtls_ssl_sig_from_pk_alg( mbedtls_pk_type_t type )
09202 {
09203     switch( type ) {
09204         case MBEDTLS_PK_RSA:
09205             return( MBEDTLS_SSL_SIG_RSA );
09206         case MBEDTLS_PK_ECDSA:
09207         case MBEDTLS_PK_ECKEY:
09208             return( MBEDTLS_SSL_SIG_ECDSA );
09209         default:
09210             return( MBEDTLS_SSL_SIG_ANON );
09211     }
09212 }
09213 
09214 mbedtls_pk_type_t mbedtls_ssl_pk_alg_from_sig( unsigned char sig )
09215 {
09216     switch( sig )
09217     {
09218 #if defined(MBEDTLS_RSA_C)
09219         case MBEDTLS_SSL_SIG_RSA:
09220             return( MBEDTLS_PK_RSA );
09221 #endif
09222 #if defined(MBEDTLS_ECDSA_C)
09223         case MBEDTLS_SSL_SIG_ECDSA:
09224             return( MBEDTLS_PK_ECDSA );
09225 #endif
09226         default:
09227             return( MBEDTLS_PK_NONE );
09228     }
09229 }
09230 #endif /* MBEDTLS_PK_C && ( MBEDTLS_RSA_C || MBEDTLS_ECDSA_C ) */
09231 
09232 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
09233     defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
09234 
09235 /* Find an entry in a signature-hash set matching a given hash algorithm. */
09236 mbedtls_md_type_t mbedtls_ssl_sig_hash_set_find( mbedtls_ssl_sig_hash_set_t *set,
09237                                                  mbedtls_pk_type_t sig_alg )
09238 {
09239     switch( sig_alg )
09240     {
09241         case MBEDTLS_PK_RSA:
09242             return( set->rsa );
09243         case MBEDTLS_PK_ECDSA:
09244             return( set->ecdsa );
09245         default:
09246             return( MBEDTLS_MD_NONE );
09247     }
09248 }
09249 
09250 /* Add a signature-hash-pair to a signature-hash set */
09251 void mbedtls_ssl_sig_hash_set_add( mbedtls_ssl_sig_hash_set_t *set,
09252                                    mbedtls_pk_type_t sig_alg,
09253                                    mbedtls_md_type_t md_alg )
09254 {
09255     switch( sig_alg )
09256     {
09257         case MBEDTLS_PK_RSA:
09258             if( set->rsa == MBEDTLS_MD_NONE )
09259                 set->rsa = md_alg;
09260             break;
09261 
09262         case MBEDTLS_PK_ECDSA:
09263             if( set->ecdsa == MBEDTLS_MD_NONE )
09264                 set->ecdsa = md_alg;
09265             break;
09266 
09267         default:
09268             break;
09269     }
09270 }
09271 
09272 /* Allow exactly one hash algorithm for each signature. */
09273 void mbedtls_ssl_sig_hash_set_const_hash( mbedtls_ssl_sig_hash_set_t *set,
09274                                           mbedtls_md_type_t md_alg )
09275 {
09276     set->rsa   = md_alg;
09277     set->ecdsa = md_alg;
09278 }
09279 
09280 #endif /* MBEDTLS_SSL_PROTO_TLS1_2) &&
09281           MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
09282 
09283 /*
09284  * Convert from MBEDTLS_SSL_HASH_XXX to MBEDTLS_MD_XXX
09285  */
09286 mbedtls_md_type_t mbedtls_ssl_md_alg_from_hash( unsigned char hash )
09287 {
09288     switch( hash )
09289     {
09290 #if defined(MBEDTLS_MD5_C)
09291         case MBEDTLS_SSL_HASH_MD5:
09292             return( MBEDTLS_MD_MD5 );
09293 #endif
09294 #if defined(MBEDTLS_SHA1_C)
09295         case MBEDTLS_SSL_HASH_SHA1:
09296             return( MBEDTLS_MD_SHA1 );
09297 #endif
09298 #if defined(MBEDTLS_SHA256_C)
09299         case MBEDTLS_SSL_HASH_SHA224:
09300             return( MBEDTLS_MD_SHA224 );
09301         case MBEDTLS_SSL_HASH_SHA256:
09302             return( MBEDTLS_MD_SHA256 );
09303 #endif
09304 #if defined(MBEDTLS_SHA512_C)
09305         case MBEDTLS_SSL_HASH_SHA384:
09306             return( MBEDTLS_MD_SHA384 );
09307         case MBEDTLS_SSL_HASH_SHA512:
09308             return( MBEDTLS_MD_SHA512 );
09309 #endif
09310         default:
09311             return( MBEDTLS_MD_NONE );
09312     }
09313 }
09314 
09315 /*
09316  * Convert from MBEDTLS_MD_XXX to MBEDTLS_SSL_HASH_XXX
09317  */
09318 unsigned char mbedtls_ssl_hash_from_md_alg( int md )
09319 {
09320     switch( md )
09321     {
09322 #if defined(MBEDTLS_MD5_C)
09323         case MBEDTLS_MD_MD5:
09324             return( MBEDTLS_SSL_HASH_MD5 );
09325 #endif
09326 #if defined(MBEDTLS_SHA1_C)
09327         case MBEDTLS_MD_SHA1:
09328             return( MBEDTLS_SSL_HASH_SHA1 );
09329 #endif
09330 #if defined(MBEDTLS_SHA256_C)
09331         case MBEDTLS_MD_SHA224:
09332             return( MBEDTLS_SSL_HASH_SHA224 );
09333         case MBEDTLS_MD_SHA256:
09334             return( MBEDTLS_SSL_HASH_SHA256 );
09335 #endif
09336 #if defined(MBEDTLS_SHA512_C)
09337         case MBEDTLS_MD_SHA384:
09338             return( MBEDTLS_SSL_HASH_SHA384 );
09339         case MBEDTLS_MD_SHA512:
09340             return( MBEDTLS_SSL_HASH_SHA512 );
09341 #endif
09342         default:
09343             return( MBEDTLS_SSL_HASH_NONE );
09344     }
09345 }
09346 
09347 #if defined(MBEDTLS_ECP_C)
09348 /*
09349  * Check if a curve proposed by the peer is in our list.
09350  * Return 0 if we're willing to use it, -1 otherwise.
09351  */
09352 int mbedtls_ssl_check_curve( const mbedtls_ssl_context *ssl, mbedtls_ecp_group_id grp_id )
09353 {
09354     const mbedtls_ecp_group_id *gid;
09355 
09356     if( ssl->conf->curve_list == NULL )
09357         return( -1 );
09358 
09359     for( gid = ssl->conf->curve_list; *gid != MBEDTLS_ECP_DP_NONE; gid++ )
09360         if( *gid == grp_id )
09361             return( 0 );
09362 
09363     return( -1 );
09364 }
09365 #endif /* MBEDTLS_ECP_C */
09366 
09367 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
09368 /*
09369  * Check if a hash proposed by the peer is in our list.
09370  * Return 0 if we're willing to use it, -1 otherwise.
09371  */
09372 int mbedtls_ssl_check_sig_hash( const mbedtls_ssl_context *ssl,
09373                                 mbedtls_md_type_t md )
09374 {
09375     const int *cur;
09376 
09377     if( ssl->conf->sig_hashes == NULL )
09378         return( -1 );
09379 
09380     for( cur = ssl->conf->sig_hashes; *cur != MBEDTLS_MD_NONE; cur++ )
09381         if( *cur == (int) md )
09382             return( 0 );
09383 
09384     return( -1 );
09385 }
09386 #endif /* MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
09387 
09388 #if defined(MBEDTLS_X509_CRT_PARSE_C)
09389 int mbedtls_ssl_check_cert_usage( const mbedtls_x509_crt *cert,
09390                           const mbedtls_ssl_ciphersuite_t *ciphersuite,
09391                           int cert_endpoint,
09392                           uint32_t *flags )
09393 {
09394     int ret = 0;
09395 #if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
09396     int usage = 0;
09397 #endif
09398 #if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
09399     const char *ext_oid;
09400     size_t ext_len;
09401 #endif
09402 
09403 #if !defined(MBEDTLS_X509_CHECK_KEY_USAGE) &&          \
09404     !defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
09405     ((void) cert);
09406     ((void) cert_endpoint);
09407     ((void) flags);
09408 #endif
09409 
09410 #if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
09411     if( cert_endpoint == MBEDTLS_SSL_IS_SERVER )
09412     {
09413         /* Server part of the key exchange */
09414         switch( ciphersuite->key_exchange )
09415         {
09416             case MBEDTLS_KEY_EXCHANGE_RSA:
09417             case MBEDTLS_KEY_EXCHANGE_RSA_PSK:
09418                 usage = MBEDTLS_X509_KU_KEY_ENCIPHERMENT;
09419                 break;
09420 
09421             case MBEDTLS_KEY_EXCHANGE_DHE_RSA:
09422             case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
09423             case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
09424                 usage = MBEDTLS_X509_KU_DIGITAL_SIGNATURE;
09425                 break;
09426 
09427             case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:
09428             case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:
09429                 usage = MBEDTLS_X509_KU_KEY_AGREEMENT;
09430                 break;
09431 
09432             /* Don't use default: we want warnings when adding new values */
09433             case MBEDTLS_KEY_EXCHANGE_NONE:
09434             case MBEDTLS_KEY_EXCHANGE_PSK:
09435             case MBEDTLS_KEY_EXCHANGE_DHE_PSK:
09436             case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK:
09437             case MBEDTLS_KEY_EXCHANGE_ECJPAKE:
09438                 usage = 0;
09439         }
09440     }
09441     else
09442     {
09443         /* Client auth: we only implement rsa_sign and mbedtls_ecdsa_sign for now */
09444         usage = MBEDTLS_X509_KU_DIGITAL_SIGNATURE;
09445     }
09446 
09447     if( mbedtls_x509_crt_check_key_usage( cert, usage ) != 0 )
09448     {
09449         *flags |= MBEDTLS_X509_BADCERT_KEY_USAGE;
09450         ret = -1;
09451     }
09452 #else
09453     ((void) ciphersuite);
09454 #endif /* MBEDTLS_X509_CHECK_KEY_USAGE */
09455 
09456 #if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
09457     if( cert_endpoint == MBEDTLS_SSL_IS_SERVER )
09458     {
09459         ext_oid = MBEDTLS_OID_SERVER_AUTH;
09460         ext_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_SERVER_AUTH );
09461     }
09462     else
09463     {
09464         ext_oid = MBEDTLS_OID_CLIENT_AUTH;
09465         ext_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_CLIENT_AUTH );
09466     }
09467 
09468     if( mbedtls_x509_crt_check_extended_key_usage( cert, ext_oid, ext_len ) != 0 )
09469     {
09470         *flags |= MBEDTLS_X509_BADCERT_EXT_KEY_USAGE;
09471         ret = -1;
09472     }
09473 #endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE */
09474 
09475     return( ret );
09476 }
09477 #endif /* MBEDTLS_X509_CRT_PARSE_C */
09478 
09479 /*
09480  * Convert version numbers to/from wire format
09481  * and, for DTLS, to/from TLS equivalent.
09482  *
09483  * For TLS this is the identity.
09484  * For DTLS, use 1's complement (v -> 255 - v, and then map as follows:
09485  * 1.0 <-> 3.2      (DTLS 1.0 is based on TLS 1.1)
09486  * 1.x <-> 3.x+1    for x != 0 (DTLS 1.2 based on TLS 1.2)
09487  */
09488 void mbedtls_ssl_write_version( int major, int minor, int transport,
09489                         unsigned char ver[2] )
09490 {
09491 #if defined(MBEDTLS_SSL_PROTO_DTLS)
09492     if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
09493     {
09494         if( minor == MBEDTLS_SSL_MINOR_VERSION_2 )
09495             --minor; /* DTLS 1.0 stored as TLS 1.1 internally */
09496 
09497         ver[0] = (unsigned char)( 255 - ( major - 2 ) );
09498         ver[1] = (unsigned char)( 255 - ( minor - 1 ) );
09499     }
09500     else
09501 #else
09502     ((void) transport);
09503 #endif
09504     {
09505         ver[0] = (unsigned char) major;
09506         ver[1] = (unsigned char) minor;
09507     }
09508 }
09509 
09510 void mbedtls_ssl_read_version( int *major, int *minor, int transport,
09511                        const unsigned char ver[2] )
09512 {
09513 #if defined(MBEDTLS_SSL_PROTO_DTLS)
09514     if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
09515     {
09516         *major = 255 - ver[0] + 2;
09517         *minor = 255 - ver[1] + 1;
09518 
09519         if( *minor == MBEDTLS_SSL_MINOR_VERSION_1 )
09520             ++*minor; /* DTLS 1.0 stored as TLS 1.1 internally */
09521     }
09522     else
09523 #else
09524     ((void) transport);
09525 #endif
09526     {
09527         *major = ver[0];
09528         *minor = ver[1];
09529     }
09530 }
09531 
09532 int mbedtls_ssl_set_calc_verify_md( mbedtls_ssl_context *ssl, int md )
09533 {
09534 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
09535     if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
09536         return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
09537 
09538     switch( md )
09539     {
09540 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
09541 #if defined(MBEDTLS_MD5_C)
09542         case MBEDTLS_SSL_HASH_MD5:
09543             return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
09544 #endif
09545 #if defined(MBEDTLS_SHA1_C)
09546         case MBEDTLS_SSL_HASH_SHA1:
09547             ssl->handshake->calc_verify = ssl_calc_verify_tls;
09548             break;
09549 #endif
09550 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
09551 #if defined(MBEDTLS_SHA512_C)
09552         case MBEDTLS_SSL_HASH_SHA384:
09553             ssl->handshake->calc_verify = ssl_calc_verify_tls_sha384;
09554             break;
09555 #endif
09556 #if defined(MBEDTLS_SHA256_C)
09557         case MBEDTLS_SSL_HASH_SHA256:
09558             ssl->handshake->calc_verify = ssl_calc_verify_tls_sha256;
09559             break;
09560 #endif
09561         default:
09562             return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
09563     }
09564 
09565     return 0;
09566 #else /* !MBEDTLS_SSL_PROTO_TLS1_2 */
09567     (void) ssl;
09568     (void) md;
09569 
09570     return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
09571 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
09572 }
09573 
09574 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
09575     defined(MBEDTLS_SSL_PROTO_TLS1_1)
09576 int mbedtls_ssl_get_key_exchange_md_ssl_tls( mbedtls_ssl_context *ssl,
09577                                         unsigned char *output,
09578                                         unsigned char *data, size_t data_len )
09579 {
09580     int ret = 0;
09581     mbedtls_md5_context mbedtls_md5;
09582     mbedtls_sha1_context mbedtls_sha1;
09583 
09584     mbedtls_md5_init( &mbedtls_md5 );
09585     mbedtls_sha1_init( &mbedtls_sha1 );
09586 
09587     /*
09588      * digitally-signed struct {
09589      *     opaque md5_hash[16];
09590      *     opaque sha_hash[20];
09591      * };
09592      *
09593      * md5_hash
09594      *     MD5(ClientHello.random + ServerHello.random
09595      *                            + ServerParams);
09596      * sha_hash
09597      *     SHA(ClientHello.random + ServerHello.random
09598      *                            + ServerParams);
09599      */
09600     if( ( ret = mbedtls_md5_starts_ret( &mbedtls_md5 ) ) != 0 )
09601     {
09602         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md5_starts_ret", ret );
09603         goto exit;
09604     }
09605     if( ( ret = mbedtls_md5_update_ret( &mbedtls_md5,
09606                                         ssl->handshake->randbytes, 64 ) ) != 0 )
09607     {
09608         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md5_update_ret", ret );
09609         goto exit;
09610     }
09611     if( ( ret = mbedtls_md5_update_ret( &mbedtls_md5, data, data_len ) ) != 0 )
09612     {
09613         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md5_update_ret", ret );
09614         goto exit;
09615     }
09616     if( ( ret = mbedtls_md5_finish_ret( &mbedtls_md5, output ) ) != 0 )
09617     {
09618         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md5_finish_ret", ret );
09619         goto exit;
09620     }
09621 
09622     if( ( ret = mbedtls_sha1_starts_ret( &mbedtls_sha1 ) ) != 0 )
09623     {
09624         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha1_starts_ret", ret );
09625         goto exit;
09626     }
09627     if( ( ret = mbedtls_sha1_update_ret( &mbedtls_sha1,
09628                                          ssl->handshake->randbytes, 64 ) ) != 0 )
09629     {
09630         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha1_update_ret", ret );
09631         goto exit;
09632     }
09633     if( ( ret = mbedtls_sha1_update_ret( &mbedtls_sha1, data,
09634                                          data_len ) ) != 0 )
09635     {
09636         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha1_update_ret", ret );
09637         goto exit;
09638     }
09639     if( ( ret = mbedtls_sha1_finish_ret( &mbedtls_sha1,
09640                                          output + 16 ) ) != 0 )
09641     {
09642         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha1_finish_ret", ret );
09643         goto exit;
09644     }
09645 
09646 exit:
09647     mbedtls_md5_free( &mbedtls_md5 );
09648     mbedtls_sha1_free( &mbedtls_sha1 );
09649 
09650     if( ret != 0 )
09651         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
09652                                         MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
09653 
09654     return( ret );
09655 
09656 }
09657 #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
09658           MBEDTLS_SSL_PROTO_TLS1_1 */
09659 
09660 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
09661     defined(MBEDTLS_SSL_PROTO_TLS1_2)
09662 int mbedtls_ssl_get_key_exchange_md_tls1_2( mbedtls_ssl_context *ssl,
09663                                             unsigned char *hash, size_t *hashlen,
09664                                             unsigned char *data, size_t data_len,
09665                                             mbedtls_md_type_t md_alg )
09666 {
09667     int ret = 0;
09668     mbedtls_md_context_t ctx;
09669     const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type( md_alg );
09670     *hashlen = mbedtls_md_get_size( md_info );
09671 
09672     mbedtls_md_init( &ctx );
09673 
09674     /*
09675      * digitally-signed struct {
09676      *     opaque client_random[32];
09677      *     opaque server_random[32];
09678      *     ServerDHParams params;
09679      * };
09680      */
09681     if( ( ret = mbedtls_md_setup( &ctx, md_info, 0 ) ) != 0 )
09682     {
09683         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_setup", ret );
09684         goto exit;
09685     }
09686     if( ( ret = mbedtls_md_starts( &ctx ) ) != 0 )
09687     {
09688         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_starts", ret );
09689         goto exit;
09690     }
09691     if( ( ret = mbedtls_md_update( &ctx, ssl->handshake->randbytes, 64 ) ) != 0 )
09692     {
09693         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_update", ret );
09694         goto exit;
09695     }
09696     if( ( ret = mbedtls_md_update( &ctx, data, data_len ) ) != 0 )
09697     {
09698         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_update", ret );
09699         goto exit;
09700     }
09701     if( ( ret = mbedtls_md_finish( &ctx, hash ) ) != 0 )
09702     {
09703         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_finish", ret );
09704         goto exit;
09705     }
09706 
09707 exit:
09708     mbedtls_md_free( &ctx );
09709 
09710     if( ret != 0 )
09711         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
09712                                         MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
09713 
09714     return( ret );
09715 }
09716 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
09717           MBEDTLS_SSL_PROTO_TLS1_2 */
09718 
09719 #endif /* MBEDTLS_SSL_TLS_C */