Subversion Repositories Kolibri OS

Rev

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

  1. /*
  2.  *  SSLv3/TLSv1 shared functions
  3.  *
  4.  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
  5.  *  SPDX-License-Identifier: GPL-2.0
  6.  *
  7.  *  This program is free software; you can redistribute it and/or modify
  8.  *  it under the terms of the GNU General Public License as published by
  9.  *  the Free Software Foundation; either version 2 of the License, or
  10.  *  (at your option) any later version.
  11.  *
  12.  *  This program is distributed in the hope that it will be useful,
  13.  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  14.  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  15.  *  GNU General Public License for more details.
  16.  *
  17.  *  You should have received a copy of the GNU General Public License along
  18.  *  with this program; if not, write to the Free Software Foundation, Inc.,
  19.  *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  20.  *
  21.  *  This file is part of mbed TLS (https://tls.mbed.org)
  22.  */
  23. /*
  24.  *  The SSL 3.0 specification was drafted by Netscape in 1996,
  25.  *  and became an IETF standard in 1999.
  26.  *
  27.  *  http://wp.netscape.com/eng/ssl3/
  28.  *  http://www.ietf.org/rfc/rfc2246.txt
  29.  *  http://www.ietf.org/rfc/rfc4346.txt
  30.  */
  31.  
  32. #if !defined(MBEDTLS_CONFIG_FILE)
  33. #include "mbedtls/config.h"
  34. #else
  35. #include MBEDTLS_CONFIG_FILE
  36. #endif
  37.  
  38. #if defined(MBEDTLS_SSL_TLS_C)
  39.  
  40. #if defined(MBEDTLS_PLATFORM_C)
  41. #include "mbedtls/platform.h"
  42. #else
  43. #include <stdlib.h>
  44. #define mbedtls_calloc    calloc
  45. #define mbedtls_free      free
  46. #endif
  47.  
  48. #include "mbedtls/debug.h"
  49. #include "mbedtls/ssl.h"
  50. #include "mbedtls/ssl_internal.h"
  51. #include "mbedtls/platform_util.h"
  52.  
  53. #include <string.h>
  54.  
  55. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  56. #include "mbedtls/oid.h"
  57. #endif
  58.  
  59. static void ssl_reset_in_out_pointers( mbedtls_ssl_context *ssl );
  60. static uint32_t ssl_get_hs_total_len( mbedtls_ssl_context const *ssl );
  61.  
  62. /* Length of the "epoch" field in the record header */
  63. static inline size_t ssl_ep_len( const mbedtls_ssl_context *ssl )
  64. {
  65. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  66.     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  67.         return( 2 );
  68. #else
  69.     ((void) ssl);
  70. #endif
  71.     return( 0 );
  72. }
  73.  
  74. /*
  75.  * Start a timer.
  76.  * Passing millisecs = 0 cancels a running timer.
  77.  */
  78. static void ssl_set_timer( mbedtls_ssl_context *ssl, uint32_t millisecs )
  79. {
  80.     if( ssl->f_set_timer == NULL )
  81.         return;
  82.  
  83.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "set_timer to %d ms", (int) millisecs ) );
  84.     ssl->f_set_timer( ssl->p_timer, millisecs / 4, millisecs );
  85. }
  86.  
  87. /*
  88.  * Return -1 is timer is expired, 0 if it isn't.
  89.  */
  90. static int ssl_check_timer( mbedtls_ssl_context *ssl )
  91. {
  92.     if( ssl->f_get_timer == NULL )
  93.         return( 0 );
  94.  
  95.     if( ssl->f_get_timer( ssl->p_timer ) == 2 )
  96.     {
  97.         MBEDTLS_SSL_DEBUG_MSG( 3, ( "timer expired" ) );
  98.         return( -1 );
  99.     }
  100.  
  101.     return( 0 );
  102. }
  103.  
  104. static void ssl_update_out_pointers( mbedtls_ssl_context *ssl,
  105.                                      mbedtls_ssl_transform *transform );
  106. static void ssl_update_in_pointers( mbedtls_ssl_context *ssl,
  107.                                     mbedtls_ssl_transform *transform );
  108.  
  109. #define SSL_DONT_FORCE_FLUSH 0
  110. #define SSL_FORCE_FLUSH      1
  111.  
  112. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  113.  
  114. /* Forward declarations for functions related to message buffering. */
  115. static void ssl_buffering_free( mbedtls_ssl_context *ssl );
  116. static void ssl_buffering_free_slot( mbedtls_ssl_context *ssl,
  117.                                      uint8_t slot );
  118. static void ssl_free_buffered_record( mbedtls_ssl_context *ssl );
  119. static int ssl_load_buffered_message( mbedtls_ssl_context *ssl );
  120. static int ssl_load_buffered_record( mbedtls_ssl_context *ssl );
  121. static int ssl_buffer_message( mbedtls_ssl_context *ssl );
  122. static int ssl_buffer_future_record( mbedtls_ssl_context *ssl );
  123. static int ssl_next_record_is_in_datagram( mbedtls_ssl_context *ssl );
  124.  
  125. static size_t ssl_get_current_mtu( const mbedtls_ssl_context *ssl );
  126. static size_t ssl_get_maximum_datagram_size( mbedtls_ssl_context const *ssl )
  127. {
  128.     size_t mtu = ssl_get_current_mtu( ssl );
  129.  
  130.     if( mtu != 0 && mtu < MBEDTLS_SSL_OUT_BUFFER_LEN )
  131.         return( mtu );
  132.  
  133.     return( MBEDTLS_SSL_OUT_BUFFER_LEN );
  134. }
  135.  
  136. static int ssl_get_remaining_space_in_datagram( mbedtls_ssl_context const *ssl )
  137. {
  138.     size_t const bytes_written = ssl->out_left;
  139.     size_t const mtu           = ssl_get_maximum_datagram_size( ssl );
  140.  
  141.     /* Double-check that the write-index hasn't gone
  142.      * past what we can transmit in a single datagram. */
  143.     if( bytes_written > mtu )
  144.     {
  145.         /* Should never happen... */
  146.         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  147.     }
  148.  
  149.     return( (int) ( mtu - bytes_written ) );
  150. }
  151.  
  152. static int ssl_get_remaining_payload_in_datagram( mbedtls_ssl_context const *ssl )
  153. {
  154.     int ret;
  155.     size_t remaining, expansion;
  156.     size_t max_len = MBEDTLS_SSL_OUT_CONTENT_LEN;
  157.  
  158. #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
  159.     const size_t mfl = mbedtls_ssl_get_max_frag_len( ssl );
  160.  
  161.     if( max_len > mfl )
  162.         max_len = mfl;
  163.  
  164.     /* By the standard (RFC 6066 Sect. 4), the MFL extension
  165.      * only limits the maximum record payload size, so in theory
  166.      * we would be allowed to pack multiple records of payload size
  167.      * MFL into a single datagram. However, this would mean that there's
  168.      * no way to explicitly communicate MTU restrictions to the peer.
  169.      *
  170.      * The following reduction of max_len makes sure that we never
  171.      * write datagrams larger than MFL + Record Expansion Overhead.
  172.      */
  173.     if( max_len <= ssl->out_left )
  174.         return( 0 );
  175.  
  176.     max_len -= ssl->out_left;
  177. #endif
  178.  
  179.     ret = ssl_get_remaining_space_in_datagram( ssl );
  180.     if( ret < 0 )
  181.         return( ret );
  182.     remaining = (size_t) ret;
  183.  
  184.     ret = mbedtls_ssl_get_record_expansion( ssl );
  185.     if( ret < 0 )
  186.         return( ret );
  187.     expansion = (size_t) ret;
  188.  
  189.     if( remaining <= expansion )
  190.         return( 0 );
  191.  
  192.     remaining -= expansion;
  193.     if( remaining >= max_len )
  194.         remaining = max_len;
  195.  
  196.     return( (int) remaining );
  197. }
  198.  
  199. /*
  200.  * Double the retransmit timeout value, within the allowed range,
  201.  * returning -1 if the maximum value has already been reached.
  202.  */
  203. static int ssl_double_retransmit_timeout( mbedtls_ssl_context *ssl )
  204. {
  205.     uint32_t new_timeout;
  206.  
  207.     if( ssl->handshake->retransmit_timeout >= ssl->conf->hs_timeout_max )
  208.         return( -1 );
  209.  
  210.     /* Implement the final paragraph of RFC 6347 section 4.1.1.1
  211.      * in the following way: after the initial transmission and a first
  212.      * retransmission, back off to a temporary estimated MTU of 508 bytes.
  213.      * This value is guaranteed to be deliverable (if not guaranteed to be
  214.      * delivered) of any compliant IPv4 (and IPv6) network, and should work
  215.      * on most non-IP stacks too. */
  216.     if( ssl->handshake->retransmit_timeout != ssl->conf->hs_timeout_min )
  217.     {
  218.         ssl->handshake->mtu = 508;
  219.         MBEDTLS_SSL_DEBUG_MSG( 2, ( "mtu autoreduction to %d bytes", ssl->handshake->mtu ) );
  220.     }
  221.  
  222.     new_timeout = 2 * ssl->handshake->retransmit_timeout;
  223.  
  224.     /* Avoid arithmetic overflow and range overflow */
  225.     if( new_timeout < ssl->handshake->retransmit_timeout ||
  226.         new_timeout > ssl->conf->hs_timeout_max )
  227.     {
  228.         new_timeout = ssl->conf->hs_timeout_max;
  229.     }
  230.  
  231.     ssl->handshake->retransmit_timeout = new_timeout;
  232.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "update timeout value to %d millisecs",
  233.                         ssl->handshake->retransmit_timeout ) );
  234.  
  235.     return( 0 );
  236. }
  237.  
  238. static void ssl_reset_retransmit_timeout( mbedtls_ssl_context *ssl )
  239. {
  240.     ssl->handshake->retransmit_timeout = ssl->conf->hs_timeout_min;
  241.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "update timeout value to %d millisecs",
  242.                         ssl->handshake->retransmit_timeout ) );
  243. }
  244. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  245.  
  246. #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
  247. /*
  248.  * Convert max_fragment_length codes to length.
  249.  * RFC 6066 says:
  250.  *    enum{
  251.  *        2^9(1), 2^10(2), 2^11(3), 2^12(4), (255)
  252.  *    } MaxFragmentLength;
  253.  * and we add 0 -> extension unused
  254.  */
  255. static unsigned int ssl_mfl_code_to_length( int mfl )
  256. {
  257.     switch( mfl )
  258.     {
  259.     case MBEDTLS_SSL_MAX_FRAG_LEN_NONE:
  260.         return ( MBEDTLS_TLS_EXT_ADV_CONTENT_LEN );
  261.     case MBEDTLS_SSL_MAX_FRAG_LEN_512:
  262.         return 512;
  263.     case MBEDTLS_SSL_MAX_FRAG_LEN_1024:
  264.         return 1024;
  265.     case MBEDTLS_SSL_MAX_FRAG_LEN_2048:
  266.         return 2048;
  267.     case MBEDTLS_SSL_MAX_FRAG_LEN_4096:
  268.         return 4096;
  269.     default:
  270.         return ( MBEDTLS_TLS_EXT_ADV_CONTENT_LEN );
  271.     }
  272. }
  273. #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
  274.  
  275. #if defined(MBEDTLS_SSL_CLI_C)
  276. static int ssl_session_copy( mbedtls_ssl_session *dst, const mbedtls_ssl_session *src )
  277. {
  278.     mbedtls_ssl_session_free( dst );
  279.     memcpy( dst, src, sizeof( mbedtls_ssl_session ) );
  280.  
  281. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  282.     if( src->peer_cert != NULL )
  283.     {
  284.         int ret;
  285.  
  286.         dst->peer_cert = mbedtls_calloc( 1, sizeof(mbedtls_x509_crt) );
  287.         if( dst->peer_cert == NULL )
  288.             return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
  289.  
  290.         mbedtls_x509_crt_init( dst->peer_cert );
  291.  
  292.         if( ( ret = mbedtls_x509_crt_parse_der( dst->peer_cert, src->peer_cert->raw.p,
  293.                                         src->peer_cert->raw.len ) ) != 0 )
  294.         {
  295.             mbedtls_free( dst->peer_cert );
  296.             dst->peer_cert = NULL;
  297.             return( ret );
  298.         }
  299.     }
  300. #endif /* MBEDTLS_X509_CRT_PARSE_C */
  301.  
  302. #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
  303.     if( src->ticket != NULL )
  304.     {
  305.         dst->ticket = mbedtls_calloc( 1, src->ticket_len );
  306.         if( dst->ticket == NULL )
  307.             return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
  308.  
  309.         memcpy( dst->ticket, src->ticket, src->ticket_len );
  310.     }
  311. #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */
  312.  
  313.     return( 0 );
  314. }
  315. #endif /* MBEDTLS_SSL_CLI_C */
  316.  
  317. #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
  318. int (*mbedtls_ssl_hw_record_init)( mbedtls_ssl_context *ssl,
  319.                      const unsigned char *key_enc, const unsigned char *key_dec,
  320.                      size_t keylen,
  321.                      const unsigned char *iv_enc,  const unsigned char *iv_dec,
  322.                      size_t ivlen,
  323.                      const unsigned char *mac_enc, const unsigned char *mac_dec,
  324.                      size_t maclen ) = NULL;
  325. int (*mbedtls_ssl_hw_record_activate)( mbedtls_ssl_context *ssl, int direction) = NULL;
  326. int (*mbedtls_ssl_hw_record_reset)( mbedtls_ssl_context *ssl ) = NULL;
  327. int (*mbedtls_ssl_hw_record_write)( mbedtls_ssl_context *ssl ) = NULL;
  328. int (*mbedtls_ssl_hw_record_read)( mbedtls_ssl_context *ssl ) = NULL;
  329. int (*mbedtls_ssl_hw_record_finish)( mbedtls_ssl_context *ssl ) = NULL;
  330. #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
  331.  
  332. /*
  333.  * Key material generation
  334.  */
  335. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  336. static int ssl3_prf( const unsigned char *secret, size_t slen,
  337.                      const char *label,
  338.                      const unsigned char *random, size_t rlen,
  339.                      unsigned char *dstbuf, size_t dlen )
  340. {
  341.     int ret = 0;
  342.     size_t i;
  343.     mbedtls_md5_context md5;
  344.     mbedtls_sha1_context sha1;
  345.     unsigned char padding[16];
  346.     unsigned char sha1sum[20];
  347.     ((void)label);
  348.  
  349.     mbedtls_md5_init(  &md5  );
  350.     mbedtls_sha1_init( &sha1 );
  351.  
  352.     /*
  353.      *  SSLv3:
  354.      *    block =
  355.      *      MD5( secret + SHA1( 'A'    + secret + random ) ) +
  356.      *      MD5( secret + SHA1( 'BB'   + secret + random ) ) +
  357.      *      MD5( secret + SHA1( 'CCC'  + secret + random ) ) +
  358.      *      ...
  359.      */
  360.     for( i = 0; i < dlen / 16; i++ )
  361.     {
  362.         memset( padding, (unsigned char) ('A' + i), 1 + i );
  363.  
  364.         if( ( ret = mbedtls_sha1_starts_ret( &sha1 ) ) != 0 )
  365.             goto exit;
  366.         if( ( ret = mbedtls_sha1_update_ret( &sha1, padding, 1 + i ) ) != 0 )
  367.             goto exit;
  368.         if( ( ret = mbedtls_sha1_update_ret( &sha1, secret, slen ) ) != 0 )
  369.             goto exit;
  370.         if( ( ret = mbedtls_sha1_update_ret( &sha1, random, rlen ) ) != 0 )
  371.             goto exit;
  372.         if( ( ret = mbedtls_sha1_finish_ret( &sha1, sha1sum ) ) != 0 )
  373.             goto exit;
  374.  
  375.         if( ( ret = mbedtls_md5_starts_ret( &md5 ) ) != 0 )
  376.             goto exit;
  377.         if( ( ret = mbedtls_md5_update_ret( &md5, secret, slen ) ) != 0 )
  378.             goto exit;
  379.         if( ( ret = mbedtls_md5_update_ret( &md5, sha1sum, 20 ) ) != 0 )
  380.             goto exit;
  381.         if( ( ret = mbedtls_md5_finish_ret( &md5, dstbuf + i * 16 ) ) != 0 )
  382.             goto exit;
  383.     }
  384.  
  385. exit:
  386.     mbedtls_md5_free(  &md5  );
  387.     mbedtls_sha1_free( &sha1 );
  388.  
  389.     mbedtls_platform_zeroize( padding, sizeof( padding ) );
  390.     mbedtls_platform_zeroize( sha1sum, sizeof( sha1sum ) );
  391.  
  392.     return( ret );
  393. }
  394. #endif /* MBEDTLS_SSL_PROTO_SSL3 */
  395.  
  396. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
  397. static int tls1_prf( const unsigned char *secret, size_t slen,
  398.                      const char *label,
  399.                      const unsigned char *random, size_t rlen,
  400.                      unsigned char *dstbuf, size_t dlen )
  401. {
  402.     size_t nb, hs;
  403.     size_t i, j, k;
  404.     const unsigned char *S1, *S2;
  405.     unsigned char tmp[128];
  406.     unsigned char h_i[20];
  407.     const mbedtls_md_info_t *md_info;
  408.     mbedtls_md_context_t md_ctx;
  409.     int ret;
  410.  
  411.     mbedtls_md_init( &md_ctx );
  412.  
  413.     if( sizeof( tmp ) < 20 + strlen( label ) + rlen )
  414.         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  415.  
  416.     hs = ( slen + 1 ) / 2;
  417.     S1 = secret;
  418.     S2 = secret + slen - hs;
  419.  
  420.     nb = strlen( label );
  421.     memcpy( tmp + 20, label, nb );
  422.     memcpy( tmp + 20 + nb, random, rlen );
  423.     nb += rlen;
  424.  
  425.     /*
  426.      * First compute P_md5(secret,label+random)[0..dlen]
  427.      */
  428.     if( ( md_info = mbedtls_md_info_from_type( MBEDTLS_MD_MD5 ) ) == NULL )
  429.         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  430.  
  431.     if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )
  432.         return( ret );
  433.  
  434.     mbedtls_md_hmac_starts( &md_ctx, S1, hs );
  435.     mbedtls_md_hmac_update( &md_ctx, tmp + 20, nb );
  436.     mbedtls_md_hmac_finish( &md_ctx, 4 + tmp );
  437.  
  438.     for( i = 0; i < dlen; i += 16 )
  439.     {
  440.         mbedtls_md_hmac_reset ( &md_ctx );
  441.         mbedtls_md_hmac_update( &md_ctx, 4 + tmp, 16 + nb );
  442.         mbedtls_md_hmac_finish( &md_ctx, h_i );
  443.  
  444.         mbedtls_md_hmac_reset ( &md_ctx );
  445.         mbedtls_md_hmac_update( &md_ctx, 4 + tmp, 16 );
  446.         mbedtls_md_hmac_finish( &md_ctx, 4 + tmp );
  447.  
  448.         k = ( i + 16 > dlen ) ? dlen % 16 : 16;
  449.  
  450.         for( j = 0; j < k; j++ )
  451.             dstbuf[i + j]  = h_i[j];
  452.     }
  453.  
  454.     mbedtls_md_free( &md_ctx );
  455.  
  456.     /*
  457.      * XOR out with P_sha1(secret,label+random)[0..dlen]
  458.      */
  459.     if( ( md_info = mbedtls_md_info_from_type( MBEDTLS_MD_SHA1 ) ) == NULL )
  460.         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  461.  
  462.     if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )
  463.         return( ret );
  464.  
  465.     mbedtls_md_hmac_starts( &md_ctx, S2, hs );
  466.     mbedtls_md_hmac_update( &md_ctx, tmp + 20, nb );
  467.     mbedtls_md_hmac_finish( &md_ctx, tmp );
  468.  
  469.     for( i = 0; i < dlen; i += 20 )
  470.     {
  471.         mbedtls_md_hmac_reset ( &md_ctx );
  472.         mbedtls_md_hmac_update( &md_ctx, tmp, 20 + nb );
  473.         mbedtls_md_hmac_finish( &md_ctx, h_i );
  474.  
  475.         mbedtls_md_hmac_reset ( &md_ctx );
  476.         mbedtls_md_hmac_update( &md_ctx, tmp, 20 );
  477.         mbedtls_md_hmac_finish( &md_ctx, tmp );
  478.  
  479.         k = ( i + 20 > dlen ) ? dlen % 20 : 20;
  480.  
  481.         for( j = 0; j < k; j++ )
  482.             dstbuf[i + j] = (unsigned char)( dstbuf[i + j] ^ h_i[j] );
  483.     }
  484.  
  485.     mbedtls_md_free( &md_ctx );
  486.  
  487.     mbedtls_platform_zeroize( tmp, sizeof( tmp ) );
  488.     mbedtls_platform_zeroize( h_i, sizeof( h_i ) );
  489.  
  490.     return( 0 );
  491. }
  492. #endif /* MBEDTLS_SSL_PROTO_TLS1) || MBEDTLS_SSL_PROTO_TLS1_1 */
  493.  
  494. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  495. static int tls_prf_generic( mbedtls_md_type_t md_type,
  496.                             const unsigned char *secret, size_t slen,
  497.                             const char *label,
  498.                             const unsigned char *random, size_t rlen,
  499.                             unsigned char *dstbuf, size_t dlen )
  500. {
  501.     size_t nb;
  502.     size_t i, j, k, md_len;
  503.     unsigned char tmp[128];
  504.     unsigned char h_i[MBEDTLS_MD_MAX_SIZE];
  505.     const mbedtls_md_info_t *md_info;
  506.     mbedtls_md_context_t md_ctx;
  507.     int ret;
  508.  
  509.     mbedtls_md_init( &md_ctx );
  510.  
  511.     if( ( md_info = mbedtls_md_info_from_type( md_type ) ) == NULL )
  512.         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  513.  
  514.     md_len = mbedtls_md_get_size( md_info );
  515.  
  516.     if( sizeof( tmp ) < md_len + strlen( label ) + rlen )
  517.         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  518.  
  519.     nb = strlen( label );
  520.     memcpy( tmp + md_len, label, nb );
  521.     memcpy( tmp + md_len + nb, random, rlen );
  522.     nb += rlen;
  523.  
  524.     /*
  525.      * Compute P_<hash>(secret, label + random)[0..dlen]
  526.      */
  527.     if ( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )
  528.         return( ret );
  529.  
  530.     mbedtls_md_hmac_starts( &md_ctx, secret, slen );
  531.     mbedtls_md_hmac_update( &md_ctx, tmp + md_len, nb );
  532.     mbedtls_md_hmac_finish( &md_ctx, tmp );
  533.  
  534.     for( i = 0; i < dlen; i += md_len )
  535.     {
  536.         mbedtls_md_hmac_reset ( &md_ctx );
  537.         mbedtls_md_hmac_update( &md_ctx, tmp, md_len + nb );
  538.         mbedtls_md_hmac_finish( &md_ctx, h_i );
  539.  
  540.         mbedtls_md_hmac_reset ( &md_ctx );
  541.         mbedtls_md_hmac_update( &md_ctx, tmp, md_len );
  542.         mbedtls_md_hmac_finish( &md_ctx, tmp );
  543.  
  544.         k = ( i + md_len > dlen ) ? dlen % md_len : md_len;
  545.  
  546.         for( j = 0; j < k; j++ )
  547.             dstbuf[i + j]  = h_i[j];
  548.     }
  549.  
  550.     mbedtls_md_free( &md_ctx );
  551.  
  552.     mbedtls_platform_zeroize( tmp, sizeof( tmp ) );
  553.     mbedtls_platform_zeroize( h_i, sizeof( h_i ) );
  554.  
  555.     return( 0 );
  556. }
  557.  
  558. #if defined(MBEDTLS_SHA256_C)
  559. static int tls_prf_sha256( const unsigned char *secret, size_t slen,
  560.                            const char *label,
  561.                            const unsigned char *random, size_t rlen,
  562.                            unsigned char *dstbuf, size_t dlen )
  563. {
  564.     return( tls_prf_generic( MBEDTLS_MD_SHA256, secret, slen,
  565.                              label, random, rlen, dstbuf, dlen ) );
  566. }
  567. #endif /* MBEDTLS_SHA256_C */
  568.  
  569. #if defined(MBEDTLS_SHA512_C)
  570. static int tls_prf_sha384( const unsigned char *secret, size_t slen,
  571.                            const char *label,
  572.                            const unsigned char *random, size_t rlen,
  573.                            unsigned char *dstbuf, size_t dlen )
  574. {
  575.     return( tls_prf_generic( MBEDTLS_MD_SHA384, secret, slen,
  576.                              label, random, rlen, dstbuf, dlen ) );
  577. }
  578. #endif /* MBEDTLS_SHA512_C */
  579. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  580.  
  581. static void ssl_update_checksum_start( mbedtls_ssl_context *, const unsigned char *, size_t );
  582.  
  583. #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
  584.     defined(MBEDTLS_SSL_PROTO_TLS1_1)
  585. static void ssl_update_checksum_md5sha1( mbedtls_ssl_context *, const unsigned char *, size_t );
  586. #endif
  587.  
  588. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  589. static void ssl_calc_verify_ssl( mbedtls_ssl_context *, unsigned char * );
  590. static void ssl_calc_finished_ssl( mbedtls_ssl_context *, unsigned char *, int );
  591. #endif
  592.  
  593. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
  594. static void ssl_calc_verify_tls( mbedtls_ssl_context *, unsigned char * );
  595. static void ssl_calc_finished_tls( mbedtls_ssl_context *, unsigned char *, int );
  596. #endif
  597.  
  598. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  599. #if defined(MBEDTLS_SHA256_C)
  600. static void ssl_update_checksum_sha256( mbedtls_ssl_context *, const unsigned char *, size_t );
  601. static void ssl_calc_verify_tls_sha256( mbedtls_ssl_context *,unsigned char * );
  602. static void ssl_calc_finished_tls_sha256( mbedtls_ssl_context *,unsigned char *, int );
  603. #endif
  604.  
  605. #if defined(MBEDTLS_SHA512_C)
  606. static void ssl_update_checksum_sha384( mbedtls_ssl_context *, const unsigned char *, size_t );
  607. static void ssl_calc_verify_tls_sha384( mbedtls_ssl_context *, unsigned char * );
  608. static void ssl_calc_finished_tls_sha384( mbedtls_ssl_context *, unsigned char *, int );
  609. #endif
  610. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  611.  
  612. int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl )
  613. {
  614.     int ret = 0;
  615.     unsigned char tmp[64];
  616.     unsigned char keyblk[256];
  617.     unsigned char *key1;
  618.     unsigned char *key2;
  619.     unsigned char *mac_enc;
  620.     unsigned char *mac_dec;
  621.     size_t mac_key_len;
  622.     size_t iv_copy_len;
  623.     const mbedtls_cipher_info_t *cipher_info;
  624.     const mbedtls_md_info_t *md_info;
  625.  
  626.     mbedtls_ssl_session *session = ssl->session_negotiate;
  627.     mbedtls_ssl_transform *transform = ssl->transform_negotiate;
  628.     mbedtls_ssl_handshake_params *handshake = ssl->handshake;
  629.  
  630.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> derive keys" ) );
  631.  
  632.     cipher_info = mbedtls_cipher_info_from_type( transform->ciphersuite_info->cipher );
  633.     if( cipher_info == NULL )
  634.     {
  635.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "cipher info for %d not found",
  636.                             transform->ciphersuite_info->cipher ) );
  637.         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  638.     }
  639.  
  640.     md_info = mbedtls_md_info_from_type( transform->ciphersuite_info->mac );
  641.     if( md_info == NULL )
  642.     {
  643.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "mbedtls_md info for %d not found",
  644.                             transform->ciphersuite_info->mac ) );
  645.         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  646.     }
  647.  
  648.     /*
  649.      * Set appropriate PRF function and other SSL / TLS / TLS1.2 functions
  650.      */
  651. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  652.     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
  653.     {
  654.         handshake->tls_prf = ssl3_prf;
  655.         handshake->calc_verify = ssl_calc_verify_ssl;
  656.         handshake->calc_finished = ssl_calc_finished_ssl;
  657.     }
  658.     else
  659. #endif
  660. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
  661.     if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 )
  662.     {
  663.         handshake->tls_prf = tls1_prf;
  664.         handshake->calc_verify = ssl_calc_verify_tls;
  665.         handshake->calc_finished = ssl_calc_finished_tls;
  666.     }
  667.     else
  668. #endif
  669. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  670. #if defined(MBEDTLS_SHA512_C)
  671.     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 &&
  672.         transform->ciphersuite_info->mac == MBEDTLS_MD_SHA384 )
  673.     {
  674.         handshake->tls_prf = tls_prf_sha384;
  675.         handshake->calc_verify = ssl_calc_verify_tls_sha384;
  676.         handshake->calc_finished = ssl_calc_finished_tls_sha384;
  677.     }
  678.     else
  679. #endif
  680. #if defined(MBEDTLS_SHA256_C)
  681.     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
  682.     {
  683.         handshake->tls_prf = tls_prf_sha256;
  684.         handshake->calc_verify = ssl_calc_verify_tls_sha256;
  685.         handshake->calc_finished = ssl_calc_finished_tls_sha256;
  686.     }
  687.     else
  688. #endif
  689. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  690.     {
  691.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  692.         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  693.     }
  694.  
  695.     /*
  696.      * SSLv3:
  697.      *   master =
  698.      *     MD5( premaster + SHA1( 'A'   + premaster + randbytes ) ) +
  699.      *     MD5( premaster + SHA1( 'BB'  + premaster + randbytes ) ) +
  700.      *     MD5( premaster + SHA1( 'CCC' + premaster + randbytes ) )
  701.      *
  702.      * TLSv1+:
  703.      *   master = PRF( premaster, "master secret", randbytes )[0..47]
  704.      */
  705.     if( handshake->resume == 0 )
  706.     {
  707.         MBEDTLS_SSL_DEBUG_BUF( 3, "premaster secret", handshake->premaster,
  708.                        handshake->pmslen );
  709.  
  710. #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
  711.         if( ssl->handshake->extended_ms == MBEDTLS_SSL_EXTENDED_MS_ENABLED )
  712.         {
  713.             unsigned char session_hash[48];
  714.             size_t hash_len;
  715.  
  716.             MBEDTLS_SSL_DEBUG_MSG( 3, ( "using extended master secret" ) );
  717.  
  718.             ssl->handshake->calc_verify( ssl, session_hash );
  719.  
  720. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  721.             if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
  722.             {
  723. #if defined(MBEDTLS_SHA512_C)
  724.                 if( ssl->transform_negotiate->ciphersuite_info->mac ==
  725.                     MBEDTLS_MD_SHA384 )
  726.                 {
  727.                     hash_len = 48;
  728.                 }
  729.                 else
  730. #endif
  731.                     hash_len = 32;
  732.             }
  733.             else
  734. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  735.                 hash_len = 36;
  736.  
  737.             MBEDTLS_SSL_DEBUG_BUF( 3, "session hash", session_hash, hash_len );
  738.  
  739.             ret = handshake->tls_prf( handshake->premaster, handshake->pmslen,
  740.                                       "extended master secret",
  741.                                       session_hash, hash_len,
  742.                                       session->master, 48 );
  743.             if( ret != 0 )
  744.             {
  745.                 MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret );
  746.                 return( ret );
  747.             }
  748.  
  749.         }
  750.         else
  751. #endif
  752.         ret = handshake->tls_prf( handshake->premaster, handshake->pmslen,
  753.                                   "master secret",
  754.                                   handshake->randbytes, 64,
  755.                                   session->master, 48 );
  756.         if( ret != 0 )
  757.         {
  758.             MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret );
  759.             return( ret );
  760.         }
  761.  
  762.         mbedtls_platform_zeroize( handshake->premaster,
  763.                                   sizeof(handshake->premaster) );
  764.     }
  765.     else
  766.         MBEDTLS_SSL_DEBUG_MSG( 3, ( "no premaster (session resumed)" ) );
  767.  
  768.     /*
  769.      * Swap the client and server random values.
  770.      */
  771.     memcpy( tmp, handshake->randbytes, 64 );
  772.     memcpy( handshake->randbytes, tmp + 32, 32 );
  773.     memcpy( handshake->randbytes + 32, tmp, 32 );
  774.     mbedtls_platform_zeroize( tmp, sizeof( tmp ) );
  775.  
  776.     /*
  777.      *  SSLv3:
  778.      *    key block =
  779.      *      MD5( master + SHA1( 'A'    + master + randbytes ) ) +
  780.      *      MD5( master + SHA1( 'BB'   + master + randbytes ) ) +
  781.      *      MD5( master + SHA1( 'CCC'  + master + randbytes ) ) +
  782.      *      MD5( master + SHA1( 'DDDD' + master + randbytes ) ) +
  783.      *      ...
  784.      *
  785.      *  TLSv1:
  786.      *    key block = PRF( master, "key expansion", randbytes )
  787.      */
  788.     ret = handshake->tls_prf( session->master, 48, "key expansion",
  789.                               handshake->randbytes, 64, keyblk, 256 );
  790.     if( ret != 0 )
  791.     {
  792.         MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret );
  793.         return( ret );
  794.     }
  795.  
  796.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite = %s",
  797.                    mbedtls_ssl_get_ciphersuite_name( session->ciphersuite ) ) );
  798.     MBEDTLS_SSL_DEBUG_BUF( 3, "master secret", session->master, 48 );
  799.     MBEDTLS_SSL_DEBUG_BUF( 4, "random bytes", handshake->randbytes, 64 );
  800.     MBEDTLS_SSL_DEBUG_BUF( 4, "key block", keyblk, 256 );
  801.  
  802.     mbedtls_platform_zeroize( handshake->randbytes,
  803.                               sizeof( handshake->randbytes ) );
  804.  
  805.     /*
  806.      * Determine the appropriate key, IV and MAC length.
  807.      */
  808.  
  809.     transform->keylen = cipher_info->key_bitlen / 8;
  810.  
  811.     if( cipher_info->mode == MBEDTLS_MODE_GCM ||
  812.         cipher_info->mode == MBEDTLS_MODE_CCM ||
  813.         cipher_info->mode == MBEDTLS_MODE_CHACHAPOLY )
  814.     {
  815.         size_t taglen, explicit_ivlen;
  816.  
  817.         transform->maclen = 0;
  818.         mac_key_len = 0;
  819.  
  820.         /* All modes haves 96-bit IVs;
  821.          * GCM and CCM has 4 implicit and 8 explicit bytes
  822.          * ChachaPoly has all 12 bytes implicit
  823.          */
  824.         transform->ivlen = 12;
  825.         if( cipher_info->mode == MBEDTLS_MODE_CHACHAPOLY )
  826.             transform->fixed_ivlen = 12;
  827.         else
  828.             transform->fixed_ivlen = 4;
  829.  
  830.         /* All modes have 128-bit tags, except CCM_8 (ciphersuite flag) */
  831.         taglen = transform->ciphersuite_info->flags &
  832.                   MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16;
  833.  
  834.  
  835.         /* Minimum length of encrypted record */
  836.         explicit_ivlen = transform->ivlen - transform->fixed_ivlen;
  837.         transform->minlen = explicit_ivlen + taglen;
  838.     }
  839.     else
  840.     {
  841.         /* Initialize HMAC contexts */
  842.         if( ( ret = mbedtls_md_setup( &transform->md_ctx_enc, md_info, 1 ) ) != 0 ||
  843.             ( ret = mbedtls_md_setup( &transform->md_ctx_dec, md_info, 1 ) ) != 0 )
  844.         {
  845.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_setup", ret );
  846.             return( ret );
  847.         }
  848.  
  849.         /* Get MAC length */
  850.         mac_key_len = mbedtls_md_get_size( md_info );
  851.         transform->maclen = mac_key_len;
  852.  
  853. #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
  854.         /*
  855.          * If HMAC is to be truncated, we shall keep the leftmost bytes,
  856.          * (rfc 6066 page 13 or rfc 2104 section 4),
  857.          * so we only need to adjust the length here.
  858.          */
  859.         if( session->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_ENABLED )
  860.         {
  861.             transform->maclen = MBEDTLS_SSL_TRUNCATED_HMAC_LEN;
  862.  
  863. #if defined(MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT)
  864.             /* Fall back to old, non-compliant version of the truncated
  865.              * HMAC implementation which also truncates the key
  866.              * (Mbed TLS versions from 1.3 to 2.6.0) */
  867.             mac_key_len = transform->maclen;
  868. #endif
  869.         }
  870. #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
  871.  
  872.         /* IV length */
  873.         transform->ivlen = cipher_info->iv_size;
  874.  
  875.         /* Minimum length */
  876.         if( cipher_info->mode == MBEDTLS_MODE_STREAM )
  877.             transform->minlen = transform->maclen;
  878.         else
  879.         {
  880.             /*
  881.              * GenericBlockCipher:
  882.              * 1. if EtM is in use: one block plus MAC
  883.              *    otherwise: * first multiple of blocklen greater than maclen
  884.              * 2. IV except for SSL3 and TLS 1.0
  885.              */
  886. #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
  887.             if( session->encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED )
  888.             {
  889.                 transform->minlen = transform->maclen
  890.                                   + cipher_info->block_size;
  891.             }
  892.             else
  893. #endif
  894.             {
  895.                 transform->minlen = transform->maclen
  896.                                   + cipher_info->block_size
  897.                                   - transform->maclen % cipher_info->block_size;
  898.             }
  899.  
  900. #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1)
  901.             if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ||
  902.                 ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_1 )
  903.                 ; /* No need to adjust minlen */
  904.             else
  905. #endif
  906. #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
  907.             if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_2 ||
  908.                 ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
  909.             {
  910.                 transform->minlen += transform->ivlen;
  911.             }
  912.             else
  913. #endif
  914.             {
  915.                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  916.                 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  917.             }
  918.         }
  919.     }
  920.  
  921.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "keylen: %d, minlen: %d, ivlen: %d, maclen: %d",
  922.                    transform->keylen, transform->minlen, transform->ivlen,
  923.                    transform->maclen ) );
  924.  
  925.     /*
  926.      * Finally setup the cipher contexts, IVs and MAC secrets.
  927.      */
  928. #if defined(MBEDTLS_SSL_CLI_C)
  929.     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
  930.     {
  931.         key1 = keyblk + mac_key_len * 2;
  932.         key2 = keyblk + mac_key_len * 2 + transform->keylen;
  933.  
  934.         mac_enc = keyblk;
  935.         mac_dec = keyblk + mac_key_len;
  936.  
  937.         /*
  938.          * This is not used in TLS v1.1.
  939.          */
  940.         iv_copy_len = ( transform->fixed_ivlen ) ?
  941.                             transform->fixed_ivlen : transform->ivlen;
  942.         memcpy( transform->iv_enc, key2 + transform->keylen,  iv_copy_len );
  943.         memcpy( transform->iv_dec, key2 + transform->keylen + iv_copy_len,
  944.                 iv_copy_len );
  945.     }
  946.     else
  947. #endif /* MBEDTLS_SSL_CLI_C */
  948. #if defined(MBEDTLS_SSL_SRV_C)
  949.     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
  950.     {
  951.         key1 = keyblk + mac_key_len * 2 + transform->keylen;
  952.         key2 = keyblk + mac_key_len * 2;
  953.  
  954.         mac_enc = keyblk + mac_key_len;
  955.         mac_dec = keyblk;
  956.  
  957.         /*
  958.          * This is not used in TLS v1.1.
  959.          */
  960.         iv_copy_len = ( transform->fixed_ivlen ) ?
  961.                             transform->fixed_ivlen : transform->ivlen;
  962.         memcpy( transform->iv_dec, key1 + transform->keylen,  iv_copy_len );
  963.         memcpy( transform->iv_enc, key1 + transform->keylen + iv_copy_len,
  964.                 iv_copy_len );
  965.     }
  966.     else
  967. #endif /* MBEDTLS_SSL_SRV_C */
  968.     {
  969.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  970.         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  971.     }
  972.  
  973. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  974.     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
  975.     {
  976.         if( mac_key_len > sizeof transform->mac_enc )
  977.         {
  978.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  979.             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  980.         }
  981.  
  982.         memcpy( transform->mac_enc, mac_enc, mac_key_len );
  983.         memcpy( transform->mac_dec, mac_dec, mac_key_len );
  984.     }
  985.     else
  986. #endif /* MBEDTLS_SSL_PROTO_SSL3 */
  987. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
  988.     defined(MBEDTLS_SSL_PROTO_TLS1_2)
  989.     if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 )
  990.     {
  991.         /* For HMAC-based ciphersuites, initialize the HMAC transforms.
  992.            For AEAD-based ciphersuites, there is nothing to do here. */
  993.         if( mac_key_len != 0 )
  994.         {
  995.             mbedtls_md_hmac_starts( &transform->md_ctx_enc, mac_enc, mac_key_len );
  996.             mbedtls_md_hmac_starts( &transform->md_ctx_dec, mac_dec, mac_key_len );
  997.         }
  998.     }
  999.     else
  1000. #endif
  1001.     {
  1002.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1003.         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1004.     }
  1005.  
  1006. #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
  1007.     if( mbedtls_ssl_hw_record_init != NULL )
  1008.     {
  1009.         MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_init()" ) );
  1010.  
  1011.         if( ( ret = mbedtls_ssl_hw_record_init( ssl, key1, key2, transform->keylen,
  1012.                                         transform->iv_enc, transform->iv_dec,
  1013.                                         iv_copy_len,
  1014.                                         mac_enc, mac_dec,
  1015.                                         mac_key_len ) ) != 0 )
  1016.         {
  1017.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_init", ret );
  1018.             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
  1019.         }
  1020.     }
  1021. #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
  1022.  
  1023. #if defined(MBEDTLS_SSL_EXPORT_KEYS)
  1024.     if( ssl->conf->f_export_keys != NULL )
  1025.     {
  1026.         ssl->conf->f_export_keys( ssl->conf->p_export_keys,
  1027.                                   session->master, keyblk,
  1028.                                   mac_key_len, transform->keylen,
  1029.                                   iv_copy_len );
  1030.     }
  1031. #endif
  1032.  
  1033.     if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_enc,
  1034.                                  cipher_info ) ) != 0 )
  1035.     {
  1036.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup", ret );
  1037.         return( ret );
  1038.     }
  1039.  
  1040.     if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_dec,
  1041.                                  cipher_info ) ) != 0 )
  1042.     {
  1043.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup", ret );
  1044.         return( ret );
  1045.     }
  1046.  
  1047.     if( ( ret = mbedtls_cipher_setkey( &transform->cipher_ctx_enc, key1,
  1048.                                cipher_info->key_bitlen,
  1049.                                MBEDTLS_ENCRYPT ) ) != 0 )
  1050.     {
  1051.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setkey", ret );
  1052.         return( ret );
  1053.     }
  1054.  
  1055.     if( ( ret = mbedtls_cipher_setkey( &transform->cipher_ctx_dec, key2,
  1056.                                cipher_info->key_bitlen,
  1057.                                MBEDTLS_DECRYPT ) ) != 0 )
  1058.     {
  1059.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setkey", ret );
  1060.         return( ret );
  1061.     }
  1062.  
  1063. #if defined(MBEDTLS_CIPHER_MODE_CBC)
  1064.     if( cipher_info->mode == MBEDTLS_MODE_CBC )
  1065.     {
  1066.         if( ( ret = mbedtls_cipher_set_padding_mode( &transform->cipher_ctx_enc,
  1067.                                              MBEDTLS_PADDING_NONE ) ) != 0 )
  1068.         {
  1069.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_set_padding_mode", ret );
  1070.             return( ret );
  1071.         }
  1072.  
  1073.         if( ( ret = mbedtls_cipher_set_padding_mode( &transform->cipher_ctx_dec,
  1074.                                              MBEDTLS_PADDING_NONE ) ) != 0 )
  1075.         {
  1076.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_set_padding_mode", ret );
  1077.             return( ret );
  1078.         }
  1079.     }
  1080. #endif /* MBEDTLS_CIPHER_MODE_CBC */
  1081.  
  1082.     mbedtls_platform_zeroize( keyblk, sizeof( keyblk ) );
  1083.  
  1084. #if defined(MBEDTLS_ZLIB_SUPPORT)
  1085.     // Initialize compression
  1086.     //
  1087.     if( session->compression == MBEDTLS_SSL_COMPRESS_DEFLATE )
  1088.     {
  1089.         if( ssl->compress_buf == NULL )
  1090.         {
  1091.             MBEDTLS_SSL_DEBUG_MSG( 3, ( "Allocating compression buffer" ) );
  1092.             ssl->compress_buf = mbedtls_calloc( 1, MBEDTLS_SSL_COMPRESS_BUFFER_LEN );
  1093.             if( ssl->compress_buf == NULL )
  1094.             {
  1095.                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed",
  1096.                                     MBEDTLS_SSL_COMPRESS_BUFFER_LEN ) );
  1097.                 return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
  1098.             }
  1099.         }
  1100.  
  1101.         MBEDTLS_SSL_DEBUG_MSG( 3, ( "Initializing zlib states" ) );
  1102.  
  1103.         memset( &transform->ctx_deflate, 0, sizeof( transform->ctx_deflate ) );
  1104.         memset( &transform->ctx_inflate, 0, sizeof( transform->ctx_inflate ) );
  1105.  
  1106.         if( deflateInit( &transform->ctx_deflate,
  1107.                          Z_DEFAULT_COMPRESSION )   != Z_OK ||
  1108.             inflateInit( &transform->ctx_inflate ) != Z_OK )
  1109.         {
  1110.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "Failed to initialize compression" ) );
  1111.             return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED );
  1112.         }
  1113.     }
  1114. #endif /* MBEDTLS_ZLIB_SUPPORT */
  1115.  
  1116.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= derive keys" ) );
  1117.  
  1118.     return( 0 );
  1119. }
  1120.  
  1121. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  1122. void ssl_calc_verify_ssl( mbedtls_ssl_context *ssl, unsigned char hash[36] )
  1123. {
  1124.     mbedtls_md5_context md5;
  1125.     mbedtls_sha1_context sha1;
  1126.     unsigned char pad_1[48];
  1127.     unsigned char pad_2[48];
  1128.  
  1129.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify ssl" ) );
  1130.  
  1131.     mbedtls_md5_init( &md5 );
  1132.     mbedtls_sha1_init( &sha1 );
  1133.  
  1134.     mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
  1135.     mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
  1136.  
  1137.     memset( pad_1, 0x36, 48 );
  1138.     memset( pad_2, 0x5C, 48 );
  1139.  
  1140.     mbedtls_md5_update_ret( &md5, ssl->session_negotiate->master, 48 );
  1141.     mbedtls_md5_update_ret( &md5, pad_1, 48 );
  1142.     mbedtls_md5_finish_ret( &md5, hash );
  1143.  
  1144.     mbedtls_md5_starts_ret( &md5 );
  1145.     mbedtls_md5_update_ret( &md5, ssl->session_negotiate->master, 48 );
  1146.     mbedtls_md5_update_ret( &md5, pad_2, 48 );
  1147.     mbedtls_md5_update_ret( &md5, hash,  16 );
  1148.     mbedtls_md5_finish_ret( &md5, hash );
  1149.  
  1150.     mbedtls_sha1_update_ret( &sha1, ssl->session_negotiate->master, 48 );
  1151.     mbedtls_sha1_update_ret( &sha1, pad_1, 40 );
  1152.     mbedtls_sha1_finish_ret( &sha1, hash + 16 );
  1153.  
  1154.     mbedtls_sha1_starts_ret( &sha1 );
  1155.     mbedtls_sha1_update_ret( &sha1, ssl->session_negotiate->master, 48 );
  1156.     mbedtls_sha1_update_ret( &sha1, pad_2, 40 );
  1157.     mbedtls_sha1_update_ret( &sha1, hash + 16, 20 );
  1158.     mbedtls_sha1_finish_ret( &sha1, hash + 16 );
  1159.  
  1160.     MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 36 );
  1161.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
  1162.  
  1163.     mbedtls_md5_free(  &md5  );
  1164.     mbedtls_sha1_free( &sha1 );
  1165.  
  1166.     return;
  1167. }
  1168. #endif /* MBEDTLS_SSL_PROTO_SSL3 */
  1169.  
  1170. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
  1171. void ssl_calc_verify_tls( mbedtls_ssl_context *ssl, unsigned char hash[36] )
  1172. {
  1173.     mbedtls_md5_context md5;
  1174.     mbedtls_sha1_context sha1;
  1175.  
  1176.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify tls" ) );
  1177.  
  1178.     mbedtls_md5_init( &md5 );
  1179.     mbedtls_sha1_init( &sha1 );
  1180.  
  1181.     mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
  1182.     mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
  1183.  
  1184.      mbedtls_md5_finish_ret( &md5,  hash );
  1185.     mbedtls_sha1_finish_ret( &sha1, hash + 16 );
  1186.  
  1187.     MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 36 );
  1188.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
  1189.  
  1190.     mbedtls_md5_free(  &md5  );
  1191.     mbedtls_sha1_free( &sha1 );
  1192.  
  1193.     return;
  1194. }
  1195. #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
  1196.  
  1197. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  1198. #if defined(MBEDTLS_SHA256_C)
  1199. void ssl_calc_verify_tls_sha256( mbedtls_ssl_context *ssl, unsigned char hash[32] )
  1200. {
  1201.     mbedtls_sha256_context sha256;
  1202.  
  1203.     mbedtls_sha256_init( &sha256 );
  1204.  
  1205.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify sha256" ) );
  1206.  
  1207.     mbedtls_sha256_clone( &sha256, &ssl->handshake->fin_sha256 );
  1208.     mbedtls_sha256_finish_ret( &sha256, hash );
  1209.  
  1210.     MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 32 );
  1211.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
  1212.  
  1213.     mbedtls_sha256_free( &sha256 );
  1214.  
  1215.     return;
  1216. }
  1217. #endif /* MBEDTLS_SHA256_C */
  1218.  
  1219. #if defined(MBEDTLS_SHA512_C)
  1220. void ssl_calc_verify_tls_sha384( mbedtls_ssl_context *ssl, unsigned char hash[48] )
  1221. {
  1222.     mbedtls_sha512_context sha512;
  1223.  
  1224.     mbedtls_sha512_init( &sha512 );
  1225.  
  1226.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify sha384" ) );
  1227.  
  1228.     mbedtls_sha512_clone( &sha512, &ssl->handshake->fin_sha512 );
  1229.     mbedtls_sha512_finish_ret( &sha512, hash );
  1230.  
  1231.     MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 48 );
  1232.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
  1233.  
  1234.     mbedtls_sha512_free( &sha512 );
  1235.  
  1236.     return;
  1237. }
  1238. #endif /* MBEDTLS_SHA512_C */
  1239. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  1240.  
  1241. #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
  1242. int mbedtls_ssl_psk_derive_premaster( mbedtls_ssl_context *ssl, mbedtls_key_exchange_type_t key_ex )
  1243. {
  1244.     unsigned char *p = ssl->handshake->premaster;
  1245.     unsigned char *end = p + sizeof( ssl->handshake->premaster );
  1246.     const unsigned char *psk = ssl->conf->psk;
  1247.     size_t psk_len = ssl->conf->psk_len;
  1248.  
  1249.     /* If the psk callback was called, use its result */
  1250.     if( ssl->handshake->psk != NULL )
  1251.     {
  1252.         psk = ssl->handshake->psk;
  1253.         psk_len = ssl->handshake->psk_len;
  1254.     }
  1255.  
  1256.     /*
  1257.      * PMS = struct {
  1258.      *     opaque other_secret<0..2^16-1>;
  1259.      *     opaque psk<0..2^16-1>;
  1260.      * };
  1261.      * with "other_secret" depending on the particular key exchange
  1262.      */
  1263. #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
  1264.     if( key_ex == MBEDTLS_KEY_EXCHANGE_PSK )
  1265.     {
  1266.         if( end - p < 2 )
  1267.             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  1268.  
  1269.         *(p++) = (unsigned char)( psk_len >> 8 );
  1270.         *(p++) = (unsigned char)( psk_len      );
  1271.  
  1272.         if( end < p || (size_t)( end - p ) < psk_len )
  1273.             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  1274.  
  1275.         memset( p, 0, psk_len );
  1276.         p += psk_len;
  1277.     }
  1278.     else
  1279. #endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */
  1280. #if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
  1281.     if( key_ex == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
  1282.     {
  1283.         /*
  1284.          * other_secret already set by the ClientKeyExchange message,
  1285.          * and is 48 bytes long
  1286.          */
  1287.         if( end - p < 2 )
  1288.             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  1289.  
  1290.         *p++ = 0;
  1291.         *p++ = 48;
  1292.         p += 48;
  1293.     }
  1294.     else
  1295. #endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
  1296. #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
  1297.     if( key_ex == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
  1298.     {
  1299.         int ret;
  1300.         size_t len;
  1301.  
  1302.         /* Write length only when we know the actual value */
  1303.         if( ( ret = mbedtls_dhm_calc_secret( &ssl->handshake->dhm_ctx,
  1304.                                       p + 2, end - ( p + 2 ), &len,
  1305.                                       ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
  1306.         {
  1307.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_calc_secret", ret );
  1308.             return( ret );
  1309.         }
  1310.         *(p++) = (unsigned char)( len >> 8 );
  1311.         *(p++) = (unsigned char)( len );
  1312.         p += len;
  1313.  
  1314.         MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: K ", &ssl->handshake->dhm_ctx.K  );
  1315.     }
  1316.     else
  1317. #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
  1318. #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
  1319.     if( key_ex == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
  1320.     {
  1321.         int ret;
  1322.         size_t zlen;
  1323.  
  1324.         if( ( ret = mbedtls_ecdh_calc_secret( &ssl->handshake->ecdh_ctx, &zlen,
  1325.                                        p + 2, end - ( p + 2 ),
  1326.                                        ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
  1327.         {
  1328.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_calc_secret", ret );
  1329.             return( ret );
  1330.         }
  1331.  
  1332.         *(p++) = (unsigned char)( zlen >> 8 );
  1333.         *(p++) = (unsigned char)( zlen      );
  1334.         p += zlen;
  1335.  
  1336.         MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx,
  1337.                                 MBEDTLS_DEBUG_ECDH_Z );
  1338.     }
  1339.     else
  1340. #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
  1341.     {
  1342.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1343.         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1344.     }
  1345.  
  1346.     /* opaque psk<0..2^16-1>; */
  1347.     if( end - p < 2 )
  1348.         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  1349.  
  1350.     *(p++) = (unsigned char)( psk_len >> 8 );
  1351.     *(p++) = (unsigned char)( psk_len      );
  1352.  
  1353.     if( end < p || (size_t)( end - p ) < psk_len )
  1354.         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  1355.  
  1356.     memcpy( p, psk, psk_len );
  1357.     p += psk_len;
  1358.  
  1359.     ssl->handshake->pmslen = p - ssl->handshake->premaster;
  1360.  
  1361.     return( 0 );
  1362. }
  1363. #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
  1364.  
  1365. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  1366. /*
  1367.  * SSLv3.0 MAC functions
  1368.  */
  1369. #define SSL_MAC_MAX_BYTES   20  /* MD-5 or SHA-1 */
  1370. static void ssl_mac( mbedtls_md_context_t *md_ctx,
  1371.                      const unsigned char *secret,
  1372.                      const unsigned char *buf, size_t len,
  1373.                      const unsigned char *ctr, int type,
  1374.                      unsigned char out[SSL_MAC_MAX_BYTES] )
  1375. {
  1376.     unsigned char header[11];
  1377.     unsigned char padding[48];
  1378.     int padlen;
  1379.     int md_size = mbedtls_md_get_size( md_ctx->md_info );
  1380.     int md_type = mbedtls_md_get_type( md_ctx->md_info );
  1381.  
  1382.     /* Only MD5 and SHA-1 supported */
  1383.     if( md_type == MBEDTLS_MD_MD5 )
  1384.         padlen = 48;
  1385.     else
  1386.         padlen = 40;
  1387.  
  1388.     memcpy( header, ctr, 8 );
  1389.     header[ 8] = (unsigned char)  type;
  1390.     header[ 9] = (unsigned char)( len >> 8 );
  1391.     header[10] = (unsigned char)( len      );
  1392.  
  1393.     memset( padding, 0x36, padlen );
  1394.     mbedtls_md_starts( md_ctx );
  1395.     mbedtls_md_update( md_ctx, secret,  md_size );
  1396.     mbedtls_md_update( md_ctx, padding, padlen  );
  1397.     mbedtls_md_update( md_ctx, header,  11      );
  1398.     mbedtls_md_update( md_ctx, buf,     len     );
  1399.     mbedtls_md_finish( md_ctx, out              );
  1400.  
  1401.     memset( padding, 0x5C, padlen );
  1402.     mbedtls_md_starts( md_ctx );
  1403.     mbedtls_md_update( md_ctx, secret,    md_size );
  1404.     mbedtls_md_update( md_ctx, padding,   padlen  );
  1405.     mbedtls_md_update( md_ctx, out,       md_size );
  1406.     mbedtls_md_finish( md_ctx, out                );
  1407. }
  1408. #endif /* MBEDTLS_SSL_PROTO_SSL3 */
  1409.  
  1410. #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER) ||     \
  1411.     ( defined(MBEDTLS_CIPHER_MODE_CBC) &&                                  \
  1412.       ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_CAMELLIA_C) || defined(MBEDTLS_ARIA_C)) )
  1413. #define SSL_SOME_MODES_USE_MAC
  1414. #endif
  1415.  
  1416. /* The function below is only used in the Lucky 13 counter-measure in
  1417.  * ssl_decrypt_buf(). These are the defines that guard the call site. */
  1418. #if defined(SSL_SOME_MODES_USE_MAC) && \
  1419.     ( defined(MBEDTLS_SSL_PROTO_TLS1) || \
  1420.       defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
  1421.       defined(MBEDTLS_SSL_PROTO_TLS1_2) )
  1422. /* This function makes sure every byte in the memory region is accessed
  1423.  * (in ascending addresses order) */
  1424. static void ssl_read_memory( unsigned char *p, size_t len )
  1425. {
  1426.     unsigned char acc = 0;
  1427.     volatile unsigned char force;
  1428.  
  1429.     for( ; len != 0; p++, len-- )
  1430.         acc ^= *p;
  1431.  
  1432.     force = acc;
  1433.     (void) force;
  1434. }
  1435. #endif /* SSL_SOME_MODES_USE_MAC && ( TLS1 || TLS1_1 || TLS1_2 ) */
  1436.  
  1437. /*
  1438.  * Encryption/decryption functions
  1439.  */
  1440. static int ssl_encrypt_buf( mbedtls_ssl_context *ssl )
  1441. {
  1442.     mbedtls_cipher_mode_t mode;
  1443.     int auth_done = 0;
  1444.  
  1445.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> encrypt buf" ) );
  1446.  
  1447.     if( ssl->session_out == NULL || ssl->transform_out == NULL )
  1448.     {
  1449.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1450.         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1451.     }
  1452.  
  1453.     mode = mbedtls_cipher_get_cipher_mode( &ssl->transform_out->cipher_ctx_enc );
  1454.  
  1455.     MBEDTLS_SSL_DEBUG_BUF( 4, "before encrypt: output payload",
  1456.                       ssl->out_msg, ssl->out_msglen );
  1457.  
  1458.     /*
  1459.      * Add MAC before if needed
  1460.      */
  1461. #if defined(SSL_SOME_MODES_USE_MAC)
  1462.     if( mode == MBEDTLS_MODE_STREAM ||
  1463.         ( mode == MBEDTLS_MODE_CBC
  1464. #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
  1465.           && ssl->session_out->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED
  1466. #endif
  1467.         ) )
  1468.     {
  1469. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  1470.         if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
  1471.         {
  1472.             unsigned char mac[SSL_MAC_MAX_BYTES];
  1473.  
  1474.             ssl_mac( &ssl->transform_out->md_ctx_enc,
  1475.                       ssl->transform_out->mac_enc,
  1476.                       ssl->out_msg, ssl->out_msglen,
  1477.                       ssl->out_ctr, ssl->out_msgtype,
  1478.                       mac );
  1479.  
  1480.             memcpy( ssl->out_msg + ssl->out_msglen, mac, ssl->transform_out->maclen );
  1481.         }
  1482.         else
  1483. #endif
  1484. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
  1485.         defined(MBEDTLS_SSL_PROTO_TLS1_2)
  1486.         if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 )
  1487.         {
  1488.             unsigned char mac[MBEDTLS_SSL_MAC_ADD];
  1489.  
  1490.             mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, ssl->out_ctr, 8 );
  1491.             mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, ssl->out_hdr, 3 );
  1492.             mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, ssl->out_len, 2 );
  1493.             mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc,
  1494.                              ssl->out_msg, ssl->out_msglen );
  1495.             mbedtls_md_hmac_finish( &ssl->transform_out->md_ctx_enc, mac );
  1496.             mbedtls_md_hmac_reset( &ssl->transform_out->md_ctx_enc );
  1497.  
  1498.             memcpy( ssl->out_msg + ssl->out_msglen, mac, ssl->transform_out->maclen );
  1499.         }
  1500.         else
  1501. #endif
  1502.         {
  1503.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1504.             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1505.         }
  1506.  
  1507.         MBEDTLS_SSL_DEBUG_BUF( 4, "computed mac",
  1508.                        ssl->out_msg + ssl->out_msglen,
  1509.                        ssl->transform_out->maclen );
  1510.  
  1511.         ssl->out_msglen += ssl->transform_out->maclen;
  1512.         auth_done++;
  1513.     }
  1514. #endif /* AEAD not the only option */
  1515.  
  1516.     /*
  1517.      * Encrypt
  1518.      */
  1519. #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER)
  1520.     if( mode == MBEDTLS_MODE_STREAM )
  1521.     {
  1522.         int ret;
  1523.         size_t olen = 0;
  1524.  
  1525.         MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
  1526.                             "including %d bytes of padding",
  1527.                        ssl->out_msglen, 0 ) );
  1528.  
  1529.         if( ( ret = mbedtls_cipher_crypt( &ssl->transform_out->cipher_ctx_enc,
  1530.                                    ssl->transform_out->iv_enc,
  1531.                                    ssl->transform_out->ivlen,
  1532.                                    ssl->out_msg, ssl->out_msglen,
  1533.                                    ssl->out_msg, &olen ) ) != 0 )
  1534.         {
  1535.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
  1536.             return( ret );
  1537.         }
  1538.  
  1539.         if( ssl->out_msglen != olen )
  1540.         {
  1541.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1542.             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1543.         }
  1544.     }
  1545.     else
  1546. #endif /* MBEDTLS_ARC4_C || MBEDTLS_CIPHER_NULL_CIPHER */
  1547. #if defined(MBEDTLS_GCM_C) || \
  1548.     defined(MBEDTLS_CCM_C) || \
  1549.     defined(MBEDTLS_CHACHAPOLY_C)
  1550.     if( mode == MBEDTLS_MODE_GCM ||
  1551.         mode == MBEDTLS_MODE_CCM ||
  1552.         mode == MBEDTLS_MODE_CHACHAPOLY )
  1553.     {
  1554.         int ret;
  1555.         size_t enc_msglen, olen;
  1556.         unsigned char *enc_msg;
  1557.         unsigned char add_data[13];
  1558.         unsigned char iv[12];
  1559.         mbedtls_ssl_transform *transform = ssl->transform_out;
  1560.         unsigned char taglen = transform->ciphersuite_info->flags &
  1561.                                MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16;
  1562.         size_t explicit_ivlen = transform->ivlen - transform->fixed_ivlen;
  1563.  
  1564.         /*
  1565.          * Prepare additional authenticated data
  1566.          */
  1567.         memcpy( add_data, ssl->out_ctr, 8 );
  1568.         add_data[8]  = ssl->out_msgtype;
  1569.         mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,
  1570.                            ssl->conf->transport, add_data + 9 );
  1571.         add_data[11] = ( ssl->out_msglen >> 8 ) & 0xFF;
  1572.         add_data[12] = ssl->out_msglen & 0xFF;
  1573.  
  1574.         MBEDTLS_SSL_DEBUG_BUF( 4, "additional data for AEAD", add_data, 13 );
  1575.  
  1576.         /*
  1577.          * Generate IV
  1578.          */
  1579.         if( transform->ivlen == 12 && transform->fixed_ivlen == 4 )
  1580.         {
  1581.             /* GCM and CCM: fixed || explicit (=seqnum) */
  1582.             memcpy( iv, transform->iv_enc, transform->fixed_ivlen );
  1583.             memcpy( iv + transform->fixed_ivlen, ssl->out_ctr, 8 );
  1584.             memcpy( ssl->out_iv, ssl->out_ctr, 8 );
  1585.  
  1586.         }
  1587.         else if( transform->ivlen == 12 && transform->fixed_ivlen == 12 )
  1588.         {
  1589.             /* ChachaPoly: fixed XOR sequence number */
  1590.             unsigned char i;
  1591.  
  1592.             memcpy( iv, transform->iv_enc, transform->fixed_ivlen );
  1593.  
  1594.             for( i = 0; i < 8; i++ )
  1595.                 iv[i+4] ^= ssl->out_ctr[i];
  1596.         }
  1597.         else
  1598.         {
  1599.             /* Reminder if we ever add an AEAD mode with a different size */
  1600.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1601.             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1602.         }
  1603.  
  1604.         MBEDTLS_SSL_DEBUG_BUF( 4, "IV used (internal)",
  1605.                                   iv, transform->ivlen );
  1606.         MBEDTLS_SSL_DEBUG_BUF( 4, "IV used (transmitted)",
  1607.                                   ssl->out_iv, explicit_ivlen );
  1608.  
  1609.         /*
  1610.          * Fix message length with added IV
  1611.          */
  1612.         enc_msg = ssl->out_msg;
  1613.         enc_msglen = ssl->out_msglen;
  1614.         ssl->out_msglen += explicit_ivlen;
  1615.  
  1616.         MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
  1617.                                     "including 0 bytes of padding",
  1618.                                     ssl->out_msglen ) );
  1619.  
  1620.         /*
  1621.          * Encrypt and authenticate
  1622.          */
  1623.         if( ( ret = mbedtls_cipher_auth_encrypt( &transform->cipher_ctx_enc,
  1624.                                          iv, transform->ivlen,
  1625.                                          add_data, 13,
  1626.                                          enc_msg, enc_msglen,
  1627.                                          enc_msg, &olen,
  1628.                                          enc_msg + enc_msglen, taglen ) ) != 0 )
  1629.         {
  1630.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_auth_encrypt", ret );
  1631.             return( ret );
  1632.         }
  1633.  
  1634.         if( olen != enc_msglen )
  1635.         {
  1636.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1637.             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1638.         }
  1639.  
  1640.         ssl->out_msglen += taglen;
  1641.         auth_done++;
  1642.  
  1643.         MBEDTLS_SSL_DEBUG_BUF( 4, "after encrypt: tag", enc_msg + enc_msglen, taglen );
  1644.     }
  1645.     else
  1646. #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C */
  1647. #if defined(MBEDTLS_CIPHER_MODE_CBC) &&                                    \
  1648.     ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_CAMELLIA_C) || defined(MBEDTLS_ARIA_C) )
  1649.     if( mode == MBEDTLS_MODE_CBC )
  1650.     {
  1651.         int ret;
  1652.         unsigned char *enc_msg;
  1653.         size_t enc_msglen, padlen, olen = 0, i;
  1654.  
  1655.         padlen = ssl->transform_out->ivlen - ( ssl->out_msglen + 1 ) %
  1656.                  ssl->transform_out->ivlen;
  1657.         if( padlen == ssl->transform_out->ivlen )
  1658.             padlen = 0;
  1659.  
  1660.         for( i = 0; i <= padlen; i++ )
  1661.             ssl->out_msg[ssl->out_msglen + i] = (unsigned char) padlen;
  1662.  
  1663.         ssl->out_msglen += padlen + 1;
  1664.  
  1665.         enc_msglen = ssl->out_msglen;
  1666.         enc_msg = ssl->out_msg;
  1667.  
  1668. #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
  1669.         /*
  1670.          * Prepend per-record IV for block cipher in TLS v1.1 and up as per
  1671.          * Method 1 (6.2.3.2. in RFC4346 and RFC5246)
  1672.          */
  1673.         if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
  1674.         {
  1675.             /*
  1676.              * Generate IV
  1677.              */
  1678.             ret = ssl->conf->f_rng( ssl->conf->p_rng, ssl->transform_out->iv_enc,
  1679.                                   ssl->transform_out->ivlen );
  1680.             if( ret != 0 )
  1681.                 return( ret );
  1682.  
  1683.             memcpy( ssl->out_iv, ssl->transform_out->iv_enc,
  1684.                     ssl->transform_out->ivlen );
  1685.  
  1686.             /*
  1687.              * Fix pointer positions and message length with added IV
  1688.              */
  1689.             enc_msg = ssl->out_msg;
  1690.             enc_msglen = ssl->out_msglen;
  1691.             ssl->out_msglen += ssl->transform_out->ivlen;
  1692.         }
  1693. #endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */
  1694.  
  1695.         MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
  1696.                             "including %d bytes of IV and %d bytes of padding",
  1697.                             ssl->out_msglen, ssl->transform_out->ivlen,
  1698.                             padlen + 1 ) );
  1699.  
  1700.         if( ( ret = mbedtls_cipher_crypt( &ssl->transform_out->cipher_ctx_enc,
  1701.                                    ssl->transform_out->iv_enc,
  1702.                                    ssl->transform_out->ivlen,
  1703.                                    enc_msg, enc_msglen,
  1704.                                    enc_msg, &olen ) ) != 0 )
  1705.         {
  1706.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
  1707.             return( ret );
  1708.         }
  1709.  
  1710.         if( enc_msglen != olen )
  1711.         {
  1712.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1713.             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1714.         }
  1715.  
  1716. #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1)
  1717.         if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 )
  1718.         {
  1719.             /*
  1720.              * Save IV in SSL3 and TLS1
  1721.              */
  1722.             memcpy( ssl->transform_out->iv_enc,
  1723.                     ssl->transform_out->cipher_ctx_enc.iv,
  1724.                     ssl->transform_out->ivlen );
  1725.         }
  1726. #endif
  1727.  
  1728. #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
  1729.         if( auth_done == 0 )
  1730.         {
  1731.             unsigned char mac[MBEDTLS_SSL_MAC_ADD];
  1732.  
  1733.             /*
  1734.              * MAC(MAC_write_key, seq_num +
  1735.              *     TLSCipherText.type +
  1736.              *     TLSCipherText.version +
  1737.              *     length_of( (IV +) ENC(...) ) +
  1738.              *     IV + // except for TLS 1.0
  1739.              *     ENC(content + padding + padding_length));
  1740.              */
  1741.             unsigned char pseudo_hdr[13];
  1742.  
  1743.             MBEDTLS_SSL_DEBUG_MSG( 3, ( "using encrypt then mac" ) );
  1744.  
  1745.             memcpy( pseudo_hdr +  0, ssl->out_ctr, 8 );
  1746.             memcpy( pseudo_hdr +  8, ssl->out_hdr, 3 );
  1747.             pseudo_hdr[11] = (unsigned char)( ( ssl->out_msglen >> 8 ) & 0xFF );
  1748.             pseudo_hdr[12] = (unsigned char)( ( ssl->out_msglen      ) & 0xFF );
  1749.  
  1750.             MBEDTLS_SSL_DEBUG_BUF( 4, "MAC'd meta-data", pseudo_hdr, 13 );
  1751.  
  1752.             mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, pseudo_hdr, 13 );
  1753.             mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc,
  1754.                              ssl->out_iv, ssl->out_msglen );
  1755.             mbedtls_md_hmac_finish( &ssl->transform_out->md_ctx_enc, mac );
  1756.             mbedtls_md_hmac_reset( &ssl->transform_out->md_ctx_enc );
  1757.  
  1758.             memcpy( ssl->out_iv + ssl->out_msglen, mac,
  1759.                     ssl->transform_out->maclen );
  1760.  
  1761.             ssl->out_msglen += ssl->transform_out->maclen;
  1762.             auth_done++;
  1763.         }
  1764. #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
  1765.     }
  1766.     else
  1767. #endif /* MBEDTLS_CIPHER_MODE_CBC &&
  1768.           ( MBEDTLS_AES_C || MBEDTLS_CAMELLIA_C || MBEDTLS_ARIA_C ) */
  1769.     {
  1770.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1771.         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1772.     }
  1773.  
  1774.     /* Make extra sure authentication was performed, exactly once */
  1775.     if( auth_done != 1 )
  1776.     {
  1777.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1778.         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1779.     }
  1780.  
  1781.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= encrypt buf" ) );
  1782.  
  1783.     return( 0 );
  1784. }
  1785.  
  1786. static int ssl_decrypt_buf( mbedtls_ssl_context *ssl )
  1787. {
  1788.     mbedtls_cipher_mode_t mode;
  1789.     int auth_done = 0;
  1790. #if defined(SSL_SOME_MODES_USE_MAC)
  1791.     size_t padlen = 0, correct = 1;
  1792. #endif
  1793.  
  1794.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> decrypt buf" ) );
  1795.  
  1796.     if( ssl->session_in == NULL || ssl->transform_in == NULL )
  1797.     {
  1798.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1799.         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1800.     }
  1801.  
  1802.     mode = mbedtls_cipher_get_cipher_mode( &ssl->transform_in->cipher_ctx_dec );
  1803.  
  1804.     if( ssl->in_msglen < ssl->transform_in->minlen )
  1805.     {
  1806.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "in_msglen (%d) < minlen (%d)",
  1807.                        ssl->in_msglen, ssl->transform_in->minlen ) );
  1808.         return( MBEDTLS_ERR_SSL_INVALID_MAC );
  1809.     }
  1810.  
  1811. #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER)
  1812.     if( mode == MBEDTLS_MODE_STREAM )
  1813.     {
  1814.         int ret;
  1815.         size_t olen = 0;
  1816.  
  1817.         padlen = 0;
  1818.  
  1819.         if( ( ret = mbedtls_cipher_crypt( &ssl->transform_in->cipher_ctx_dec,
  1820.                                    ssl->transform_in->iv_dec,
  1821.                                    ssl->transform_in->ivlen,
  1822.                                    ssl->in_msg, ssl->in_msglen,
  1823.                                    ssl->in_msg, &olen ) ) != 0 )
  1824.         {
  1825.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
  1826.             return( ret );
  1827.         }
  1828.  
  1829.         if( ssl->in_msglen != olen )
  1830.         {
  1831.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1832.             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1833.         }
  1834.     }
  1835.     else
  1836. #endif /* MBEDTLS_ARC4_C || MBEDTLS_CIPHER_NULL_CIPHER */
  1837. #if defined(MBEDTLS_GCM_C) || \
  1838.     defined(MBEDTLS_CCM_C) || \
  1839.     defined(MBEDTLS_CHACHAPOLY_C)
  1840.     if( mode == MBEDTLS_MODE_GCM ||
  1841.         mode == MBEDTLS_MODE_CCM ||
  1842.         mode == MBEDTLS_MODE_CHACHAPOLY )
  1843.     {
  1844.         int ret;
  1845.         size_t dec_msglen, olen;
  1846.         unsigned char *dec_msg;
  1847.         unsigned char *dec_msg_result;
  1848.         unsigned char add_data[13];
  1849.         unsigned char iv[12];
  1850.         mbedtls_ssl_transform *transform = ssl->transform_in;
  1851.         unsigned char taglen = transform->ciphersuite_info->flags &
  1852.                                MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16;
  1853.         size_t explicit_iv_len = transform->ivlen - transform->fixed_ivlen;
  1854.  
  1855.         /*
  1856.          * Compute and update sizes
  1857.          */
  1858.         if( ssl->in_msglen < explicit_iv_len + taglen )
  1859.         {
  1860.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < explicit_iv_len (%d) "
  1861.                                 "+ taglen (%d)", ssl->in_msglen,
  1862.                                 explicit_iv_len, taglen ) );
  1863.             return( MBEDTLS_ERR_SSL_INVALID_MAC );
  1864.         }
  1865.         dec_msglen = ssl->in_msglen - explicit_iv_len - taglen;
  1866.  
  1867.         dec_msg = ssl->in_msg;
  1868.         dec_msg_result = ssl->in_msg;
  1869.         ssl->in_msglen = dec_msglen;
  1870.  
  1871.         /*
  1872.          * Prepare additional authenticated data
  1873.          */
  1874.         memcpy( add_data, ssl->in_ctr, 8 );
  1875.         add_data[8]  = ssl->in_msgtype;
  1876.         mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,
  1877.                            ssl->conf->transport, add_data + 9 );
  1878.         add_data[11] = ( ssl->in_msglen >> 8 ) & 0xFF;
  1879.         add_data[12] = ssl->in_msglen & 0xFF;
  1880.  
  1881.         MBEDTLS_SSL_DEBUG_BUF( 4, "additional data for AEAD", add_data, 13 );
  1882.  
  1883.         /*
  1884.          * Prepare IV
  1885.          */
  1886.         if( transform->ivlen == 12 && transform->fixed_ivlen == 4 )
  1887.         {
  1888.             /* GCM and CCM: fixed || explicit (transmitted) */
  1889.             memcpy( iv, transform->iv_dec, transform->fixed_ivlen );
  1890.             memcpy( iv + transform->fixed_ivlen, ssl->in_iv, 8 );
  1891.  
  1892.         }
  1893.         else if( transform->ivlen == 12 && transform->fixed_ivlen == 12 )
  1894.         {
  1895.             /* ChachaPoly: fixed XOR sequence number */
  1896.             unsigned char i;
  1897.  
  1898.             memcpy( iv, transform->iv_dec, transform->fixed_ivlen );
  1899.  
  1900.             for( i = 0; i < 8; i++ )
  1901.                 iv[i+4] ^= ssl->in_ctr[i];
  1902.         }
  1903.         else
  1904.         {
  1905.             /* Reminder if we ever add an AEAD mode with a different size */
  1906.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1907.             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1908.         }
  1909.  
  1910.         MBEDTLS_SSL_DEBUG_BUF( 4, "IV used", iv, transform->ivlen );
  1911.         MBEDTLS_SSL_DEBUG_BUF( 4, "TAG used", dec_msg + dec_msglen, taglen );
  1912.  
  1913.         /*
  1914.          * Decrypt and authenticate
  1915.          */
  1916.         if( ( ret = mbedtls_cipher_auth_decrypt( &ssl->transform_in->cipher_ctx_dec,
  1917.                                          iv, transform->ivlen,
  1918.                                          add_data, 13,
  1919.                                          dec_msg, dec_msglen,
  1920.                                          dec_msg_result, &olen,
  1921.                                          dec_msg + dec_msglen, taglen ) ) != 0 )
  1922.         {
  1923.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_auth_decrypt", ret );
  1924.  
  1925.             if( ret == MBEDTLS_ERR_CIPHER_AUTH_FAILED )
  1926.                 return( MBEDTLS_ERR_SSL_INVALID_MAC );
  1927.  
  1928.             return( ret );
  1929.         }
  1930.         auth_done++;
  1931.  
  1932.         if( olen != dec_msglen )
  1933.         {
  1934.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  1935.             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  1936.         }
  1937.     }
  1938.     else
  1939. #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C */
  1940. #if defined(MBEDTLS_CIPHER_MODE_CBC) &&                                    \
  1941.     ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_CAMELLIA_C) || defined(MBEDTLS_ARIA_C) )
  1942.     if( mode == MBEDTLS_MODE_CBC )
  1943.     {
  1944.         /*
  1945.          * Decrypt and check the padding
  1946.          */
  1947.         int ret;
  1948.         unsigned char *dec_msg;
  1949.         unsigned char *dec_msg_result;
  1950.         size_t dec_msglen;
  1951.         size_t minlen = 0;
  1952.         size_t olen = 0;
  1953.  
  1954.         /*
  1955.          * Check immediate ciphertext sanity
  1956.          */
  1957. #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
  1958.         if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
  1959.             minlen += ssl->transform_in->ivlen;
  1960. #endif
  1961.  
  1962.         if( ssl->in_msglen < minlen + ssl->transform_in->ivlen ||
  1963.             ssl->in_msglen < minlen + ssl->transform_in->maclen + 1 )
  1964.         {
  1965.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < max( ivlen(%d), maclen (%d) "
  1966.                                 "+ 1 ) ( + expl IV )", ssl->in_msglen,
  1967.                                 ssl->transform_in->ivlen,
  1968.                                 ssl->transform_in->maclen ) );
  1969.             return( MBEDTLS_ERR_SSL_INVALID_MAC );
  1970.         }
  1971.  
  1972.         dec_msglen = ssl->in_msglen;
  1973.         dec_msg = ssl->in_msg;
  1974.         dec_msg_result = ssl->in_msg;
  1975.  
  1976.         /*
  1977.          * Authenticate before decrypt if enabled
  1978.          */
  1979. #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
  1980.         if( ssl->session_in->encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED )
  1981.         {
  1982.             unsigned char mac_expect[MBEDTLS_SSL_MAC_ADD];
  1983.             unsigned char pseudo_hdr[13];
  1984.  
  1985.             MBEDTLS_SSL_DEBUG_MSG( 3, ( "using encrypt then mac" ) );
  1986.  
  1987.             dec_msglen -= ssl->transform_in->maclen;
  1988.             ssl->in_msglen -= ssl->transform_in->maclen;
  1989.  
  1990.             memcpy( pseudo_hdr +  0, ssl->in_ctr, 8 );
  1991.             memcpy( pseudo_hdr +  8, ssl->in_hdr, 3 );
  1992.             pseudo_hdr[11] = (unsigned char)( ( ssl->in_msglen >> 8 ) & 0xFF );
  1993.             pseudo_hdr[12] = (unsigned char)( ( ssl->in_msglen      ) & 0xFF );
  1994.  
  1995.             MBEDTLS_SSL_DEBUG_BUF( 4, "MAC'd meta-data", pseudo_hdr, 13 );
  1996.  
  1997.             mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, pseudo_hdr, 13 );
  1998.             mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec,
  1999.                              ssl->in_iv, ssl->in_msglen );
  2000.             mbedtls_md_hmac_finish( &ssl->transform_in->md_ctx_dec, mac_expect );
  2001.             mbedtls_md_hmac_reset( &ssl->transform_in->md_ctx_dec );
  2002.  
  2003.             MBEDTLS_SSL_DEBUG_BUF( 4, "message  mac", ssl->in_iv + ssl->in_msglen,
  2004.                                               ssl->transform_in->maclen );
  2005.             MBEDTLS_SSL_DEBUG_BUF( 4, "expected mac", mac_expect,
  2006.                                               ssl->transform_in->maclen );
  2007.  
  2008.             if( mbedtls_ssl_safer_memcmp( ssl->in_iv + ssl->in_msglen, mac_expect,
  2009.                                           ssl->transform_in->maclen ) != 0 )
  2010.             {
  2011.                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "message mac does not match" ) );
  2012.  
  2013.                 return( MBEDTLS_ERR_SSL_INVALID_MAC );
  2014.             }
  2015.             auth_done++;
  2016.         }
  2017. #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
  2018.  
  2019.         /*
  2020.          * Check length sanity
  2021.          */
  2022.         if( ssl->in_msglen % ssl->transform_in->ivlen != 0 )
  2023.         {
  2024.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) %% ivlen (%d) != 0",
  2025.                            ssl->in_msglen, ssl->transform_in->ivlen ) );
  2026.             return( MBEDTLS_ERR_SSL_INVALID_MAC );
  2027.         }
  2028.  
  2029. #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
  2030.         /*
  2031.          * Initialize for prepended IV for block cipher in TLS v1.1 and up
  2032.          */
  2033.         if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
  2034.         {
  2035.             unsigned char i;
  2036.             dec_msglen -= ssl->transform_in->ivlen;
  2037.             ssl->in_msglen -= ssl->transform_in->ivlen;
  2038.  
  2039.             for( i = 0; i < ssl->transform_in->ivlen; i++ )
  2040.                 ssl->transform_in->iv_dec[i] = ssl->in_iv[i];
  2041.         }
  2042. #endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */
  2043.  
  2044.         if( ( ret = mbedtls_cipher_crypt( &ssl->transform_in->cipher_ctx_dec,
  2045.                                    ssl->transform_in->iv_dec,
  2046.                                    ssl->transform_in->ivlen,
  2047.                                    dec_msg, dec_msglen,
  2048.                                    dec_msg_result, &olen ) ) != 0 )
  2049.         {
  2050.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
  2051.             return( ret );
  2052.         }
  2053.  
  2054.         if( dec_msglen != olen )
  2055.         {
  2056.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  2057.             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  2058.         }
  2059.  
  2060. #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1)
  2061.         if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 )
  2062.         {
  2063.             /*
  2064.              * Save IV in SSL3 and TLS1
  2065.              */
  2066.             memcpy( ssl->transform_in->iv_dec,
  2067.                     ssl->transform_in->cipher_ctx_dec.iv,
  2068.                     ssl->transform_in->ivlen );
  2069.         }
  2070. #endif
  2071.  
  2072.         padlen = 1 + ssl->in_msg[ssl->in_msglen - 1];
  2073.  
  2074.         if( ssl->in_msglen < ssl->transform_in->maclen + padlen &&
  2075.             auth_done == 0 )
  2076.         {
  2077. #if defined(MBEDTLS_SSL_DEBUG_ALL)
  2078.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < maclen (%d) + padlen (%d)",
  2079.                         ssl->in_msglen, ssl->transform_in->maclen, padlen ) );
  2080. #endif
  2081.             padlen = 0;
  2082.             correct = 0;
  2083.         }
  2084.  
  2085. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  2086.         if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
  2087.         {
  2088.             if( padlen > ssl->transform_in->ivlen )
  2089.             {
  2090. #if defined(MBEDTLS_SSL_DEBUG_ALL)
  2091.                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad padding length: is %d, "
  2092.                                     "should be no more than %d",
  2093.                                padlen, ssl->transform_in->ivlen ) );
  2094. #endif
  2095.                 correct = 0;
  2096.             }
  2097.         }
  2098.         else
  2099. #endif /* MBEDTLS_SSL_PROTO_SSL3 */
  2100. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
  2101.     defined(MBEDTLS_SSL_PROTO_TLS1_2)
  2102.         if( ssl->minor_ver > MBEDTLS_SSL_MINOR_VERSION_0 )
  2103.         {
  2104.             /*
  2105.              * TLSv1+: always check the padding up to the first failure
  2106.              * and fake check up to 256 bytes of padding
  2107.              */
  2108.             size_t pad_count = 0, real_count = 1;
  2109.             size_t padding_idx = ssl->in_msglen - padlen;
  2110.             size_t i;
  2111.  
  2112.             /*
  2113.              * Padding is guaranteed to be incorrect if:
  2114.              *   1. padlen > ssl->in_msglen
  2115.              *
  2116.              *   2. padding_idx > MBEDTLS_SSL_IN_CONTENT_LEN +
  2117.              *                     ssl->transform_in->maclen
  2118.              *
  2119.              * In both cases we reset padding_idx to a safe value (0) to
  2120.              * prevent out-of-buffer reads.
  2121.              */
  2122.             correct &= ( padlen <= ssl->in_msglen );
  2123.             correct &= ( padding_idx <= MBEDTLS_SSL_IN_CONTENT_LEN +
  2124.                                        ssl->transform_in->maclen );
  2125.  
  2126.             padding_idx *= correct;
  2127.  
  2128.             for( i = 0; i < 256; i++ )
  2129.             {
  2130.                 real_count &= ( i < padlen );
  2131.                 pad_count += real_count *
  2132.                              ( ssl->in_msg[padding_idx + i] == padlen - 1 );
  2133.             }
  2134.  
  2135.             correct &= ( pad_count == padlen ); /* Only 1 on correct padding */
  2136.  
  2137. #if defined(MBEDTLS_SSL_DEBUG_ALL)
  2138.             if( padlen > 0 && correct == 0 )
  2139.                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad padding byte detected" ) );
  2140. #endif
  2141.             padlen &= correct * 0x1FF;
  2142.         }
  2143.         else
  2144. #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
  2145.           MBEDTLS_SSL_PROTO_TLS1_2 */
  2146.         {
  2147.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  2148.             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  2149.         }
  2150.  
  2151.         ssl->in_msglen -= padlen;
  2152.     }
  2153.     else
  2154. #endif /* MBEDTLS_CIPHER_MODE_CBC &&
  2155.           ( MBEDTLS_AES_C || MBEDTLS_CAMELLIA_C || MBEDTLS_ARIA_C ) */
  2156.     {
  2157.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  2158.         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  2159.     }
  2160.  
  2161. #if defined(MBEDTLS_SSL_DEBUG_ALL)
  2162.     MBEDTLS_SSL_DEBUG_BUF( 4, "raw buffer after decryption",
  2163.                    ssl->in_msg, ssl->in_msglen );
  2164. #endif
  2165.  
  2166.     /*
  2167.      * Authenticate if not done yet.
  2168.      * Compute the MAC regardless of the padding result (RFC4346, CBCTIME).
  2169.      */
  2170. #if defined(SSL_SOME_MODES_USE_MAC)
  2171.     if( auth_done == 0 )
  2172.     {
  2173.         unsigned char mac_expect[MBEDTLS_SSL_MAC_ADD];
  2174.  
  2175.         ssl->in_msglen -= ssl->transform_in->maclen;
  2176.  
  2177.         ssl->in_len[0] = (unsigned char)( ssl->in_msglen >> 8 );
  2178.         ssl->in_len[1] = (unsigned char)( ssl->in_msglen      );
  2179.  
  2180. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  2181.         if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
  2182.         {
  2183.             ssl_mac( &ssl->transform_in->md_ctx_dec,
  2184.                       ssl->transform_in->mac_dec,
  2185.                       ssl->in_msg, ssl->in_msglen,
  2186.                       ssl->in_ctr, ssl->in_msgtype,
  2187.                       mac_expect );
  2188.         }
  2189.         else
  2190. #endif /* MBEDTLS_SSL_PROTO_SSL3 */
  2191. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
  2192.         defined(MBEDTLS_SSL_PROTO_TLS1_2)
  2193.         if( ssl->minor_ver > MBEDTLS_SSL_MINOR_VERSION_0 )
  2194.         {
  2195.             /*
  2196.              * Process MAC and always update for padlen afterwards to make
  2197.              * total time independent of padlen.
  2198.              *
  2199.              * Known timing attacks:
  2200.              *  - Lucky Thirteen (http://www.isg.rhul.ac.uk/tls/TLStiming.pdf)
  2201.              *
  2202.              * To compensate for different timings for the MAC calculation
  2203.              * depending on how much padding was removed (which is determined
  2204.              * by padlen), process extra_run more blocks through the hash
  2205.              * function.
  2206.              *
  2207.              * The formula in the paper is
  2208.              *   extra_run = ceil( (L1-55) / 64 ) - ceil( (L2-55) / 64 )
  2209.              * where L1 is the size of the header plus the decrypted message
  2210.              * plus CBC padding and L2 is the size of the header plus the
  2211.              * decrypted message. This is for an underlying hash function
  2212.              * with 64-byte blocks.
  2213.              * We use ( (Lx+8) / 64 ) to handle 'negative Lx' values
  2214.              * correctly. We round down instead of up, so -56 is the correct
  2215.              * value for our calculations instead of -55.
  2216.              *
  2217.              * Repeat the formula rather than defining a block_size variable.
  2218.              * This avoids requiring division by a variable at runtime
  2219.              * (which would be marginally less efficient and would require
  2220.              * linking an extra division function in some builds).
  2221.              */
  2222.             size_t j, extra_run = 0;
  2223.  
  2224.             /*
  2225.              * The next two sizes are the minimum and maximum values of
  2226.              * in_msglen over all padlen values.
  2227.              *
  2228.              * They're independent of padlen, since we previously did
  2229.              * in_msglen -= padlen.
  2230.              *
  2231.              * Note that max_len + maclen is never more than the buffer
  2232.              * length, as we previously did in_msglen -= maclen too.
  2233.              */
  2234.             const size_t max_len = ssl->in_msglen + padlen;
  2235.             const size_t min_len = ( max_len > 256 ) ? max_len - 256 : 0;
  2236.  
  2237.             switch( ssl->transform_in->ciphersuite_info->mac )
  2238.             {
  2239. #if defined(MBEDTLS_MD5_C) || defined(MBEDTLS_SHA1_C) || \
  2240.     defined(MBEDTLS_SHA256_C)
  2241.                 case MBEDTLS_MD_MD5:
  2242.                 case MBEDTLS_MD_SHA1:
  2243.                 case MBEDTLS_MD_SHA256:
  2244.                     /* 8 bytes of message size, 64-byte compression blocks */
  2245.                     extra_run = ( 13 + ssl->in_msglen + padlen + 8 ) / 64 -
  2246.                                 ( 13 + ssl->in_msglen          + 8 ) / 64;
  2247.                     break;
  2248. #endif
  2249. #if defined(MBEDTLS_SHA512_C)
  2250.                 case MBEDTLS_MD_SHA384:
  2251.                     /* 16 bytes of message size, 128-byte compression blocks */
  2252.                     extra_run = ( 13 + ssl->in_msglen + padlen + 16 ) / 128 -
  2253.                                 ( 13 + ssl->in_msglen          + 16 ) / 128;
  2254.                     break;
  2255. #endif
  2256.                 default:
  2257.                     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  2258.                     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  2259.             }
  2260.  
  2261.             extra_run &= correct * 0xFF;
  2262.  
  2263.             mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_ctr, 8 );
  2264.             mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_hdr, 3 );
  2265.             mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_len, 2 );
  2266.             mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_msg,
  2267.                              ssl->in_msglen );
  2268.             /* Make sure we access everything even when padlen > 0. This
  2269.              * makes the synchronisation requirements for just-in-time
  2270.              * Prime+Probe attacks much tighter and hopefully impractical. */
  2271.             ssl_read_memory( ssl->in_msg + ssl->in_msglen, padlen );
  2272.             mbedtls_md_hmac_finish( &ssl->transform_in->md_ctx_dec, mac_expect );
  2273.  
  2274.             /* Call mbedtls_md_process at least once due to cache attacks
  2275.              * that observe whether md_process() was called of not */
  2276.             for( j = 0; j < extra_run + 1; j++ )
  2277.                 mbedtls_md_process( &ssl->transform_in->md_ctx_dec, ssl->in_msg );
  2278.  
  2279.             mbedtls_md_hmac_reset( &ssl->transform_in->md_ctx_dec );
  2280.  
  2281.             /* Make sure we access all the memory that could contain the MAC,
  2282.              * before we check it in the next code block. This makes the
  2283.              * synchronisation requirements for just-in-time Prime+Probe
  2284.              * attacks much tighter and hopefully impractical. */
  2285.             ssl_read_memory( ssl->in_msg + min_len,
  2286.                                  max_len - min_len + ssl->transform_in->maclen );
  2287.         }
  2288.         else
  2289. #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
  2290.               MBEDTLS_SSL_PROTO_TLS1_2 */
  2291.         {
  2292.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  2293.             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  2294.         }
  2295.  
  2296. #if defined(MBEDTLS_SSL_DEBUG_ALL)
  2297.         MBEDTLS_SSL_DEBUG_BUF( 4, "expected mac", mac_expect, ssl->transform_in->maclen );
  2298.         MBEDTLS_SSL_DEBUG_BUF( 4, "message  mac", ssl->in_msg + ssl->in_msglen,
  2299.                                ssl->transform_in->maclen );
  2300. #endif
  2301.  
  2302.         if( mbedtls_ssl_safer_memcmp( ssl->in_msg + ssl->in_msglen, mac_expect,
  2303.                                       ssl->transform_in->maclen ) != 0 )
  2304.         {
  2305. #if defined(MBEDTLS_SSL_DEBUG_ALL)
  2306.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "message mac does not match" ) );
  2307. #endif
  2308.             correct = 0;
  2309.         }
  2310.         auth_done++;
  2311.     }
  2312.  
  2313.     /*
  2314.      * Finally check the correct flag
  2315.      */
  2316.     if( correct == 0 )
  2317.         return( MBEDTLS_ERR_SSL_INVALID_MAC );
  2318. #endif /* SSL_SOME_MODES_USE_MAC */
  2319.  
  2320.     /* Make extra sure authentication was performed, exactly once */
  2321.     if( auth_done != 1 )
  2322.     {
  2323.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  2324.         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  2325.     }
  2326.  
  2327.     if( ssl->in_msglen == 0 )
  2328.     {
  2329. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  2330.         if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3
  2331.             && ssl->in_msgtype != MBEDTLS_SSL_MSG_APPLICATION_DATA )
  2332.         {
  2333.             /* TLS v1.2 explicitly disallows zero-length messages which are not application data */
  2334.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid zero-length message type: %d", ssl->in_msgtype ) );
  2335.             return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  2336.         }
  2337. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  2338.  
  2339.         ssl->nb_zero++;
  2340.  
  2341.         /*
  2342.          * Three or more empty messages may be a DoS attack
  2343.          * (excessive CPU consumption).
  2344.          */
  2345.         if( ssl->nb_zero > 3 )
  2346.         {
  2347.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "received four consecutive empty "
  2348.                                 "messages, possible DoS attack" ) );
  2349.             return( MBEDTLS_ERR_SSL_INVALID_MAC );
  2350.         }
  2351.     }
  2352.     else
  2353.         ssl->nb_zero = 0;
  2354.  
  2355. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  2356.     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  2357.     {
  2358.         ; /* in_ctr read from peer, not maintained internally */
  2359.     }
  2360.     else
  2361. #endif
  2362.     {
  2363.         unsigned char i;
  2364.         for( i = 8; i > ssl_ep_len( ssl ); i-- )
  2365.             if( ++ssl->in_ctr[i - 1] != 0 )
  2366.                 break;
  2367.  
  2368.         /* The loop goes to its end iff the counter is wrapping */
  2369.         if( i == ssl_ep_len( ssl ) )
  2370.         {
  2371.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "incoming message counter would wrap" ) );
  2372.             return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
  2373.         }
  2374.     }
  2375.  
  2376.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= decrypt buf" ) );
  2377.  
  2378.     return( 0 );
  2379. }
  2380.  
  2381. #undef MAC_NONE
  2382. #undef MAC_PLAINTEXT
  2383. #undef MAC_CIPHERTEXT
  2384.  
  2385. #if defined(MBEDTLS_ZLIB_SUPPORT)
  2386. /*
  2387.  * Compression/decompression functions
  2388.  */
  2389. static int ssl_compress_buf( mbedtls_ssl_context *ssl )
  2390. {
  2391.     int ret;
  2392.     unsigned char *msg_post = ssl->out_msg;
  2393.     ptrdiff_t bytes_written = ssl->out_msg - ssl->out_buf;
  2394.     size_t len_pre = ssl->out_msglen;
  2395.     unsigned char *msg_pre = ssl->compress_buf;
  2396.  
  2397.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> compress buf" ) );
  2398.  
  2399.     if( len_pre == 0 )
  2400.         return( 0 );
  2401.  
  2402.     memcpy( msg_pre, ssl->out_msg, len_pre );
  2403.  
  2404.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "before compression: msglen = %d, ",
  2405.                    ssl->out_msglen ) );
  2406.  
  2407.     MBEDTLS_SSL_DEBUG_BUF( 4, "before compression: output payload",
  2408.                    ssl->out_msg, ssl->out_msglen );
  2409.  
  2410.     ssl->transform_out->ctx_deflate.next_in = msg_pre;
  2411.     ssl->transform_out->ctx_deflate.avail_in = len_pre;
  2412.     ssl->transform_out->ctx_deflate.next_out = msg_post;
  2413.     ssl->transform_out->ctx_deflate.avail_out = MBEDTLS_SSL_OUT_BUFFER_LEN - bytes_written;
  2414.  
  2415.     ret = deflate( &ssl->transform_out->ctx_deflate, Z_SYNC_FLUSH );
  2416.     if( ret != Z_OK )
  2417.     {
  2418.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "failed to perform compression (%d)", ret ) );
  2419.         return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED );
  2420.     }
  2421.  
  2422.     ssl->out_msglen = MBEDTLS_SSL_OUT_BUFFER_LEN -
  2423.                       ssl->transform_out->ctx_deflate.avail_out - bytes_written;
  2424.  
  2425.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "after compression: msglen = %d, ",
  2426.                    ssl->out_msglen ) );
  2427.  
  2428.     MBEDTLS_SSL_DEBUG_BUF( 4, "after compression: output payload",
  2429.                    ssl->out_msg, ssl->out_msglen );
  2430.  
  2431.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= compress buf" ) );
  2432.  
  2433.     return( 0 );
  2434. }
  2435.  
  2436. static int ssl_decompress_buf( mbedtls_ssl_context *ssl )
  2437. {
  2438.     int ret;
  2439.     unsigned char *msg_post = ssl->in_msg;
  2440.     ptrdiff_t header_bytes = ssl->in_msg - ssl->in_buf;
  2441.     size_t len_pre = ssl->in_msglen;
  2442.     unsigned char *msg_pre = ssl->compress_buf;
  2443.  
  2444.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> decompress buf" ) );
  2445.  
  2446.     if( len_pre == 0 )
  2447.         return( 0 );
  2448.  
  2449.     memcpy( msg_pre, ssl->in_msg, len_pre );
  2450.  
  2451.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "before decompression: msglen = %d, ",
  2452.                    ssl->in_msglen ) );
  2453.  
  2454.     MBEDTLS_SSL_DEBUG_BUF( 4, "before decompression: input payload",
  2455.                    ssl->in_msg, ssl->in_msglen );
  2456.  
  2457.     ssl->transform_in->ctx_inflate.next_in = msg_pre;
  2458.     ssl->transform_in->ctx_inflate.avail_in = len_pre;
  2459.     ssl->transform_in->ctx_inflate.next_out = msg_post;
  2460.     ssl->transform_in->ctx_inflate.avail_out = MBEDTLS_SSL_IN_BUFFER_LEN -
  2461.                                                header_bytes;
  2462.  
  2463.     ret = inflate( &ssl->transform_in->ctx_inflate, Z_SYNC_FLUSH );
  2464.     if( ret != Z_OK )
  2465.     {
  2466.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "failed to perform decompression (%d)", ret ) );
  2467.         return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED );
  2468.     }
  2469.  
  2470.     ssl->in_msglen = MBEDTLS_SSL_IN_BUFFER_LEN -
  2471.                      ssl->transform_in->ctx_inflate.avail_out - header_bytes;
  2472.  
  2473.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "after decompression: msglen = %d, ",
  2474.                    ssl->in_msglen ) );
  2475.  
  2476.     MBEDTLS_SSL_DEBUG_BUF( 4, "after decompression: input payload",
  2477.                    ssl->in_msg, ssl->in_msglen );
  2478.  
  2479.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= decompress buf" ) );
  2480.  
  2481.     return( 0 );
  2482. }
  2483. #endif /* MBEDTLS_ZLIB_SUPPORT */
  2484.  
  2485. #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
  2486. static int ssl_write_hello_request( mbedtls_ssl_context *ssl );
  2487.  
  2488. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  2489. static int ssl_resend_hello_request( mbedtls_ssl_context *ssl )
  2490. {
  2491.     /* If renegotiation is not enforced, retransmit until we would reach max
  2492.      * timeout if we were using the usual handshake doubling scheme */
  2493.     if( ssl->conf->renego_max_records < 0 )
  2494.     {
  2495.         uint32_t ratio = ssl->conf->hs_timeout_max / ssl->conf->hs_timeout_min + 1;
  2496.         unsigned char doublings = 1;
  2497.  
  2498.         while( ratio != 0 )
  2499.         {
  2500.             ++doublings;
  2501.             ratio >>= 1;
  2502.         }
  2503.  
  2504.         if( ++ssl->renego_records_seen > doublings )
  2505.         {
  2506.             MBEDTLS_SSL_DEBUG_MSG( 2, ( "no longer retransmitting hello request" ) );
  2507.             return( 0 );
  2508.         }
  2509.     }
  2510.  
  2511.     return( ssl_write_hello_request( ssl ) );
  2512. }
  2513. #endif
  2514. #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
  2515.  
  2516. /*
  2517.  * Fill the input message buffer by appending data to it.
  2518.  * The amount of data already fetched is in ssl->in_left.
  2519.  *
  2520.  * If we return 0, is it guaranteed that (at least) nb_want bytes are
  2521.  * available (from this read and/or a previous one). Otherwise, an error code
  2522.  * is returned (possibly EOF or WANT_READ).
  2523.  *
  2524.  * With stream transport (TLS) on success ssl->in_left == nb_want, but
  2525.  * with datagram transport (DTLS) on success ssl->in_left >= nb_want,
  2526.  * since we always read a whole datagram at once.
  2527.  *
  2528.  * For DTLS, it is up to the caller to set ssl->next_record_offset when
  2529.  * they're done reading a record.
  2530.  */
  2531. int mbedtls_ssl_fetch_input( mbedtls_ssl_context *ssl, size_t nb_want )
  2532. {
  2533.     int ret;
  2534.     size_t len;
  2535.  
  2536.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> fetch input" ) );
  2537.  
  2538.     if( ssl->f_recv == NULL && ssl->f_recv_timeout == NULL )
  2539.     {
  2540.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Bad usage of mbedtls_ssl_set_bio() "
  2541.                             "or mbedtls_ssl_set_bio()" ) );
  2542.         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  2543.     }
  2544.  
  2545.     if( nb_want > MBEDTLS_SSL_IN_BUFFER_LEN - (size_t)( ssl->in_hdr - ssl->in_buf ) )
  2546.     {
  2547.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "requesting more data than fits" ) );
  2548.         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  2549.     }
  2550.  
  2551. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  2552.     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  2553.     {
  2554.         uint32_t timeout;
  2555.  
  2556.         /* Just to be sure */
  2557.         if( ssl->f_set_timer == NULL || ssl->f_get_timer == NULL )
  2558.         {
  2559.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "You must use "
  2560.                         "mbedtls_ssl_set_timer_cb() for DTLS" ) );
  2561.             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  2562.         }
  2563.  
  2564.         /*
  2565.          * The point is, we need to always read a full datagram at once, so we
  2566.          * sometimes read more then requested, and handle the additional data.
  2567.          * It could be the rest of the current record (while fetching the
  2568.          * header) and/or some other records in the same datagram.
  2569.          */
  2570.  
  2571.         /*
  2572.          * Move to the next record in the already read datagram if applicable
  2573.          */
  2574.         if( ssl->next_record_offset != 0 )
  2575.         {
  2576.             if( ssl->in_left < ssl->next_record_offset )
  2577.             {
  2578.                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  2579.                 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  2580.             }
  2581.  
  2582.             ssl->in_left -= ssl->next_record_offset;
  2583.  
  2584.             if( ssl->in_left != 0 )
  2585.             {
  2586.                 MBEDTLS_SSL_DEBUG_MSG( 2, ( "next record in same datagram, offset: %d",
  2587.                                     ssl->next_record_offset ) );
  2588.                 memmove( ssl->in_hdr,
  2589.                          ssl->in_hdr + ssl->next_record_offset,
  2590.                          ssl->in_left );
  2591.             }
  2592.  
  2593.             ssl->next_record_offset = 0;
  2594.         }
  2595.  
  2596.         MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d",
  2597.                        ssl->in_left, nb_want ) );
  2598.  
  2599.         /*
  2600.          * Done if we already have enough data.
  2601.          */
  2602.         if( nb_want <= ssl->in_left)
  2603.         {
  2604.             MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= fetch input" ) );
  2605.             return( 0 );
  2606.         }
  2607.  
  2608.         /*
  2609.          * A record can't be split across datagrams. If we need to read but
  2610.          * are not at the beginning of a new record, the caller did something
  2611.          * wrong.
  2612.          */
  2613.         if( ssl->in_left != 0 )
  2614.         {
  2615.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  2616.             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  2617.         }
  2618.  
  2619.         /*
  2620.          * Don't even try to read if time's out already.
  2621.          * This avoids by-passing the timer when repeatedly receiving messages
  2622.          * that will end up being dropped.
  2623.          */
  2624.         if( ssl_check_timer( ssl ) != 0 )
  2625.         {
  2626.             MBEDTLS_SSL_DEBUG_MSG( 2, ( "timer has expired" ) );
  2627.             ret = MBEDTLS_ERR_SSL_TIMEOUT;
  2628.         }
  2629.         else
  2630.         {
  2631.             len = MBEDTLS_SSL_IN_BUFFER_LEN - ( ssl->in_hdr - ssl->in_buf );
  2632.  
  2633.             if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
  2634.                 timeout = ssl->handshake->retransmit_timeout;
  2635.             else
  2636.                 timeout = ssl->conf->read_timeout;
  2637.  
  2638.             MBEDTLS_SSL_DEBUG_MSG( 3, ( "f_recv_timeout: %u ms", timeout ) );
  2639.  
  2640.             if( ssl->f_recv_timeout != NULL )
  2641.                 ret = ssl->f_recv_timeout( ssl->p_bio, ssl->in_hdr, len,
  2642.                                                                     timeout );
  2643.             else
  2644.                 ret = ssl->f_recv( ssl->p_bio, ssl->in_hdr, len );
  2645.  
  2646.             MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_recv(_timeout)", ret );
  2647.  
  2648.             if( ret == 0 )
  2649.                 return( MBEDTLS_ERR_SSL_CONN_EOF );
  2650.         }
  2651.  
  2652.         if( ret == MBEDTLS_ERR_SSL_TIMEOUT )
  2653.         {
  2654.             MBEDTLS_SSL_DEBUG_MSG( 2, ( "timeout" ) );
  2655.             ssl_set_timer( ssl, 0 );
  2656.  
  2657.             if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
  2658.             {
  2659.                 if( ssl_double_retransmit_timeout( ssl ) != 0 )
  2660.                 {
  2661.                     MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake timeout" ) );
  2662.                     return( MBEDTLS_ERR_SSL_TIMEOUT );
  2663.                 }
  2664.  
  2665.                 if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )
  2666.                 {
  2667.                     MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend", ret );
  2668.                     return( ret );
  2669.                 }
  2670.  
  2671.                 return( MBEDTLS_ERR_SSL_WANT_READ );
  2672.             }
  2673. #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
  2674.             else if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
  2675.                      ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
  2676.             {
  2677.                 if( ( ret = ssl_resend_hello_request( ssl ) ) != 0 )
  2678.                 {
  2679.                     MBEDTLS_SSL_DEBUG_RET( 1, "ssl_resend_hello_request", ret );
  2680.                     return( ret );
  2681.                 }
  2682.  
  2683.                 return( MBEDTLS_ERR_SSL_WANT_READ );
  2684.             }
  2685. #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
  2686.         }
  2687.  
  2688.         if( ret < 0 )
  2689.             return( ret );
  2690.  
  2691.         ssl->in_left = ret;
  2692.     }
  2693.     else
  2694. #endif
  2695.     {
  2696.         MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d",
  2697.                        ssl->in_left, nb_want ) );
  2698.  
  2699.         while( ssl->in_left < nb_want )
  2700.         {
  2701.             len = nb_want - ssl->in_left;
  2702.  
  2703.             if( ssl_check_timer( ssl ) != 0 )
  2704.                 ret = MBEDTLS_ERR_SSL_TIMEOUT;
  2705.             else
  2706.             {
  2707.                 if( ssl->f_recv_timeout != NULL )
  2708.                 {
  2709.                     ret = ssl->f_recv_timeout( ssl->p_bio,
  2710.                                                ssl->in_hdr + ssl->in_left, len,
  2711.                                                ssl->conf->read_timeout );
  2712.                 }
  2713.                 else
  2714.                 {
  2715.                     ret = ssl->f_recv( ssl->p_bio,
  2716.                                        ssl->in_hdr + ssl->in_left, len );
  2717.                 }
  2718.             }
  2719.  
  2720.             MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d",
  2721.                                         ssl->in_left, nb_want ) );
  2722.             MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_recv(_timeout)", ret );
  2723.  
  2724.             if( ret == 0 )
  2725.                 return( MBEDTLS_ERR_SSL_CONN_EOF );
  2726.  
  2727.             if( ret < 0 )
  2728.                 return( ret );
  2729.  
  2730.             if ( (size_t)ret > len || ( INT_MAX > SIZE_MAX && ret > SIZE_MAX ) )
  2731.             {
  2732.                 MBEDTLS_SSL_DEBUG_MSG( 1,
  2733.                     ( "f_recv returned %d bytes but only %lu were requested",
  2734.                     ret, (unsigned long)len ) );
  2735.                 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  2736.             }
  2737.  
  2738.             ssl->in_left += ret;
  2739.         }
  2740.     }
  2741.  
  2742.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= fetch input" ) );
  2743.  
  2744.     return( 0 );
  2745. }
  2746.  
  2747. /*
  2748.  * Flush any data not yet written
  2749.  */
  2750. int mbedtls_ssl_flush_output( mbedtls_ssl_context *ssl )
  2751. {
  2752.     int ret;
  2753.     unsigned char *buf;
  2754.  
  2755.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> flush output" ) );
  2756.  
  2757.     if( ssl->f_send == NULL )
  2758.     {
  2759.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Bad usage of mbedtls_ssl_set_bio() "
  2760.                             "or mbedtls_ssl_set_bio()" ) );
  2761.         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  2762.     }
  2763.  
  2764.     /* Avoid incrementing counter if data is flushed */
  2765.     if( ssl->out_left == 0 )
  2766.     {
  2767.         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= flush output" ) );
  2768.         return( 0 );
  2769.     }
  2770.  
  2771.     while( ssl->out_left > 0 )
  2772.     {
  2773.         MBEDTLS_SSL_DEBUG_MSG( 2, ( "message length: %d, out_left: %d",
  2774.                        mbedtls_ssl_hdr_len( ssl ) + ssl->out_msglen, ssl->out_left ) );
  2775.  
  2776.         buf = ssl->out_hdr - ssl->out_left;
  2777.         ret = ssl->f_send( ssl->p_bio, buf, ssl->out_left );
  2778.  
  2779.         MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_send", ret );
  2780.  
  2781.         if( ret <= 0 )
  2782.             return( ret );
  2783.  
  2784.         if( (size_t)ret > ssl->out_left || ( INT_MAX > SIZE_MAX && ret > SIZE_MAX ) )
  2785.         {
  2786.             MBEDTLS_SSL_DEBUG_MSG( 1,
  2787.                 ( "f_send returned %d bytes but only %lu bytes were sent",
  2788.                 ret, (unsigned long)ssl->out_left ) );
  2789.             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  2790.         }
  2791.  
  2792.         ssl->out_left -= ret;
  2793.     }
  2794.  
  2795. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  2796.     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  2797.     {
  2798.         ssl->out_hdr = ssl->out_buf;
  2799.     }
  2800.     else
  2801. #endif
  2802.     {
  2803.         ssl->out_hdr = ssl->out_buf + 8;
  2804.     }
  2805.     ssl_update_out_pointers( ssl, ssl->transform_out );
  2806.  
  2807.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= flush output" ) );
  2808.  
  2809.     return( 0 );
  2810. }
  2811.  
  2812. /*
  2813.  * Functions to handle the DTLS retransmission state machine
  2814.  */
  2815. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  2816. /*
  2817.  * Append current handshake message to current outgoing flight
  2818.  */
  2819. static int ssl_flight_append( mbedtls_ssl_context *ssl )
  2820. {
  2821.     mbedtls_ssl_flight_item *msg;
  2822.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> ssl_flight_append" ) );
  2823.     MBEDTLS_SSL_DEBUG_BUF( 4, "message appended to flight",
  2824.                            ssl->out_msg, ssl->out_msglen );
  2825.  
  2826.     /* Allocate space for current message */
  2827.     if( ( msg = mbedtls_calloc( 1, sizeof(  mbedtls_ssl_flight_item ) ) ) == NULL )
  2828.     {
  2829.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc %d bytes failed",
  2830.                             sizeof( mbedtls_ssl_flight_item ) ) );
  2831.         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
  2832.     }
  2833.  
  2834.     if( ( msg->p = mbedtls_calloc( 1, ssl->out_msglen ) ) == NULL )
  2835.     {
  2836.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc %d bytes failed", ssl->out_msglen ) );
  2837.         mbedtls_free( msg );
  2838.         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
  2839.     }
  2840.  
  2841.     /* Copy current handshake message with headers */
  2842.     memcpy( msg->p, ssl->out_msg, ssl->out_msglen );
  2843.     msg->len = ssl->out_msglen;
  2844.     msg->type = ssl->out_msgtype;
  2845.     msg->next = NULL;
  2846.  
  2847.     /* Append to the current flight */
  2848.     if( ssl->handshake->flight == NULL )
  2849.         ssl->handshake->flight = msg;
  2850.     else
  2851.     {
  2852.         mbedtls_ssl_flight_item *cur = ssl->handshake->flight;
  2853.         while( cur->next != NULL )
  2854.             cur = cur->next;
  2855.         cur->next = msg;
  2856.     }
  2857.  
  2858.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= ssl_flight_append" ) );
  2859.     return( 0 );
  2860. }
  2861.  
  2862. /*
  2863.  * Free the current flight of handshake messages
  2864.  */
  2865. static void ssl_flight_free( mbedtls_ssl_flight_item *flight )
  2866. {
  2867.     mbedtls_ssl_flight_item *cur = flight;
  2868.     mbedtls_ssl_flight_item *next;
  2869.  
  2870.     while( cur != NULL )
  2871.     {
  2872.         next = cur->next;
  2873.  
  2874.         mbedtls_free( cur->p );
  2875.         mbedtls_free( cur );
  2876.  
  2877.         cur = next;
  2878.     }
  2879. }
  2880.  
  2881. #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
  2882. static void ssl_dtls_replay_reset( mbedtls_ssl_context *ssl );
  2883. #endif
  2884.  
  2885. /*
  2886.  * Swap transform_out and out_ctr with the alternative ones
  2887.  */
  2888. static int ssl_swap_epochs( mbedtls_ssl_context *ssl )
  2889. {
  2890.     mbedtls_ssl_transform *tmp_transform;
  2891.     unsigned char tmp_out_ctr[8];
  2892. #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
  2893.     int ret;
  2894. #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
  2895.  
  2896.     if( ssl->transform_out == ssl->handshake->alt_transform_out )
  2897.     {
  2898.         MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip swap epochs" ) );
  2899.         return( 0 );
  2900.     }
  2901.  
  2902.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "swap epochs" ) );
  2903.  
  2904.     /* Swap transforms */
  2905.     tmp_transform                     = ssl->transform_out;
  2906.     ssl->transform_out                = ssl->handshake->alt_transform_out;
  2907.     ssl->handshake->alt_transform_out = tmp_transform;
  2908.  
  2909.     /* Swap epoch + sequence_number */
  2910.     memcpy( tmp_out_ctr,                 ssl->cur_out_ctr,            8 );
  2911.     memcpy( ssl->cur_out_ctr,            ssl->handshake->alt_out_ctr, 8 );
  2912.     memcpy( ssl->handshake->alt_out_ctr, tmp_out_ctr,                 8 );
  2913.  
  2914.     /* Adjust to the newly activated transform */
  2915.     ssl_update_out_pointers( ssl, ssl->transform_out );
  2916.  
  2917. #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
  2918.     if( mbedtls_ssl_hw_record_activate != NULL )
  2919.     {
  2920.         if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_OUTBOUND ) ) != 0 )
  2921.         {
  2922.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret );
  2923.             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
  2924.         }
  2925.     }
  2926. #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
  2927.  
  2928.     return( 0 );
  2929. }
  2930.  
  2931. /*
  2932.  * Retransmit the current flight of messages.
  2933.  */
  2934. int mbedtls_ssl_resend( mbedtls_ssl_context *ssl )
  2935. {
  2936.     int ret = 0;
  2937.  
  2938.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> mbedtls_ssl_resend" ) );
  2939.  
  2940.     ret = mbedtls_ssl_flight_transmit( ssl );
  2941.  
  2942.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= mbedtls_ssl_resend" ) );
  2943.  
  2944.     return( ret );
  2945. }
  2946.  
  2947. /*
  2948.  * Transmit or retransmit the current flight of messages.
  2949.  *
  2950.  * Need to remember the current message in case flush_output returns
  2951.  * WANT_WRITE, causing us to exit this function and come back later.
  2952.  * This function must be called until state is no longer SENDING.
  2953.  */
  2954. int mbedtls_ssl_flight_transmit( mbedtls_ssl_context *ssl )
  2955. {
  2956.     int ret;
  2957.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> mbedtls_ssl_flight_transmit" ) );
  2958.  
  2959.     if( ssl->handshake->retransmit_state != MBEDTLS_SSL_RETRANS_SENDING )
  2960.     {
  2961.         MBEDTLS_SSL_DEBUG_MSG( 2, ( "initialise flight transmission" ) );
  2962.  
  2963.         ssl->handshake->cur_msg = ssl->handshake->flight;
  2964.         ssl->handshake->cur_msg_p = ssl->handshake->flight->p + 12;
  2965.         if( ( ret = ssl_swap_epochs( ssl ) ) != 0 )
  2966.             return( ret );
  2967.  
  2968.         ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_SENDING;
  2969.     }
  2970.  
  2971.     while( ssl->handshake->cur_msg != NULL )
  2972.     {
  2973.         size_t max_frag_len;
  2974.         const mbedtls_ssl_flight_item * const cur = ssl->handshake->cur_msg;
  2975.  
  2976.         int const is_finished =
  2977.             ( cur->type == MBEDTLS_SSL_MSG_HANDSHAKE &&
  2978.               cur->p[0] == MBEDTLS_SSL_HS_FINISHED );
  2979.  
  2980.         uint8_t const force_flush = ssl->disable_datagram_packing == 1 ?
  2981.             SSL_FORCE_FLUSH : SSL_DONT_FORCE_FLUSH;
  2982.  
  2983.         /* Swap epochs before sending Finished: we can't do it after
  2984.          * sending ChangeCipherSpec, in case write returns WANT_READ.
  2985.          * Must be done before copying, may change out_msg pointer */
  2986.         if( is_finished && ssl->handshake->cur_msg_p == ( cur->p + 12 ) )
  2987.         {
  2988.             MBEDTLS_SSL_DEBUG_MSG( 2, ( "swap epochs to send finished message" ) );
  2989.             if( ( ret = ssl_swap_epochs( ssl ) ) != 0 )
  2990.                 return( ret );
  2991.         }
  2992.  
  2993.         ret = ssl_get_remaining_payload_in_datagram( ssl );
  2994.         if( ret < 0 )
  2995.             return( ret );
  2996.         max_frag_len = (size_t) ret;
  2997.  
  2998.         /* CCS is copied as is, while HS messages may need fragmentation */
  2999.         if( cur->type == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC )
  3000.         {
  3001.             if( max_frag_len == 0 )
  3002.             {
  3003.                 if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
  3004.                     return( ret );
  3005.  
  3006.                 continue;
  3007.             }
  3008.  
  3009.             memcpy( ssl->out_msg, cur->p, cur->len );
  3010.             ssl->out_msglen  = cur->len;
  3011.             ssl->out_msgtype = cur->type;
  3012.  
  3013.             /* Update position inside current message */
  3014.             ssl->handshake->cur_msg_p += cur->len;
  3015.         }
  3016.         else
  3017.         {
  3018.             const unsigned char * const p = ssl->handshake->cur_msg_p;
  3019.             const size_t hs_len = cur->len - 12;
  3020.             const size_t frag_off = p - ( cur->p + 12 );
  3021.             const size_t rem_len = hs_len - frag_off;
  3022.             size_t cur_hs_frag_len, max_hs_frag_len;
  3023.  
  3024.             if( ( max_frag_len < 12 ) || ( max_frag_len == 12 && hs_len != 0 ) )
  3025.             {
  3026.                 if( is_finished )
  3027.                 {
  3028.                     if( ( ret = ssl_swap_epochs( ssl ) ) != 0 )
  3029.                         return( ret );
  3030.                 }
  3031.  
  3032.                 if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
  3033.                     return( ret );
  3034.  
  3035.                 continue;
  3036.             }
  3037.             max_hs_frag_len = max_frag_len - 12;
  3038.  
  3039.             cur_hs_frag_len = rem_len > max_hs_frag_len ?
  3040.                 max_hs_frag_len : rem_len;
  3041.  
  3042.             if( frag_off == 0 && cur_hs_frag_len != hs_len )
  3043.             {
  3044.                 MBEDTLS_SSL_DEBUG_MSG( 2, ( "fragmenting handshake message (%u > %u)",
  3045.                                             (unsigned) cur_hs_frag_len,
  3046.                                             (unsigned) max_hs_frag_len ) );
  3047.             }
  3048.  
  3049.             /* Messages are stored with handshake headers as if not fragmented,
  3050.              * copy beginning of headers then fill fragmentation fields.
  3051.              * Handshake headers: type(1) len(3) seq(2) f_off(3) f_len(3) */
  3052.             memcpy( ssl->out_msg, cur->p, 6 );
  3053.  
  3054.             ssl->out_msg[6] = ( ( frag_off >> 16 ) & 0xff );
  3055.             ssl->out_msg[7] = ( ( frag_off >>  8 ) & 0xff );
  3056.             ssl->out_msg[8] = ( ( frag_off       ) & 0xff );
  3057.  
  3058.             ssl->out_msg[ 9] = ( ( cur_hs_frag_len >> 16 ) & 0xff );
  3059.             ssl->out_msg[10] = ( ( cur_hs_frag_len >>  8 ) & 0xff );
  3060.             ssl->out_msg[11] = ( ( cur_hs_frag_len       ) & 0xff );
  3061.  
  3062.             MBEDTLS_SSL_DEBUG_BUF( 3, "handshake header", ssl->out_msg, 12 );
  3063.  
  3064.             /* Copy the handshake message content and set records fields */
  3065.             memcpy( ssl->out_msg + 12, p, cur_hs_frag_len );
  3066.             ssl->out_msglen = cur_hs_frag_len + 12;
  3067.             ssl->out_msgtype = cur->type;
  3068.  
  3069.             /* Update position inside current message */
  3070.             ssl->handshake->cur_msg_p += cur_hs_frag_len;
  3071.         }
  3072.  
  3073.         /* If done with the current message move to the next one if any */
  3074.         if( ssl->handshake->cur_msg_p >= cur->p + cur->len )
  3075.         {
  3076.             if( cur->next != NULL )
  3077.             {
  3078.                 ssl->handshake->cur_msg = cur->next;
  3079.                 ssl->handshake->cur_msg_p = cur->next->p + 12;
  3080.             }
  3081.             else
  3082.             {
  3083.                 ssl->handshake->cur_msg = NULL;
  3084.                 ssl->handshake->cur_msg_p = NULL;
  3085.             }
  3086.         }
  3087.  
  3088.         /* Actually send the message out */
  3089.         if( ( ret = mbedtls_ssl_write_record( ssl, force_flush ) ) != 0 )
  3090.         {
  3091.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
  3092.             return( ret );
  3093.         }
  3094.     }
  3095.  
  3096.     if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
  3097.         return( ret );
  3098.  
  3099.     /* Update state and set timer */
  3100.     if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )
  3101.         ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
  3102.     else
  3103.     {
  3104.         ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
  3105.         ssl_set_timer( ssl, ssl->handshake->retransmit_timeout );
  3106.     }
  3107.  
  3108.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= mbedtls_ssl_flight_transmit" ) );
  3109.  
  3110.     return( 0 );
  3111. }
  3112.  
  3113. /*
  3114.  * To be called when the last message of an incoming flight is received.
  3115.  */
  3116. void mbedtls_ssl_recv_flight_completed( mbedtls_ssl_context *ssl )
  3117. {
  3118.     /* We won't need to resend that one any more */
  3119.     ssl_flight_free( ssl->handshake->flight );
  3120.     ssl->handshake->flight = NULL;
  3121.     ssl->handshake->cur_msg = NULL;
  3122.  
  3123.     /* The next incoming flight will start with this msg_seq */
  3124.     ssl->handshake->in_flight_start_seq = ssl->handshake->in_msg_seq;
  3125.  
  3126.     /* We don't want to remember CCS's across flight boundaries. */
  3127.     ssl->handshake->buffering.seen_ccs = 0;
  3128.  
  3129.     /* Clear future message buffering structure. */
  3130.     ssl_buffering_free( ssl );
  3131.  
  3132.     /* Cancel timer */
  3133.     ssl_set_timer( ssl, 0 );
  3134.  
  3135.     if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
  3136.         ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED )
  3137.     {
  3138.         ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
  3139.     }
  3140.     else
  3141.         ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_PREPARING;
  3142. }
  3143.  
  3144. /*
  3145.  * To be called when the last message of an outgoing flight is send.
  3146.  */
  3147. void mbedtls_ssl_send_flight_completed( mbedtls_ssl_context *ssl )
  3148. {
  3149.     ssl_reset_retransmit_timeout( ssl );
  3150.     ssl_set_timer( ssl, ssl->handshake->retransmit_timeout );
  3151.  
  3152.     if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
  3153.         ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED )
  3154.     {
  3155.         ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
  3156.     }
  3157.     else
  3158.         ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
  3159. }
  3160. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  3161.  
  3162. /*
  3163.  * Handshake layer functions
  3164.  */
  3165.  
  3166. /*
  3167.  * Write (DTLS: or queue) current handshake (including CCS) message.
  3168.  *
  3169.  *  - fill in handshake headers
  3170.  *  - update handshake checksum
  3171.  *  - DTLS: save message for resending
  3172.  *  - then pass to the record layer
  3173.  *
  3174.  * DTLS: except for HelloRequest, messages are only queued, and will only be
  3175.  * actually sent when calling flight_transmit() or resend().
  3176.  *
  3177.  * Inputs:
  3178.  *  - ssl->out_msglen: 4 + actual handshake message len
  3179.  *      (4 is the size of handshake headers for TLS)
  3180.  *  - ssl->out_msg[0]: the handshake type (ClientHello, ServerHello, etc)
  3181.  *  - ssl->out_msg + 4: the handshake message body
  3182.  *
  3183.  * Outputs, ie state before passing to flight_append() or write_record():
  3184.  *   - ssl->out_msglen: the length of the record contents
  3185.  *      (including handshake headers but excluding record headers)
  3186.  *   - ssl->out_msg: the record contents (handshake headers + content)
  3187.  */
  3188. int mbedtls_ssl_write_handshake_msg( mbedtls_ssl_context *ssl )
  3189. {
  3190.     int ret;
  3191.     const size_t hs_len = ssl->out_msglen - 4;
  3192.     const unsigned char hs_type = ssl->out_msg[0];
  3193.  
  3194.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write handshake message" ) );
  3195.  
  3196.     /*
  3197.      * Sanity checks
  3198.      */
  3199.     if( ssl->out_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE          &&
  3200.         ssl->out_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC )
  3201.     {
  3202.         /* In SSLv3, the client might send a NoCertificate alert. */
  3203. #if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_CLI_C)
  3204.         if( ! ( ssl->minor_ver      == MBEDTLS_SSL_MINOR_VERSION_0 &&
  3205.                 ssl->out_msgtype    == MBEDTLS_SSL_MSG_ALERT       &&
  3206.                 ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ) )
  3207. #endif /* MBEDTLS_SSL_PROTO_SSL3 && MBEDTLS_SSL_SRV_C */
  3208.         {
  3209.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  3210.             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  3211.         }
  3212.     }
  3213.  
  3214.     /* Whenever we send anything different from a
  3215.      * HelloRequest we should be in a handshake - double check. */
  3216.     if( ! ( ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
  3217.             hs_type          == MBEDTLS_SSL_HS_HELLO_REQUEST ) &&
  3218.         ssl->handshake == NULL )
  3219.     {
  3220.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  3221.         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  3222.     }
  3223.  
  3224. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  3225.     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  3226.         ssl->handshake != NULL &&
  3227.         ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING )
  3228.     {
  3229.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  3230.         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  3231.     }
  3232. #endif
  3233.  
  3234.     /* Double-check that we did not exceed the bounds
  3235.      * of the outgoing record buffer.
  3236.      * This should never fail as the various message
  3237.      * writing functions must obey the bounds of the
  3238.      * outgoing record buffer, but better be safe.
  3239.      *
  3240.      * Note: We deliberately do not check for the MTU or MFL here.
  3241.      */
  3242.     if( ssl->out_msglen > MBEDTLS_SSL_OUT_CONTENT_LEN )
  3243.     {
  3244.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Record too large: "
  3245.                                     "size %u, maximum %u",
  3246.                                     (unsigned) ssl->out_msglen,
  3247.                                     (unsigned) MBEDTLS_SSL_OUT_CONTENT_LEN ) );
  3248.         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  3249.     }
  3250.  
  3251.     /*
  3252.      * Fill handshake headers
  3253.      */
  3254.     if( ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE )
  3255.     {
  3256.         ssl->out_msg[1] = (unsigned char)( hs_len >> 16 );
  3257.         ssl->out_msg[2] = (unsigned char)( hs_len >>  8 );
  3258.         ssl->out_msg[3] = (unsigned char)( hs_len       );
  3259.  
  3260.         /*
  3261.          * DTLS has additional fields in the Handshake layer,
  3262.          * between the length field and the actual payload:
  3263.          *      uint16 message_seq;
  3264.          *      uint24 fragment_offset;
  3265.          *      uint24 fragment_length;
  3266.          */
  3267. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  3268.         if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  3269.         {
  3270.             /* Make room for the additional DTLS fields */
  3271.             if( MBEDTLS_SSL_OUT_CONTENT_LEN - ssl->out_msglen < 8 )
  3272.             {
  3273.                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS handshake message too large: "
  3274.                               "size %u, maximum %u",
  3275.                                (unsigned) ( hs_len ),
  3276.                                (unsigned) ( MBEDTLS_SSL_OUT_CONTENT_LEN - 12 ) ) );
  3277.                 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  3278.             }
  3279.  
  3280.             memmove( ssl->out_msg + 12, ssl->out_msg + 4, hs_len );
  3281.             ssl->out_msglen += 8;
  3282.  
  3283.             /* Write message_seq and update it, except for HelloRequest */
  3284.             if( hs_type != MBEDTLS_SSL_HS_HELLO_REQUEST )
  3285.             {
  3286.                 ssl->out_msg[4] = ( ssl->handshake->out_msg_seq >> 8 ) & 0xFF;
  3287.                 ssl->out_msg[5] = ( ssl->handshake->out_msg_seq      ) & 0xFF;
  3288.                 ++( ssl->handshake->out_msg_seq );
  3289.             }
  3290.             else
  3291.             {
  3292.                 ssl->out_msg[4] = 0;
  3293.                 ssl->out_msg[5] = 0;
  3294.             }
  3295.  
  3296.             /* Handshake hashes are computed without fragmentation,
  3297.              * so set frag_offset = 0 and frag_len = hs_len for now */
  3298.             memset( ssl->out_msg + 6, 0x00, 3 );
  3299.             memcpy( ssl->out_msg + 9, ssl->out_msg + 1, 3 );
  3300.         }
  3301. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  3302.  
  3303.         /* Update running hashes of handshake messages seen */
  3304.         if( hs_type != MBEDTLS_SSL_HS_HELLO_REQUEST )
  3305.             ssl->handshake->update_checksum( ssl, ssl->out_msg, ssl->out_msglen );
  3306.     }
  3307.  
  3308.     /* Either send now, or just save to be sent (and resent) later */
  3309. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  3310.     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  3311.         ! ( ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
  3312.             hs_type          == MBEDTLS_SSL_HS_HELLO_REQUEST ) )
  3313.     {
  3314.         if( ( ret = ssl_flight_append( ssl ) ) != 0 )
  3315.         {
  3316.             MBEDTLS_SSL_DEBUG_RET( 1, "ssl_flight_append", ret );
  3317.             return( ret );
  3318.         }
  3319.     }
  3320.     else
  3321. #endif
  3322.     {
  3323.         if( ( ret = mbedtls_ssl_write_record( ssl, SSL_FORCE_FLUSH ) ) != 0 )
  3324.         {
  3325.             MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_record", ret );
  3326.             return( ret );
  3327.         }
  3328.     }
  3329.  
  3330.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write handshake message" ) );
  3331.  
  3332.     return( 0 );
  3333. }
  3334.  
  3335. /*
  3336.  * Record layer functions
  3337.  */
  3338.  
  3339. /*
  3340.  * Write current record.
  3341.  *
  3342.  * Uses:
  3343.  *  - ssl->out_msgtype: type of the message (AppData, Handshake, Alert, CCS)
  3344.  *  - ssl->out_msglen: length of the record content (excl headers)
  3345.  *  - ssl->out_msg: record content
  3346.  */
  3347. int mbedtls_ssl_write_record( mbedtls_ssl_context *ssl, uint8_t force_flush )
  3348. {
  3349.     int ret, done = 0;
  3350.     size_t len = ssl->out_msglen;
  3351.     uint8_t flush = force_flush;
  3352.  
  3353.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write record" ) );
  3354.  
  3355. #if defined(MBEDTLS_ZLIB_SUPPORT)
  3356.     if( ssl->transform_out != NULL &&
  3357.         ssl->session_out->compression == MBEDTLS_SSL_COMPRESS_DEFLATE )
  3358.     {
  3359.         if( ( ret = ssl_compress_buf( ssl ) ) != 0 )
  3360.         {
  3361.             MBEDTLS_SSL_DEBUG_RET( 1, "ssl_compress_buf", ret );
  3362.             return( ret );
  3363.         }
  3364.  
  3365.         len = ssl->out_msglen;
  3366.     }
  3367. #endif /*MBEDTLS_ZLIB_SUPPORT */
  3368.  
  3369. #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
  3370.     if( mbedtls_ssl_hw_record_write != NULL )
  3371.     {
  3372.         MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_write()" ) );
  3373.  
  3374.         ret = mbedtls_ssl_hw_record_write( ssl );
  3375.         if( ret != 0 && ret != MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH )
  3376.         {
  3377.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_write", ret );
  3378.             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
  3379.         }
  3380.  
  3381.         if( ret == 0 )
  3382.             done = 1;
  3383.     }
  3384. #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
  3385.     if( !done )
  3386.     {
  3387.         unsigned i;
  3388.         size_t protected_record_size;
  3389.  
  3390.         ssl->out_hdr[0] = (unsigned char) ssl->out_msgtype;
  3391.         mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,
  3392.                            ssl->conf->transport, ssl->out_hdr + 1 );
  3393.  
  3394.         memcpy( ssl->out_ctr, ssl->cur_out_ctr, 8 );
  3395.         ssl->out_len[0] = (unsigned char)( len >> 8 );
  3396.         ssl->out_len[1] = (unsigned char)( len      );
  3397.  
  3398.         if( ssl->transform_out != NULL )
  3399.         {
  3400.             if( ( ret = ssl_encrypt_buf( ssl ) ) != 0 )
  3401.             {
  3402.                 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_encrypt_buf", ret );
  3403.                 return( ret );
  3404.             }
  3405.  
  3406.             len = ssl->out_msglen;
  3407.             ssl->out_len[0] = (unsigned char)( len >> 8 );
  3408.             ssl->out_len[1] = (unsigned char)( len      );
  3409.         }
  3410.  
  3411.         protected_record_size = len + mbedtls_ssl_hdr_len( ssl );
  3412.  
  3413. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  3414.         /* In case of DTLS, double-check that we don't exceed
  3415.          * the remaining space in the datagram. */
  3416.         if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  3417.         {
  3418.             ret = ssl_get_remaining_space_in_datagram( ssl );
  3419.             if( ret < 0 )
  3420.                 return( ret );
  3421.  
  3422.             if( protected_record_size > (size_t) ret )
  3423.             {
  3424.                 /* Should never happen */
  3425.                 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  3426.             }
  3427.         }
  3428. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  3429.  
  3430.         MBEDTLS_SSL_DEBUG_MSG( 3, ( "output record: msgtype = %d, "
  3431.                                     "version = [%d:%d], msglen = %d",
  3432.                                     ssl->out_hdr[0], ssl->out_hdr[1],
  3433.                                     ssl->out_hdr[2], len ) );
  3434.  
  3435.         MBEDTLS_SSL_DEBUG_BUF( 4, "output record sent to network",
  3436.                                ssl->out_hdr, protected_record_size );
  3437.  
  3438.         ssl->out_left += protected_record_size;
  3439.         ssl->out_hdr  += protected_record_size;
  3440.         ssl_update_out_pointers( ssl, ssl->transform_out );
  3441.  
  3442.         for( i = 8; i > ssl_ep_len( ssl ); i-- )
  3443.             if( ++ssl->cur_out_ctr[i - 1] != 0 )
  3444.                 break;
  3445.  
  3446.         /* The loop goes to its end iff the counter is wrapping */
  3447.         if( i == ssl_ep_len( ssl ) )
  3448.         {
  3449.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "outgoing message counter would wrap" ) );
  3450.             return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
  3451.         }
  3452.     }
  3453.  
  3454. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  3455.     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  3456.         flush == SSL_DONT_FORCE_FLUSH )
  3457.     {
  3458.         size_t remaining;
  3459.         ret = ssl_get_remaining_payload_in_datagram( ssl );
  3460.         if( ret < 0 )
  3461.         {
  3462.             MBEDTLS_SSL_DEBUG_RET( 1, "ssl_get_remaining_payload_in_datagram",
  3463.                                    ret );
  3464.             return( ret );
  3465.         }
  3466.  
  3467.         remaining = (size_t) ret;
  3468.         if( remaining == 0 )
  3469.         {
  3470.             flush = SSL_FORCE_FLUSH;
  3471.         }
  3472.         else
  3473.         {
  3474.             MBEDTLS_SSL_DEBUG_MSG( 2, ( "Still %u bytes available in current datagram", (unsigned) remaining ) );
  3475.         }
  3476.     }
  3477. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  3478.  
  3479.     if( ( flush == SSL_FORCE_FLUSH ) &&
  3480.         ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
  3481.     {
  3482.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flush_output", ret );
  3483.         return( ret );
  3484.     }
  3485.  
  3486.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write record" ) );
  3487.  
  3488.     return( 0 );
  3489. }
  3490.  
  3491. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  3492.  
  3493. static int ssl_hs_is_proper_fragment( mbedtls_ssl_context *ssl )
  3494. {
  3495.     if( ssl->in_msglen < ssl->in_hslen ||
  3496.         memcmp( ssl->in_msg + 6, "\0\0\0",        3 ) != 0 ||
  3497.         memcmp( ssl->in_msg + 9, ssl->in_msg + 1, 3 ) != 0 )
  3498.     {
  3499.         return( 1 );
  3500.     }
  3501.     return( 0 );
  3502. }
  3503.  
  3504. static uint32_t ssl_get_hs_frag_len( mbedtls_ssl_context const *ssl )
  3505. {
  3506.     return( ( ssl->in_msg[9] << 16  ) |
  3507.             ( ssl->in_msg[10] << 8  ) |
  3508.               ssl->in_msg[11] );
  3509. }
  3510.  
  3511. static uint32_t ssl_get_hs_frag_off( mbedtls_ssl_context const *ssl )
  3512. {
  3513.     return( ( ssl->in_msg[6] << 16 ) |
  3514.             ( ssl->in_msg[7] << 8  ) |
  3515.               ssl->in_msg[8] );
  3516. }
  3517.  
  3518. static int ssl_check_hs_header( mbedtls_ssl_context const *ssl )
  3519. {
  3520.     uint32_t msg_len, frag_off, frag_len;
  3521.  
  3522.     msg_len  = ssl_get_hs_total_len( ssl );
  3523.     frag_off = ssl_get_hs_frag_off( ssl );
  3524.     frag_len = ssl_get_hs_frag_len( ssl );
  3525.  
  3526.     if( frag_off > msg_len )
  3527.         return( -1 );
  3528.  
  3529.     if( frag_len > msg_len - frag_off )
  3530.         return( -1 );
  3531.  
  3532.     if( frag_len + 12 > ssl->in_msglen )
  3533.         return( -1 );
  3534.  
  3535.     return( 0 );
  3536. }
  3537.  
  3538. /*
  3539.  * Mark bits in bitmask (used for DTLS HS reassembly)
  3540.  */
  3541. static void ssl_bitmask_set( unsigned char *mask, size_t offset, size_t len )
  3542. {
  3543.     unsigned int start_bits, end_bits;
  3544.  
  3545.     start_bits = 8 - ( offset % 8 );
  3546.     if( start_bits != 8 )
  3547.     {
  3548.         size_t first_byte_idx = offset / 8;
  3549.  
  3550.         /* Special case */
  3551.         if( len <= start_bits )
  3552.         {
  3553.             for( ; len != 0; len-- )
  3554.                 mask[first_byte_idx] |= 1 << ( start_bits - len );
  3555.  
  3556.             /* Avoid potential issues with offset or len becoming invalid */
  3557.             return;
  3558.         }
  3559.  
  3560.         offset += start_bits; /* Now offset % 8 == 0 */
  3561.         len -= start_bits;
  3562.  
  3563.         for( ; start_bits != 0; start_bits-- )
  3564.             mask[first_byte_idx] |= 1 << ( start_bits - 1 );
  3565.     }
  3566.  
  3567.     end_bits = len % 8;
  3568.     if( end_bits != 0 )
  3569.     {
  3570.         size_t last_byte_idx = ( offset + len ) / 8;
  3571.  
  3572.         len -= end_bits; /* Now len % 8 == 0 */
  3573.  
  3574.         for( ; end_bits != 0; end_bits-- )
  3575.             mask[last_byte_idx] |= 1 << ( 8 - end_bits );
  3576.     }
  3577.  
  3578.     memset( mask + offset / 8, 0xFF, len / 8 );
  3579. }
  3580.  
  3581. /*
  3582.  * Check that bitmask is full
  3583.  */
  3584. static int ssl_bitmask_check( unsigned char *mask, size_t len )
  3585. {
  3586.     size_t i;
  3587.  
  3588.     for( i = 0; i < len / 8; i++ )
  3589.         if( mask[i] != 0xFF )
  3590.             return( -1 );
  3591.  
  3592.     for( i = 0; i < len % 8; i++ )
  3593.         if( ( mask[len / 8] & ( 1 << ( 7 - i ) ) ) == 0 )
  3594.             return( -1 );
  3595.  
  3596.     return( 0 );
  3597. }
  3598.  
  3599. /* msg_len does not include the handshake header */
  3600. static size_t ssl_get_reassembly_buffer_size( size_t msg_len,
  3601.                                               unsigned add_bitmap )
  3602. {
  3603.     size_t alloc_len;
  3604.  
  3605.     alloc_len  = 12;                                 /* Handshake header */
  3606.     alloc_len += msg_len;                            /* Content buffer   */
  3607.  
  3608.     if( add_bitmap )
  3609.         alloc_len += msg_len / 8 + ( msg_len % 8 != 0 ); /* Bitmap       */
  3610.  
  3611.     return( alloc_len );
  3612. }
  3613.  
  3614. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  3615.  
  3616. static uint32_t ssl_get_hs_total_len( mbedtls_ssl_context const *ssl )
  3617. {
  3618.     return( ( ssl->in_msg[1] << 16 ) |
  3619.             ( ssl->in_msg[2] << 8  ) |
  3620.               ssl->in_msg[3] );
  3621. }
  3622.  
  3623. int mbedtls_ssl_prepare_handshake_record( mbedtls_ssl_context *ssl )
  3624. {
  3625.     if( ssl->in_msglen < mbedtls_ssl_hs_hdr_len( ssl ) )
  3626.     {
  3627.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake message too short: %d",
  3628.                             ssl->in_msglen ) );
  3629.         return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  3630.     }
  3631.  
  3632.     ssl->in_hslen = mbedtls_ssl_hs_hdr_len( ssl ) + ssl_get_hs_total_len( ssl );
  3633.  
  3634.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "handshake message: msglen ="
  3635.                         " %d, type = %d, hslen = %d",
  3636.                         ssl->in_msglen, ssl->in_msg[0], ssl->in_hslen ) );
  3637.  
  3638. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  3639.     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  3640.     {
  3641.         int ret;
  3642.         unsigned int recv_msg_seq = ( ssl->in_msg[4] << 8 ) | ssl->in_msg[5];
  3643.  
  3644.         if( ssl_check_hs_header( ssl ) != 0 )
  3645.         {
  3646.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid handshake header" ) );
  3647.             return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  3648.         }
  3649.  
  3650.         if( ssl->handshake != NULL &&
  3651.             ( ( ssl->state   != MBEDTLS_SSL_HANDSHAKE_OVER &&
  3652.                 recv_msg_seq != ssl->handshake->in_msg_seq ) ||
  3653.               ( ssl->state  == MBEDTLS_SSL_HANDSHAKE_OVER &&
  3654.                 ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_HELLO ) ) )
  3655.         {
  3656.             if( recv_msg_seq > ssl->handshake->in_msg_seq )
  3657.             {
  3658.                 MBEDTLS_SSL_DEBUG_MSG( 2, ( "received future handshake message of sequence number %u (next %u)",
  3659.                                             recv_msg_seq,
  3660.                                             ssl->handshake->in_msg_seq ) );
  3661.                 return( MBEDTLS_ERR_SSL_EARLY_MESSAGE );
  3662.             }
  3663.  
  3664.             /* Retransmit only on last message from previous flight, to avoid
  3665.              * too many retransmissions.
  3666.              * Besides, No sane server ever retransmits HelloVerifyRequest */
  3667.             if( recv_msg_seq == ssl->handshake->in_flight_start_seq - 1 &&
  3668.                 ssl->in_msg[0] != MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST )
  3669.             {
  3670.                 MBEDTLS_SSL_DEBUG_MSG( 2, ( "received message from last flight, "
  3671.                                     "message_seq = %d, start_of_flight = %d",
  3672.                                     recv_msg_seq,
  3673.                                     ssl->handshake->in_flight_start_seq ) );
  3674.  
  3675.                 if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )
  3676.                 {
  3677.                     MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend", ret );
  3678.                     return( ret );
  3679.                 }
  3680.             }
  3681.             else
  3682.             {
  3683.                 MBEDTLS_SSL_DEBUG_MSG( 2, ( "dropping out-of-sequence message: "
  3684.                                     "message_seq = %d, expected = %d",
  3685.                                     recv_msg_seq,
  3686.                                     ssl->handshake->in_msg_seq ) );
  3687.             }
  3688.  
  3689.             return( MBEDTLS_ERR_SSL_CONTINUE_PROCESSING );
  3690.         }
  3691.         /* Wait until message completion to increment in_msg_seq */
  3692.  
  3693.         /* Message reassembly is handled alongside buffering of future
  3694.          * messages; the commonality is that both handshake fragments and
  3695.          * future messages cannot be forwarded immediately to the
  3696.          * handshake logic layer. */
  3697.         if( ssl_hs_is_proper_fragment( ssl ) == 1 )
  3698.         {
  3699.             MBEDTLS_SSL_DEBUG_MSG( 2, ( "found fragmented DTLS handshake message" ) );
  3700.             return( MBEDTLS_ERR_SSL_EARLY_MESSAGE );
  3701.         }
  3702.     }
  3703.     else
  3704. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  3705.     /* With TLS we don't handle fragmentation (for now) */
  3706.     if( ssl->in_msglen < ssl->in_hslen )
  3707.     {
  3708.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "TLS handshake fragmentation not supported" ) );
  3709.         return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
  3710.     }
  3711.  
  3712.     return( 0 );
  3713. }
  3714.  
  3715. void mbedtls_ssl_update_handshake_status( mbedtls_ssl_context *ssl )
  3716. {
  3717.     mbedtls_ssl_handshake_params * const hs = ssl->handshake;
  3718.  
  3719.     if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER && hs != NULL )
  3720.     {
  3721.         ssl->handshake->update_checksum( ssl, ssl->in_msg, ssl->in_hslen );
  3722.     }
  3723.  
  3724.     /* Handshake message is complete, increment counter */
  3725. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  3726.     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  3727.         ssl->handshake != NULL )
  3728.     {
  3729.         unsigned offset;
  3730.         mbedtls_ssl_hs_buffer *hs_buf;
  3731.  
  3732.         /* Increment handshake sequence number */
  3733.         hs->in_msg_seq++;
  3734.  
  3735.         /*
  3736.          * Clear up handshake buffering and reassembly structure.
  3737.          */
  3738.  
  3739.         /* Free first entry */
  3740.         ssl_buffering_free_slot( ssl, 0 );
  3741.  
  3742.         /* Shift all other entries */
  3743.         for( offset = 0, hs_buf = &hs->buffering.hs[0];
  3744.              offset + 1 < MBEDTLS_SSL_MAX_BUFFERED_HS;
  3745.              offset++, hs_buf++ )
  3746.         {
  3747.             *hs_buf = *(hs_buf + 1);
  3748.         }
  3749.  
  3750.         /* Create a fresh last entry */
  3751.         memset( hs_buf, 0, sizeof( mbedtls_ssl_hs_buffer ) );
  3752.     }
  3753. #endif
  3754. }
  3755.  
  3756. /*
  3757.  * DTLS anti-replay: RFC 6347 4.1.2.6
  3758.  *
  3759.  * in_window is a field of bits numbered from 0 (lsb) to 63 (msb).
  3760.  * Bit n is set iff record number in_window_top - n has been seen.
  3761.  *
  3762.  * Usually, in_window_top is the last record number seen and the lsb of
  3763.  * in_window is set. The only exception is the initial state (record number 0
  3764.  * not seen yet).
  3765.  */
  3766. #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
  3767. static void ssl_dtls_replay_reset( mbedtls_ssl_context *ssl )
  3768. {
  3769.     ssl->in_window_top = 0;
  3770.     ssl->in_window = 0;
  3771. }
  3772.  
  3773. static inline uint64_t ssl_load_six_bytes( unsigned char *buf )
  3774. {
  3775.     return( ( (uint64_t) buf[0] << 40 ) |
  3776.             ( (uint64_t) buf[1] << 32 ) |
  3777.             ( (uint64_t) buf[2] << 24 ) |
  3778.             ( (uint64_t) buf[3] << 16 ) |
  3779.             ( (uint64_t) buf[4] <<  8 ) |
  3780.             ( (uint64_t) buf[5]       ) );
  3781. }
  3782.  
  3783. /*
  3784.  * Return 0 if sequence number is acceptable, -1 otherwise
  3785.  */
  3786. int mbedtls_ssl_dtls_replay_check( mbedtls_ssl_context *ssl )
  3787. {
  3788.     uint64_t rec_seqnum = ssl_load_six_bytes( ssl->in_ctr + 2 );
  3789.     uint64_t bit;
  3790.  
  3791.     if( ssl->conf->anti_replay == MBEDTLS_SSL_ANTI_REPLAY_DISABLED )
  3792.         return( 0 );
  3793.  
  3794.     if( rec_seqnum > ssl->in_window_top )
  3795.         return( 0 );
  3796.  
  3797.     bit = ssl->in_window_top - rec_seqnum;
  3798.  
  3799.     if( bit >= 64 )
  3800.         return( -1 );
  3801.  
  3802.     if( ( ssl->in_window & ( (uint64_t) 1 << bit ) ) != 0 )
  3803.         return( -1 );
  3804.  
  3805.     return( 0 );
  3806. }
  3807.  
  3808. /*
  3809.  * Update replay window on new validated record
  3810.  */
  3811. void mbedtls_ssl_dtls_replay_update( mbedtls_ssl_context *ssl )
  3812. {
  3813.     uint64_t rec_seqnum = ssl_load_six_bytes( ssl->in_ctr + 2 );
  3814.  
  3815.     if( ssl->conf->anti_replay == MBEDTLS_SSL_ANTI_REPLAY_DISABLED )
  3816.         return;
  3817.  
  3818.     if( rec_seqnum > ssl->in_window_top )
  3819.     {
  3820.         /* Update window_top and the contents of the window */
  3821.         uint64_t shift = rec_seqnum - ssl->in_window_top;
  3822.  
  3823.         if( shift >= 64 )
  3824.             ssl->in_window = 1;
  3825.         else
  3826.         {
  3827.             ssl->in_window <<= shift;
  3828.             ssl->in_window |= 1;
  3829.         }
  3830.  
  3831.         ssl->in_window_top = rec_seqnum;
  3832.     }
  3833.     else
  3834.     {
  3835.         /* Mark that number as seen in the current window */
  3836.         uint64_t bit = ssl->in_window_top - rec_seqnum;
  3837.  
  3838.         if( bit < 64 ) /* Always true, but be extra sure */
  3839.             ssl->in_window |= (uint64_t) 1 << bit;
  3840.     }
  3841. }
  3842. #endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */
  3843.  
  3844. #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
  3845. /* Forward declaration */
  3846. static int ssl_session_reset_int( mbedtls_ssl_context *ssl, int partial );
  3847.  
  3848. /*
  3849.  * Without any SSL context, check if a datagram looks like a ClientHello with
  3850.  * a valid cookie, and if it doesn't, generate a HelloVerifyRequest message.
  3851.  * Both input and output include full DTLS headers.
  3852.  *
  3853.  * - if cookie is valid, return 0
  3854.  * - if ClientHello looks superficially valid but cookie is not,
  3855.  *   fill obuf and set olen, then
  3856.  *   return MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED
  3857.  * - otherwise return a specific error code
  3858.  */
  3859. static int ssl_check_dtls_clihlo_cookie(
  3860.                            mbedtls_ssl_cookie_write_t *f_cookie_write,
  3861.                            mbedtls_ssl_cookie_check_t *f_cookie_check,
  3862.                            void *p_cookie,
  3863.                            const unsigned char *cli_id, size_t cli_id_len,
  3864.                            const unsigned char *in, size_t in_len,
  3865.                            unsigned char *obuf, size_t buf_len, size_t *olen )
  3866. {
  3867.     size_t sid_len, cookie_len;
  3868.     unsigned char *p;
  3869.  
  3870.     if( f_cookie_write == NULL || f_cookie_check == NULL )
  3871.         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  3872.  
  3873.     /*
  3874.      * Structure of ClientHello with record and handshake headers,
  3875.      * and expected values. We don't need to check a lot, more checks will be
  3876.      * done when actually parsing the ClientHello - skipping those checks
  3877.      * avoids code duplication and does not make cookie forging any easier.
  3878.      *
  3879.      *  0-0  ContentType type;                  copied, must be handshake
  3880.      *  1-2  ProtocolVersion version;           copied
  3881.      *  3-4  uint16 epoch;                      copied, must be 0
  3882.      *  5-10 uint48 sequence_number;            copied
  3883.      * 11-12 uint16 length;                     (ignored)
  3884.      *
  3885.      * 13-13 HandshakeType msg_type;            (ignored)
  3886.      * 14-16 uint24 length;                     (ignored)
  3887.      * 17-18 uint16 message_seq;                copied
  3888.      * 19-21 uint24 fragment_offset;            copied, must be 0
  3889.      * 22-24 uint24 fragment_length;            (ignored)
  3890.      *
  3891.      * 25-26 ProtocolVersion client_version;    (ignored)
  3892.      * 27-58 Random random;                     (ignored)
  3893.      * 59-xx SessionID session_id;              1 byte len + sid_len content
  3894.      * 60+   opaque cookie<0..2^8-1>;           1 byte len + content
  3895.      *       ...
  3896.      *
  3897.      * Minimum length is 61 bytes.
  3898.      */
  3899.     if( in_len < 61 ||
  3900.         in[0] != MBEDTLS_SSL_MSG_HANDSHAKE ||
  3901.         in[3] != 0 || in[4] != 0 ||
  3902.         in[19] != 0 || in[20] != 0 || in[21] != 0 )
  3903.     {
  3904.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  3905.     }
  3906.  
  3907.     sid_len = in[59];
  3908.     if( sid_len > in_len - 61 )
  3909.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  3910.  
  3911.     cookie_len = in[60 + sid_len];
  3912.     if( cookie_len > in_len - 60 )
  3913.         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
  3914.  
  3915.     if( f_cookie_check( p_cookie, in + sid_len + 61, cookie_len,
  3916.                         cli_id, cli_id_len ) == 0 )
  3917.     {
  3918.         /* Valid cookie */
  3919.         return( 0 );
  3920.     }
  3921.  
  3922.     /*
  3923.      * If we get here, we've got an invalid cookie, let's prepare HVR.
  3924.      *
  3925.      *  0-0  ContentType type;                  copied
  3926.      *  1-2  ProtocolVersion version;           copied
  3927.      *  3-4  uint16 epoch;                      copied
  3928.      *  5-10 uint48 sequence_number;            copied
  3929.      * 11-12 uint16 length;                     olen - 13
  3930.      *
  3931.      * 13-13 HandshakeType msg_type;            hello_verify_request
  3932.      * 14-16 uint24 length;                     olen - 25
  3933.      * 17-18 uint16 message_seq;                copied
  3934.      * 19-21 uint24 fragment_offset;            copied
  3935.      * 22-24 uint24 fragment_length;            olen - 25
  3936.      *
  3937.      * 25-26 ProtocolVersion server_version;    0xfe 0xff
  3938.      * 27-27 opaque cookie<0..2^8-1>;           cookie_len = olen - 27, cookie
  3939.      *
  3940.      * Minimum length is 28.
  3941.      */
  3942.     if( buf_len < 28 )
  3943.         return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
  3944.  
  3945.     /* Copy most fields and adapt others */
  3946.     memcpy( obuf, in, 25 );
  3947.     obuf[13] = MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST;
  3948.     obuf[25] = 0xfe;
  3949.     obuf[26] = 0xff;
  3950.  
  3951.     /* Generate and write actual cookie */
  3952.     p = obuf + 28;
  3953.     if( f_cookie_write( p_cookie,
  3954.                         &p, obuf + buf_len, cli_id, cli_id_len ) != 0 )
  3955.     {
  3956.         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  3957.     }
  3958.  
  3959.     *olen = p - obuf;
  3960.  
  3961.     /* Go back and fill length fields */
  3962.     obuf[27] = (unsigned char)( *olen - 28 );
  3963.  
  3964.     obuf[14] = obuf[22] = (unsigned char)( ( *olen - 25 ) >> 16 );
  3965.     obuf[15] = obuf[23] = (unsigned char)( ( *olen - 25 ) >>  8 );
  3966.     obuf[16] = obuf[24] = (unsigned char)( ( *olen - 25 )       );
  3967.  
  3968.     obuf[11] = (unsigned char)( ( *olen - 13 ) >>  8 );
  3969.     obuf[12] = (unsigned char)( ( *olen - 13 )       );
  3970.  
  3971.     return( MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED );
  3972. }
  3973.  
  3974. /*
  3975.  * Handle possible client reconnect with the same UDP quadruplet
  3976.  * (RFC 6347 Section 4.2.8).
  3977.  *
  3978.  * Called by ssl_parse_record_header() in case we receive an epoch 0 record
  3979.  * that looks like a ClientHello.
  3980.  *
  3981.  * - if the input looks like a ClientHello without cookies,
  3982.  *   send back HelloVerifyRequest, then
  3983.  *   return MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED
  3984.  * - if the input looks like a ClientHello with a valid cookie,
  3985.  *   reset the session of the current context, and
  3986.  *   return MBEDTLS_ERR_SSL_CLIENT_RECONNECT
  3987.  * - if anything goes wrong, return a specific error code
  3988.  *
  3989.  * mbedtls_ssl_read_record() will ignore the record if anything else than
  3990.  * MBEDTLS_ERR_SSL_CLIENT_RECONNECT or 0 is returned, although this function
  3991.  * cannot not return 0.
  3992.  */
  3993. static int ssl_handle_possible_reconnect( mbedtls_ssl_context *ssl )
  3994. {
  3995.     int ret;
  3996.     size_t len;
  3997.  
  3998.     ret = ssl_check_dtls_clihlo_cookie(
  3999.             ssl->conf->f_cookie_write,
  4000.             ssl->conf->f_cookie_check,
  4001.             ssl->conf->p_cookie,
  4002.             ssl->cli_id, ssl->cli_id_len,
  4003.             ssl->in_buf, ssl->in_left,
  4004.             ssl->out_buf, MBEDTLS_SSL_OUT_CONTENT_LEN, &len );
  4005.  
  4006.     MBEDTLS_SSL_DEBUG_RET( 2, "ssl_check_dtls_clihlo_cookie", ret );
  4007.  
  4008.     if( ret == MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED )
  4009.     {
  4010.         int send_ret;
  4011.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "sending HelloVerifyRequest" ) );
  4012.         MBEDTLS_SSL_DEBUG_BUF( 4, "output record sent to network",
  4013.                                   ssl->out_buf, len );
  4014.         /* Don't check write errors as we can't do anything here.
  4015.          * If the error is permanent we'll catch it later,
  4016.          * if it's not, then hopefully it'll work next time. */
  4017.         send_ret = ssl->f_send( ssl->p_bio, ssl->out_buf, len );
  4018.         MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_send", send_ret );
  4019.         (void) send_ret;
  4020.  
  4021.         return( MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED );
  4022.     }
  4023.  
  4024.     if( ret == 0 )
  4025.     {
  4026.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "cookie is valid, resetting context" ) );
  4027.         if( ( ret = ssl_session_reset_int( ssl, 1 ) ) != 0 )
  4028.         {
  4029.             MBEDTLS_SSL_DEBUG_RET( 1, "reset", ret );
  4030.             return( ret );
  4031.         }
  4032.  
  4033.         return( MBEDTLS_ERR_SSL_CLIENT_RECONNECT );
  4034.     }
  4035.  
  4036.     return( ret );
  4037. }
  4038. #endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */
  4039.  
  4040. /*
  4041.  * ContentType type;
  4042.  * ProtocolVersion version;
  4043.  * uint16 epoch;            // DTLS only
  4044.  * uint48 sequence_number;  // DTLS only
  4045.  * uint16 length;
  4046.  *
  4047.  * Return 0 if header looks sane (and, for DTLS, the record is expected)
  4048.  * MBEDTLS_ERR_SSL_INVALID_RECORD if the header looks bad,
  4049.  * MBEDTLS_ERR_SSL_UNEXPECTED_RECORD (DTLS only) if sane but unexpected.
  4050.  *
  4051.  * With DTLS, mbedtls_ssl_read_record() will:
  4052.  * 1. proceed with the record if this function returns 0
  4053.  * 2. drop only the current record if this function returns UNEXPECTED_RECORD
  4054.  * 3. return CLIENT_RECONNECT if this function return that value
  4055.  * 4. drop the whole datagram if this function returns anything else.
  4056.  * Point 2 is needed when the peer is resending, and we have already received
  4057.  * the first record from a datagram but are still waiting for the others.
  4058.  */
  4059. static int ssl_parse_record_header( mbedtls_ssl_context *ssl )
  4060. {
  4061.     int major_ver, minor_ver;
  4062.  
  4063.     MBEDTLS_SSL_DEBUG_BUF( 4, "input record header", ssl->in_hdr, mbedtls_ssl_hdr_len( ssl ) );
  4064.  
  4065.     ssl->in_msgtype =  ssl->in_hdr[0];
  4066.     ssl->in_msglen = ( ssl->in_len[0] << 8 ) | ssl->in_len[1];
  4067.     mbedtls_ssl_read_version( &major_ver, &minor_ver, ssl->conf->transport, ssl->in_hdr + 1 );
  4068.  
  4069.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "input record: msgtype = %d, "
  4070.                         "version = [%d:%d], msglen = %d",
  4071.                         ssl->in_msgtype,
  4072.                         major_ver, minor_ver, ssl->in_msglen ) );
  4073.  
  4074.     /* Check record type */
  4075.     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE &&
  4076.         ssl->in_msgtype != MBEDTLS_SSL_MSG_ALERT &&
  4077.         ssl->in_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC &&
  4078.         ssl->in_msgtype != MBEDTLS_SSL_MSG_APPLICATION_DATA )
  4079.     {
  4080.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "unknown record type" ) );
  4081.  
  4082. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4083.         /* Silently ignore invalid DTLS records as recommended by RFC 6347
  4084.          * Section 4.1.2.7 */
  4085.         if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  4086. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  4087.             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  4088.                                     MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
  4089.  
  4090.         return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  4091.     }
  4092.  
  4093.     /* Check version */
  4094.     if( major_ver != ssl->major_ver )
  4095.     {
  4096.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "major version mismatch" ) );
  4097.         return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  4098.     }
  4099.  
  4100.     if( minor_ver > ssl->conf->max_minor_ver )
  4101.     {
  4102.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "minor version mismatch" ) );
  4103.         return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  4104.     }
  4105.  
  4106.     /* Check length against the size of our buffer */
  4107.     if( ssl->in_msglen > MBEDTLS_SSL_IN_BUFFER_LEN
  4108.                          - (size_t)( ssl->in_msg - ssl->in_buf ) )
  4109.     {
  4110.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
  4111.         return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  4112.     }
  4113.  
  4114.     /*
  4115.      * DTLS-related tests.
  4116.      * Check epoch before checking length constraint because
  4117.      * the latter varies with the epoch. E.g., if a ChangeCipherSpec
  4118.      * message gets duplicated before the corresponding Finished message,
  4119.      * the second ChangeCipherSpec should be discarded because it belongs
  4120.      * to an old epoch, but not because its length is shorter than
  4121.      * the minimum record length for packets using the new record transform.
  4122.      * Note that these two kinds of failures are handled differently,
  4123.      * as an unexpected record is silently skipped but an invalid
  4124.      * record leads to the entire datagram being dropped.
  4125.      */
  4126. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4127.     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  4128.     {
  4129.         unsigned int rec_epoch = ( ssl->in_ctr[0] << 8 ) | ssl->in_ctr[1];
  4130.  
  4131.         /* Check epoch (and sequence number) with DTLS */
  4132.         if( rec_epoch != ssl->in_epoch )
  4133.         {
  4134.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "record from another epoch: "
  4135.                                         "expected %d, received %d",
  4136.                                         ssl->in_epoch, rec_epoch ) );
  4137.  
  4138. #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
  4139.             /*
  4140.              * Check for an epoch 0 ClientHello. We can't use in_msg here to
  4141.              * access the first byte of record content (handshake type), as we
  4142.              * have an active transform (possibly iv_len != 0), so use the
  4143.              * fact that the record header len is 13 instead.
  4144.              */
  4145.             if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
  4146.                 ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER &&
  4147.                 rec_epoch == 0 &&
  4148.                 ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
  4149.                 ssl->in_left > 13 &&
  4150.                 ssl->in_buf[13] == MBEDTLS_SSL_HS_CLIENT_HELLO )
  4151.             {
  4152.                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "possible client reconnect "
  4153.                                             "from the same port" ) );
  4154.                 return( ssl_handle_possible_reconnect( ssl ) );
  4155.             }
  4156.             else
  4157. #endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */
  4158.             {
  4159.                 /* Consider buffering the record. */
  4160.                 if( rec_epoch == (unsigned int) ssl->in_epoch + 1 )
  4161.                 {
  4162.                     MBEDTLS_SSL_DEBUG_MSG( 2, ( "Consider record for buffering" ) );
  4163.                     return( MBEDTLS_ERR_SSL_EARLY_MESSAGE );
  4164.                 }
  4165.  
  4166.                 return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD );
  4167.             }
  4168.         }
  4169.  
  4170. #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
  4171.         /* Replay detection only works for the current epoch */
  4172.         if( rec_epoch == ssl->in_epoch &&
  4173.             mbedtls_ssl_dtls_replay_check( ssl ) != 0 )
  4174.         {
  4175.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "replayed record" ) );
  4176.             return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD );
  4177.         }
  4178. #endif
  4179.  
  4180.         /* Drop unexpected ApplicationData records,
  4181.          * except at the beginning of renegotiations */
  4182.         if( ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA &&
  4183.             ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER
  4184. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  4185.             && ! ( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
  4186.                    ssl->state == MBEDTLS_SSL_SERVER_HELLO )
  4187. #endif
  4188.             )
  4189.         {
  4190.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "dropping unexpected ApplicationData" ) );
  4191.             return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD );
  4192.         }
  4193.     }
  4194. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  4195.  
  4196.  
  4197.     /* Check length against bounds of the current transform and version */
  4198.     if( ssl->transform_in == NULL )
  4199.     {
  4200.         if( ssl->in_msglen < 1 ||
  4201.             ssl->in_msglen > MBEDTLS_SSL_IN_CONTENT_LEN )
  4202.         {
  4203.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
  4204.             return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  4205.         }
  4206.     }
  4207.     else
  4208.     {
  4209.         if( ssl->in_msglen < ssl->transform_in->minlen )
  4210.         {
  4211.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
  4212.             return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  4213.         }
  4214.  
  4215. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  4216.         if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 &&
  4217.             ssl->in_msglen > ssl->transform_in->minlen + MBEDTLS_SSL_IN_CONTENT_LEN )
  4218.         {
  4219.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
  4220.             return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  4221.         }
  4222. #endif
  4223. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
  4224.     defined(MBEDTLS_SSL_PROTO_TLS1_2)
  4225.         /*
  4226.          * TLS encrypted messages can have up to 256 bytes of padding
  4227.          */
  4228.         if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 &&
  4229.             ssl->in_msglen > ssl->transform_in->minlen +
  4230.                              MBEDTLS_SSL_IN_CONTENT_LEN + 256 )
  4231.         {
  4232.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
  4233.             return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  4234.         }
  4235. #endif
  4236.     }
  4237.  
  4238.     return( 0 );
  4239. }
  4240.  
  4241. /*
  4242.  * If applicable, decrypt (and decompress) record content
  4243.  */
  4244. static int ssl_prepare_record_content( mbedtls_ssl_context *ssl )
  4245. {
  4246.     int ret, done = 0;
  4247.  
  4248.     MBEDTLS_SSL_DEBUG_BUF( 4, "input record from network",
  4249.                    ssl->in_hdr, mbedtls_ssl_hdr_len( ssl ) + ssl->in_msglen );
  4250.  
  4251. #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
  4252.     if( mbedtls_ssl_hw_record_read != NULL )
  4253.     {
  4254.         MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_read()" ) );
  4255.  
  4256.         ret = mbedtls_ssl_hw_record_read( ssl );
  4257.         if( ret != 0 && ret != MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH )
  4258.         {
  4259.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_read", ret );
  4260.             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
  4261.         }
  4262.  
  4263.         if( ret == 0 )
  4264.             done = 1;
  4265.     }
  4266. #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
  4267.     if( !done && ssl->transform_in != NULL )
  4268.     {
  4269.         if( ( ret = ssl_decrypt_buf( ssl ) ) != 0 )
  4270.         {
  4271.             MBEDTLS_SSL_DEBUG_RET( 1, "ssl_decrypt_buf", ret );
  4272.             return( ret );
  4273.         }
  4274.  
  4275.         MBEDTLS_SSL_DEBUG_BUF( 4, "input payload after decrypt",
  4276.                        ssl->in_msg, ssl->in_msglen );
  4277.  
  4278.         if( ssl->in_msglen > MBEDTLS_SSL_IN_CONTENT_LEN )
  4279.         {
  4280.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
  4281.             return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  4282.         }
  4283.     }
  4284.  
  4285. #if defined(MBEDTLS_ZLIB_SUPPORT)
  4286.     if( ssl->transform_in != NULL &&
  4287.         ssl->session_in->compression == MBEDTLS_SSL_COMPRESS_DEFLATE )
  4288.     {
  4289.         if( ( ret = ssl_decompress_buf( ssl ) ) != 0 )
  4290.         {
  4291.             MBEDTLS_SSL_DEBUG_RET( 1, "ssl_decompress_buf", ret );
  4292.             return( ret );
  4293.         }
  4294.     }
  4295. #endif /* MBEDTLS_ZLIB_SUPPORT */
  4296.  
  4297. #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
  4298.     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  4299.     {
  4300.         mbedtls_ssl_dtls_replay_update( ssl );
  4301.     }
  4302. #endif
  4303.  
  4304.     return( 0 );
  4305. }
  4306.  
  4307. static void ssl_handshake_wrapup_free_hs_transform( mbedtls_ssl_context *ssl );
  4308.  
  4309. /*
  4310.  * Read a record.
  4311.  *
  4312.  * Silently ignore non-fatal alert (and for DTLS, invalid records as well,
  4313.  * RFC 6347 4.1.2.7) and continue reading until a valid record is found.
  4314.  *
  4315.  */
  4316.  
  4317. /* Helper functions for mbedtls_ssl_read_record(). */
  4318. static int ssl_consume_current_message( mbedtls_ssl_context *ssl );
  4319. static int ssl_get_next_record( mbedtls_ssl_context *ssl );
  4320. static int ssl_record_is_in_progress( mbedtls_ssl_context *ssl );
  4321.  
  4322. int mbedtls_ssl_read_record( mbedtls_ssl_context *ssl,
  4323.                              unsigned update_hs_digest )
  4324. {
  4325.     int ret;
  4326.  
  4327.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> read record" ) );
  4328.  
  4329.     if( ssl->keep_current_message == 0 )
  4330.     {
  4331.         do {
  4332.  
  4333.             ret = ssl_consume_current_message( ssl );
  4334.             if( ret != 0 )
  4335.                 return( ret );
  4336.  
  4337.             if( ssl_record_is_in_progress( ssl ) == 0 )
  4338.             {
  4339. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4340.                 int have_buffered = 0;
  4341.  
  4342.                 /* We only check for buffered messages if the
  4343.                  * current datagram is fully consumed. */
  4344.                 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  4345.                     ssl_next_record_is_in_datagram( ssl ) == 0 )
  4346.                 {
  4347.                     if( ssl_load_buffered_message( ssl ) == 0 )
  4348.                         have_buffered = 1;
  4349.                 }
  4350.  
  4351.                 if( have_buffered == 0 )
  4352. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  4353.                 {
  4354.                     ret = ssl_get_next_record( ssl );
  4355.                     if( ret == MBEDTLS_ERR_SSL_CONTINUE_PROCESSING )
  4356.                         continue;
  4357.  
  4358.                     if( ret != 0 )
  4359.                     {
  4360.                         MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_get_next_record" ), ret );
  4361.                         return( ret );
  4362.                     }
  4363.                 }
  4364.             }
  4365.  
  4366.             ret = mbedtls_ssl_handle_message_type( ssl );
  4367.  
  4368. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4369.             if( ret == MBEDTLS_ERR_SSL_EARLY_MESSAGE )
  4370.             {
  4371.                 /* Buffer future message */
  4372.                 ret = ssl_buffer_message( ssl );
  4373.                 if( ret != 0 )
  4374.                     return( ret );
  4375.  
  4376.                 ret = MBEDTLS_ERR_SSL_CONTINUE_PROCESSING;
  4377.             }
  4378. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  4379.  
  4380.         } while( MBEDTLS_ERR_SSL_NON_FATAL           == ret  ||
  4381.                  MBEDTLS_ERR_SSL_CONTINUE_PROCESSING == ret );
  4382.  
  4383.         if( 0 != ret )
  4384.         {
  4385.             MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ssl_handle_message_type" ), ret );
  4386.             return( ret );
  4387.         }
  4388.  
  4389.         if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
  4390.             update_hs_digest == 1 )
  4391.         {
  4392.             mbedtls_ssl_update_handshake_status( ssl );
  4393.         }
  4394.     }
  4395.     else
  4396.     {
  4397.         MBEDTLS_SSL_DEBUG_MSG( 2, ( "reuse previously read message" ) );
  4398.         ssl->keep_current_message = 0;
  4399.     }
  4400.  
  4401.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= read record" ) );
  4402.  
  4403.     return( 0 );
  4404. }
  4405.  
  4406. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4407. static int ssl_next_record_is_in_datagram( mbedtls_ssl_context *ssl )
  4408. {
  4409.     if( ssl->in_left > ssl->next_record_offset )
  4410.         return( 1 );
  4411.  
  4412.     return( 0 );
  4413. }
  4414.  
  4415. static int ssl_load_buffered_message( mbedtls_ssl_context *ssl )
  4416. {
  4417.     mbedtls_ssl_handshake_params * const hs = ssl->handshake;
  4418.     mbedtls_ssl_hs_buffer * hs_buf;
  4419.     int ret = 0;
  4420.  
  4421.     if( hs == NULL )
  4422.         return( -1 );
  4423.  
  4424.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> ssl_load_buffered_messsage" ) );
  4425.  
  4426.     if( ssl->state == MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC ||
  4427.         ssl->state == MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC )
  4428.     {
  4429.         /* Check if we have seen a ChangeCipherSpec before.
  4430.          * If yes, synthesize a CCS record. */
  4431.         if( !hs->buffering.seen_ccs )
  4432.         {
  4433.             MBEDTLS_SSL_DEBUG_MSG( 2, ( "CCS not seen in the current flight" ) );
  4434.             ret = -1;
  4435.             goto exit;
  4436.         }
  4437.  
  4438.         MBEDTLS_SSL_DEBUG_MSG( 2, ( "Injecting buffered CCS message" ) );
  4439.         ssl->in_msgtype = MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC;
  4440.         ssl->in_msglen = 1;
  4441.         ssl->in_msg[0] = 1;
  4442.  
  4443.         /* As long as they are equal, the exact value doesn't matter. */
  4444.         ssl->in_left            = 0;
  4445.         ssl->next_record_offset = 0;
  4446.  
  4447.         hs->buffering.seen_ccs = 0;
  4448.         goto exit;
  4449.     }
  4450.  
  4451. #if defined(MBEDTLS_DEBUG_C)
  4452.     /* Debug only */
  4453.     {
  4454.         unsigned offset;
  4455.         for( offset = 1; offset < MBEDTLS_SSL_MAX_BUFFERED_HS; offset++ )
  4456.         {
  4457.             hs_buf = &hs->buffering.hs[offset];
  4458.             if( hs_buf->is_valid == 1 )
  4459.             {
  4460.                 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Future message with sequence number %u %s buffered.",
  4461.                             hs->in_msg_seq + offset,
  4462.                             hs_buf->is_complete ? "fully" : "partially" ) );
  4463.             }
  4464.         }
  4465.     }
  4466. #endif /* MBEDTLS_DEBUG_C */
  4467.  
  4468.     /* Check if we have buffered and/or fully reassembled the
  4469.      * next handshake message. */
  4470.     hs_buf = &hs->buffering.hs[0];
  4471.     if( ( hs_buf->is_valid == 1 ) && ( hs_buf->is_complete == 1 ) )
  4472.     {
  4473.         /* Synthesize a record containing the buffered HS message. */
  4474.         size_t msg_len = ( hs_buf->data[1] << 16 ) |
  4475.                          ( hs_buf->data[2] << 8  ) |
  4476.                            hs_buf->data[3];
  4477.  
  4478.         /* Double-check that we haven't accidentally buffered
  4479.          * a message that doesn't fit into the input buffer. */
  4480.         if( msg_len + 12 > MBEDTLS_SSL_IN_CONTENT_LEN )
  4481.         {
  4482.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  4483.             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  4484.         }
  4485.  
  4486.         MBEDTLS_SSL_DEBUG_MSG( 2, ( "Next handshake message has been buffered - load" ) );
  4487.         MBEDTLS_SSL_DEBUG_BUF( 3, "Buffered handshake message (incl. header)",
  4488.                                hs_buf->data, msg_len + 12 );
  4489.  
  4490.         ssl->in_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
  4491.         ssl->in_hslen   = msg_len + 12;
  4492.         ssl->in_msglen  = msg_len + 12;
  4493.         memcpy( ssl->in_msg, hs_buf->data, ssl->in_hslen );
  4494.  
  4495.         ret = 0;
  4496.         goto exit;
  4497.     }
  4498.     else
  4499.     {
  4500.         MBEDTLS_SSL_DEBUG_MSG( 2, ( "Next handshake message %u not or only partially bufffered",
  4501.                                     hs->in_msg_seq ) );
  4502.     }
  4503.  
  4504.     ret = -1;
  4505.  
  4506. exit:
  4507.  
  4508.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= ssl_load_buffered_message" ) );
  4509.     return( ret );
  4510. }
  4511.  
  4512. static int ssl_buffer_make_space( mbedtls_ssl_context *ssl,
  4513.                                   size_t desired )
  4514. {
  4515.     int offset;
  4516.     mbedtls_ssl_handshake_params * const hs = ssl->handshake;
  4517.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "Attempt to free buffered messages to have %u bytes available",
  4518.                                 (unsigned) desired ) );
  4519.  
  4520.     /* Get rid of future records epoch first, if such exist. */
  4521.     ssl_free_buffered_record( ssl );
  4522.  
  4523.     /* Check if we have enough space available now. */
  4524.     if( desired <= ( MBEDTLS_SSL_DTLS_MAX_BUFFERING -
  4525.                      hs->buffering.total_bytes_buffered ) )
  4526.     {
  4527.         MBEDTLS_SSL_DEBUG_MSG( 2, ( "Enough space available after freeing future epoch record" ) );
  4528.         return( 0 );
  4529.     }
  4530.  
  4531.     /* We don't have enough space to buffer the next expected handshake
  4532.      * message. Remove buffers used for future messages to gain space,
  4533.      * starting with the most distant one. */
  4534.     for( offset = MBEDTLS_SSL_MAX_BUFFERED_HS - 1;
  4535.          offset >= 0; offset-- )
  4536.     {
  4537.         MBEDTLS_SSL_DEBUG_MSG( 2, ( "Free buffering slot %d to make space for reassembly of next handshake message",
  4538.                                     offset ) );
  4539.  
  4540.         ssl_buffering_free_slot( ssl, (uint8_t) offset );
  4541.  
  4542.         /* Check if we have enough space available now. */
  4543.         if( desired <= ( MBEDTLS_SSL_DTLS_MAX_BUFFERING -
  4544.                          hs->buffering.total_bytes_buffered ) )
  4545.         {
  4546.             MBEDTLS_SSL_DEBUG_MSG( 2, ( "Enough space available after freeing buffered HS messages" ) );
  4547.             return( 0 );
  4548.         }
  4549.     }
  4550.  
  4551.     return( -1 );
  4552. }
  4553.  
  4554. static int ssl_buffer_message( mbedtls_ssl_context *ssl )
  4555. {
  4556.     int ret = 0;
  4557.     mbedtls_ssl_handshake_params * const hs = ssl->handshake;
  4558.  
  4559.     if( hs == NULL )
  4560.         return( 0 );
  4561.  
  4562.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> ssl_buffer_message" ) );
  4563.  
  4564.     switch( ssl->in_msgtype )
  4565.     {
  4566.         case MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC:
  4567.             MBEDTLS_SSL_DEBUG_MSG( 2, ( "Remember CCS message" ) );
  4568.  
  4569.             hs->buffering.seen_ccs = 1;
  4570.             break;
  4571.  
  4572.         case MBEDTLS_SSL_MSG_HANDSHAKE:
  4573.         {
  4574.             unsigned recv_msg_seq_offset;
  4575.             unsigned recv_msg_seq = ( ssl->in_msg[4] << 8 ) | ssl->in_msg[5];
  4576.             mbedtls_ssl_hs_buffer *hs_buf;
  4577.             size_t msg_len = ssl->in_hslen - 12;
  4578.  
  4579.             /* We should never receive an old handshake
  4580.              * message - double-check nonetheless. */
  4581.             if( recv_msg_seq < ssl->handshake->in_msg_seq )
  4582.             {
  4583.                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  4584.                 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  4585.             }
  4586.  
  4587.             recv_msg_seq_offset = recv_msg_seq - ssl->handshake->in_msg_seq;
  4588.             if( recv_msg_seq_offset >= MBEDTLS_SSL_MAX_BUFFERED_HS )
  4589.             {
  4590.                 /* Silently ignore -- message too far in the future */
  4591.                 MBEDTLS_SSL_DEBUG_MSG( 2,
  4592.                  ( "Ignore future HS message with sequence number %u, "
  4593.                    "buffering window %u - %u",
  4594.                    recv_msg_seq, ssl->handshake->in_msg_seq,
  4595.                    ssl->handshake->in_msg_seq + MBEDTLS_SSL_MAX_BUFFERED_HS - 1 ) );
  4596.  
  4597.                 goto exit;
  4598.             }
  4599.  
  4600.             MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffering HS message with sequence number %u, offset %u ",
  4601.                                         recv_msg_seq, recv_msg_seq_offset ) );
  4602.  
  4603.             hs_buf = &hs->buffering.hs[ recv_msg_seq_offset ];
  4604.  
  4605.             /* Check if the buffering for this seq nr has already commenced. */
  4606.             if( !hs_buf->is_valid )
  4607.             {
  4608.                 size_t reassembly_buf_sz;
  4609.  
  4610.                 hs_buf->is_fragmented =
  4611.                     ( ssl_hs_is_proper_fragment( ssl ) == 1 );
  4612.  
  4613.                 /* We copy the message back into the input buffer
  4614.                  * after reassembly, so check that it's not too large.
  4615.                  * This is an implementation-specific limitation
  4616.                  * and not one from the standard, hence it is not
  4617.                  * checked in ssl_check_hs_header(). */
  4618.                 if( msg_len + 12 > MBEDTLS_SSL_IN_CONTENT_LEN )
  4619.                 {
  4620.                     /* Ignore message */
  4621.                     goto exit;
  4622.                 }
  4623.  
  4624.                 /* Check if we have enough space to buffer the message. */
  4625.                 if( hs->buffering.total_bytes_buffered >
  4626.                     MBEDTLS_SSL_DTLS_MAX_BUFFERING )
  4627.                 {
  4628.                     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  4629.                     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  4630.                 }
  4631.  
  4632.                 reassembly_buf_sz = ssl_get_reassembly_buffer_size( msg_len,
  4633.                                                        hs_buf->is_fragmented );
  4634.  
  4635.                 if( reassembly_buf_sz > ( MBEDTLS_SSL_DTLS_MAX_BUFFERING -
  4636.                                           hs->buffering.total_bytes_buffered ) )
  4637.                 {
  4638.                     if( recv_msg_seq_offset > 0 )
  4639.                     {
  4640.                         /* If we can't buffer a future message because
  4641.                          * of space limitations -- ignore. */
  4642.                         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",
  4643.                              (unsigned) msg_len, MBEDTLS_SSL_DTLS_MAX_BUFFERING,
  4644.                              (unsigned) hs->buffering.total_bytes_buffered ) );
  4645.                         goto exit;
  4646.                     }
  4647.                     else
  4648.                     {
  4649.                         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",
  4650.                              (unsigned) msg_len, MBEDTLS_SSL_DTLS_MAX_BUFFERING,
  4651.                              (unsigned) hs->buffering.total_bytes_buffered ) );
  4652.                     }
  4653.  
  4654.                     if( ssl_buffer_make_space( ssl, reassembly_buf_sz ) != 0 )
  4655.                     {
  4656.                         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",
  4657.                              (unsigned) msg_len,
  4658.                              (unsigned) reassembly_buf_sz,
  4659.                              MBEDTLS_SSL_DTLS_MAX_BUFFERING,
  4660.                              (unsigned) hs->buffering.total_bytes_buffered ) );
  4661.                         ret = MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
  4662.                         goto exit;
  4663.                     }
  4664.                 }
  4665.  
  4666.                 MBEDTLS_SSL_DEBUG_MSG( 2, ( "initialize reassembly, total length = %d",
  4667.                                             msg_len ) );
  4668.  
  4669.                 hs_buf->data = mbedtls_calloc( 1, reassembly_buf_sz );
  4670.                 if( hs_buf->data == NULL )
  4671.                 {
  4672.                     ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
  4673.                     goto exit;
  4674.                 }
  4675.                 hs_buf->data_len = reassembly_buf_sz;
  4676.  
  4677.                 /* Prepare final header: copy msg_type, length and message_seq,
  4678.                  * then add standardised fragment_offset and fragment_length */
  4679.                 memcpy( hs_buf->data, ssl->in_msg, 6 );
  4680.                 memset( hs_buf->data + 6, 0, 3 );
  4681.                 memcpy( hs_buf->data + 9, hs_buf->data + 1, 3 );
  4682.  
  4683.                 hs_buf->is_valid = 1;
  4684.  
  4685.                 hs->buffering.total_bytes_buffered += reassembly_buf_sz;
  4686.             }
  4687.             else
  4688.             {
  4689.                 /* Make sure msg_type and length are consistent */
  4690.                 if( memcmp( hs_buf->data, ssl->in_msg, 4 ) != 0 )
  4691.                 {
  4692.                     MBEDTLS_SSL_DEBUG_MSG( 1, ( "Fragment header mismatch - ignore" ) );
  4693.                     /* Ignore */
  4694.                     goto exit;
  4695.                 }
  4696.             }
  4697.  
  4698.             if( !hs_buf->is_complete )
  4699.             {
  4700.                 size_t frag_len, frag_off;
  4701.                 unsigned char * const msg = hs_buf->data + 12;
  4702.  
  4703.                 /*
  4704.                  * Check and copy current fragment
  4705.                  */
  4706.  
  4707.                 /* Validation of header fields already done in
  4708.                  * mbedtls_ssl_prepare_handshake_record(). */
  4709.                 frag_off = ssl_get_hs_frag_off( ssl );
  4710.                 frag_len = ssl_get_hs_frag_len( ssl );
  4711.  
  4712.                 MBEDTLS_SSL_DEBUG_MSG( 2, ( "adding fragment, offset = %d, length = %d",
  4713.                                             frag_off, frag_len ) );
  4714.                 memcpy( msg + frag_off, ssl->in_msg + 12, frag_len );
  4715.  
  4716.                 if( hs_buf->is_fragmented )
  4717.                 {
  4718.                     unsigned char * const bitmask = msg + msg_len;
  4719.                     ssl_bitmask_set( bitmask, frag_off, frag_len );
  4720.                     hs_buf->is_complete = ( ssl_bitmask_check( bitmask,
  4721.                                                                msg_len ) == 0 );
  4722.                 }
  4723.                 else
  4724.                 {
  4725.                     hs_buf->is_complete = 1;
  4726.                 }
  4727.  
  4728.                 MBEDTLS_SSL_DEBUG_MSG( 2, ( "message %scomplete",
  4729.                                    hs_buf->is_complete ? "" : "not yet " ) );
  4730.             }
  4731.  
  4732.             break;
  4733.         }
  4734.  
  4735.         default:
  4736.             /* We don't buffer other types of messages. */
  4737.             break;
  4738.     }
  4739.  
  4740. exit:
  4741.  
  4742.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= ssl_buffer_message" ) );
  4743.     return( ret );
  4744. }
  4745. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  4746.  
  4747. static int ssl_consume_current_message( mbedtls_ssl_context *ssl )
  4748. {
  4749.     /*
  4750.      * Consume last content-layer message and potentially
  4751.      * update in_msglen which keeps track of the contents'
  4752.      * consumption state.
  4753.      *
  4754.      * (1) Handshake messages:
  4755.      *     Remove last handshake message, move content
  4756.      *     and adapt in_msglen.
  4757.      *
  4758.      * (2) Alert messages:
  4759.      *     Consume whole record content, in_msglen = 0.
  4760.      *
  4761.      * (3) Change cipher spec:
  4762.      *     Consume whole record content, in_msglen = 0.
  4763.      *
  4764.      * (4) Application data:
  4765.      *     Don't do anything - the record layer provides
  4766.      *     the application data as a stream transport
  4767.      *     and consumes through mbedtls_ssl_read only.
  4768.      *
  4769.      */
  4770.  
  4771.     /* Case (1): Handshake messages */
  4772.     if( ssl->in_hslen != 0 )
  4773.     {
  4774.         /* Hard assertion to be sure that no application data
  4775.          * is in flight, as corrupting ssl->in_msglen during
  4776.          * ssl->in_offt != NULL is fatal. */
  4777.         if( ssl->in_offt != NULL )
  4778.         {
  4779.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  4780.             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  4781.         }
  4782.  
  4783.         /*
  4784.          * Get next Handshake message in the current record
  4785.          */
  4786.  
  4787.         /* Notes:
  4788.          * (1) in_hslen is not necessarily the size of the
  4789.          *     current handshake content: If DTLS handshake
  4790.          *     fragmentation is used, that's the fragment
  4791.          *     size instead. Using the total handshake message
  4792.          *     size here is faulty and should be changed at
  4793.          *     some point.
  4794.          * (2) While it doesn't seem to cause problems, one
  4795.          *     has to be very careful not to assume that in_hslen
  4796.          *     is always <= in_msglen in a sensible communication.
  4797.          *     Again, it's wrong for DTLS handshake fragmentation.
  4798.          *     The following check is therefore mandatory, and
  4799.          *     should not be treated as a silently corrected assertion.
  4800.          *     Additionally, ssl->in_hslen might be arbitrarily out of
  4801.          *     bounds after handling a DTLS message with an unexpected
  4802.          *     sequence number, see mbedtls_ssl_prepare_handshake_record.
  4803.          */
  4804.         if( ssl->in_hslen < ssl->in_msglen )
  4805.         {
  4806.             ssl->in_msglen -= ssl->in_hslen;
  4807.             memmove( ssl->in_msg, ssl->in_msg + ssl->in_hslen,
  4808.                      ssl->in_msglen );
  4809.  
  4810.             MBEDTLS_SSL_DEBUG_BUF( 4, "remaining content in record",
  4811.                                    ssl->in_msg, ssl->in_msglen );
  4812.         }
  4813.         else
  4814.         {
  4815.             ssl->in_msglen = 0;
  4816.         }
  4817.  
  4818.         ssl->in_hslen   = 0;
  4819.     }
  4820.     /* Case (4): Application data */
  4821.     else if( ssl->in_offt != NULL )
  4822.     {
  4823.         return( 0 );
  4824.     }
  4825.     /* Everything else (CCS & Alerts) */
  4826.     else
  4827.     {
  4828.         ssl->in_msglen = 0;
  4829.     }
  4830.  
  4831.     return( 0 );
  4832. }
  4833.  
  4834. static int ssl_record_is_in_progress( mbedtls_ssl_context *ssl )
  4835. {
  4836.     if( ssl->in_msglen > 0 )
  4837.         return( 1 );
  4838.  
  4839.     return( 0 );
  4840. }
  4841.  
  4842. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4843.  
  4844. static void ssl_free_buffered_record( mbedtls_ssl_context *ssl )
  4845. {
  4846.     mbedtls_ssl_handshake_params * const hs = ssl->handshake;
  4847.     if( hs == NULL )
  4848.         return;
  4849.  
  4850.     if( hs->buffering.future_record.data != NULL )
  4851.     {
  4852.         hs->buffering.total_bytes_buffered -=
  4853.             hs->buffering.future_record.len;
  4854.  
  4855.         mbedtls_free( hs->buffering.future_record.data );
  4856.         hs->buffering.future_record.data = NULL;
  4857.     }
  4858. }
  4859.  
  4860. static int ssl_load_buffered_record( mbedtls_ssl_context *ssl )
  4861. {
  4862.     mbedtls_ssl_handshake_params * const hs = ssl->handshake;
  4863.     unsigned char * rec;
  4864.     size_t rec_len;
  4865.     unsigned rec_epoch;
  4866.  
  4867.     if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  4868.         return( 0 );
  4869.  
  4870.     if( hs == NULL )
  4871.         return( 0 );
  4872.  
  4873.     rec       = hs->buffering.future_record.data;
  4874.     rec_len   = hs->buffering.future_record.len;
  4875.     rec_epoch = hs->buffering.future_record.epoch;
  4876.  
  4877.     if( rec == NULL )
  4878.         return( 0 );
  4879.  
  4880.     /* Only consider loading future records if the
  4881.      * input buffer is empty. */
  4882.     if( ssl_next_record_is_in_datagram( ssl ) == 1 )
  4883.         return( 0 );
  4884.  
  4885.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> ssl_load_buffered_record" ) );
  4886.  
  4887.     if( rec_epoch != ssl->in_epoch )
  4888.     {
  4889.         MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffered record not from current epoch." ) );
  4890.         goto exit;
  4891.     }
  4892.  
  4893.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "Found buffered record from current epoch - load" ) );
  4894.  
  4895.     /* Double-check that the record is not too large */
  4896.     if( rec_len > MBEDTLS_SSL_IN_BUFFER_LEN -
  4897.         (size_t)( ssl->in_hdr - ssl->in_buf ) )
  4898.     {
  4899.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  4900.         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  4901.     }
  4902.  
  4903.     memcpy( ssl->in_hdr, rec, rec_len );
  4904.     ssl->in_left = rec_len;
  4905.     ssl->next_record_offset = 0;
  4906.  
  4907.     ssl_free_buffered_record( ssl );
  4908.  
  4909. exit:
  4910.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= ssl_load_buffered_record" ) );
  4911.     return( 0 );
  4912. }
  4913.  
  4914. static int ssl_buffer_future_record( mbedtls_ssl_context *ssl )
  4915. {
  4916.     mbedtls_ssl_handshake_params * const hs = ssl->handshake;
  4917.     size_t const rec_hdr_len = 13;
  4918.     size_t const total_buf_sz = rec_hdr_len + ssl->in_msglen;
  4919.  
  4920.     /* Don't buffer future records outside handshakes. */
  4921.     if( hs == NULL )
  4922.         return( 0 );
  4923.  
  4924.     /* Only buffer handshake records (we are only interested
  4925.      * in Finished messages). */
  4926.     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
  4927.         return( 0 );
  4928.  
  4929.     /* Don't buffer more than one future epoch record. */
  4930.     if( hs->buffering.future_record.data != NULL )
  4931.         return( 0 );
  4932.  
  4933.     /* Don't buffer record if there's not enough buffering space remaining. */
  4934.     if( total_buf_sz > ( MBEDTLS_SSL_DTLS_MAX_BUFFERING -
  4935.                          hs->buffering.total_bytes_buffered ) )
  4936.     {
  4937.         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",
  4938.                         (unsigned) total_buf_sz, MBEDTLS_SSL_DTLS_MAX_BUFFERING,
  4939.                         (unsigned) hs->buffering.total_bytes_buffered ) );
  4940.         return( 0 );
  4941.     }
  4942.  
  4943.     /* Buffer record */
  4944.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffer record from epoch %u",
  4945.                                 ssl->in_epoch + 1 ) );
  4946.     MBEDTLS_SSL_DEBUG_BUF( 3, "Buffered record", ssl->in_hdr,
  4947.                            rec_hdr_len + ssl->in_msglen );
  4948.  
  4949.     /* ssl_parse_record_header() only considers records
  4950.      * of the next epoch as candidates for buffering. */
  4951.     hs->buffering.future_record.epoch = ssl->in_epoch + 1;
  4952.     hs->buffering.future_record.len   = total_buf_sz;
  4953.  
  4954.     hs->buffering.future_record.data =
  4955.         mbedtls_calloc( 1, hs->buffering.future_record.len );
  4956.     if( hs->buffering.future_record.data == NULL )
  4957.     {
  4958.         /* If we run out of RAM trying to buffer a
  4959.          * record from the next epoch, just ignore. */
  4960.         return( 0 );
  4961.     }
  4962.  
  4963.     memcpy( hs->buffering.future_record.data, ssl->in_hdr, total_buf_sz );
  4964.  
  4965.     hs->buffering.total_bytes_buffered += total_buf_sz;
  4966.     return( 0 );
  4967. }
  4968.  
  4969. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  4970.  
  4971. static int ssl_get_next_record( mbedtls_ssl_context *ssl )
  4972. {
  4973.     int ret;
  4974.  
  4975. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4976.     /* We might have buffered a future record; if so,
  4977.      * and if the epoch matches now, load it.
  4978.      * On success, this call will set ssl->in_left to
  4979.      * the length of the buffered record, so that
  4980.      * the calls to ssl_fetch_input() below will
  4981.      * essentially be no-ops. */
  4982.     ret = ssl_load_buffered_record( ssl );
  4983.     if( ret != 0 )
  4984.         return( ret );
  4985. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  4986.  
  4987.     if( ( ret = mbedtls_ssl_fetch_input( ssl, mbedtls_ssl_hdr_len( ssl ) ) ) != 0 )
  4988.     {
  4989.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret );
  4990.         return( ret );
  4991.     }
  4992.  
  4993.     if( ( ret = ssl_parse_record_header( ssl ) ) != 0 )
  4994.     {
  4995. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  4996.         if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  4997.             ret != MBEDTLS_ERR_SSL_CLIENT_RECONNECT )
  4998.         {
  4999.             if( ret == MBEDTLS_ERR_SSL_EARLY_MESSAGE )
  5000.             {
  5001.                 ret = ssl_buffer_future_record( ssl );
  5002.                 if( ret != 0 )
  5003.                     return( ret );
  5004.  
  5005.                 /* Fall through to handling of unexpected records */
  5006.                 ret = MBEDTLS_ERR_SSL_UNEXPECTED_RECORD;
  5007.             }
  5008.  
  5009.             if( ret == MBEDTLS_ERR_SSL_UNEXPECTED_RECORD )
  5010.             {
  5011.                 /* Skip unexpected record (but not whole datagram) */
  5012.                 ssl->next_record_offset = ssl->in_msglen
  5013.                                         + mbedtls_ssl_hdr_len( ssl );
  5014.  
  5015.                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding unexpected record "
  5016.                                             "(header)" ) );
  5017.             }
  5018.             else
  5019.             {
  5020.                 /* Skip invalid record and the rest of the datagram */
  5021.                 ssl->next_record_offset = 0;
  5022.                 ssl->in_left = 0;
  5023.  
  5024.                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding invalid record "
  5025.                                             "(header)" ) );
  5026.             }
  5027.  
  5028.             /* Get next record */
  5029.             return( MBEDTLS_ERR_SSL_CONTINUE_PROCESSING );
  5030.         }
  5031. #endif
  5032.         return( ret );
  5033.     }
  5034.  
  5035.     /*
  5036.      * Read and optionally decrypt the message contents
  5037.      */
  5038.     if( ( ret = mbedtls_ssl_fetch_input( ssl,
  5039.                                  mbedtls_ssl_hdr_len( ssl ) + ssl->in_msglen ) ) != 0 )
  5040.     {
  5041.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret );
  5042.         return( ret );
  5043.     }
  5044.  
  5045.     /* Done reading this record, get ready for the next one */
  5046. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  5047.     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  5048.     {
  5049.         ssl->next_record_offset = ssl->in_msglen + mbedtls_ssl_hdr_len( ssl );
  5050.         if( ssl->next_record_offset < ssl->in_left )
  5051.         {
  5052.             MBEDTLS_SSL_DEBUG_MSG( 3, ( "more than one record within datagram" ) );
  5053.         }
  5054.     }
  5055.     else
  5056. #endif
  5057.         ssl->in_left = 0;
  5058.  
  5059.     if( ( ret = ssl_prepare_record_content( ssl ) ) != 0 )
  5060.     {
  5061. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  5062.         if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  5063.         {
  5064.             /* Silently discard invalid records */
  5065.             if( ret == MBEDTLS_ERR_SSL_INVALID_RECORD ||
  5066.                 ret == MBEDTLS_ERR_SSL_INVALID_MAC )
  5067.             {
  5068.                 /* Except when waiting for Finished as a bad mac here
  5069.                  * probably means something went wrong in the handshake
  5070.                  * (eg wrong psk used, mitm downgrade attempt, etc.) */
  5071.                 if( ssl->state == MBEDTLS_SSL_CLIENT_FINISHED ||
  5072.                     ssl->state == MBEDTLS_SSL_SERVER_FINISHED )
  5073.                 {
  5074. #if defined(MBEDTLS_SSL_ALL_ALERT_MESSAGES)
  5075.                     if( ret == MBEDTLS_ERR_SSL_INVALID_MAC )
  5076.                     {
  5077.                         mbedtls_ssl_send_alert_message( ssl,
  5078.                                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  5079.                                 MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC );
  5080.                     }
  5081. #endif
  5082.                     return( ret );
  5083.                 }
  5084.  
  5085. #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT)
  5086.                 if( ssl->conf->badmac_limit != 0 &&
  5087.                     ++ssl->badmac_seen >= ssl->conf->badmac_limit )
  5088.                 {
  5089.                     MBEDTLS_SSL_DEBUG_MSG( 1, ( "too many records with bad MAC" ) );
  5090.                     return( MBEDTLS_ERR_SSL_INVALID_MAC );
  5091.                 }
  5092. #endif
  5093.  
  5094.                 /* As above, invalid records cause
  5095.                  * dismissal of the whole datagram. */
  5096.  
  5097.                 ssl->next_record_offset = 0;
  5098.                 ssl->in_left = 0;
  5099.  
  5100.                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding invalid record (mac)" ) );
  5101.                 return( MBEDTLS_ERR_SSL_CONTINUE_PROCESSING );
  5102.             }
  5103.  
  5104.             return( ret );
  5105.         }
  5106.         else
  5107. #endif
  5108.         {
  5109.             /* Error out (and send alert) on invalid records */
  5110. #if defined(MBEDTLS_SSL_ALL_ALERT_MESSAGES)
  5111.             if( ret == MBEDTLS_ERR_SSL_INVALID_MAC )
  5112.             {
  5113.                 mbedtls_ssl_send_alert_message( ssl,
  5114.                         MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  5115.                         MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC );
  5116.             }
  5117. #endif
  5118.             return( ret );
  5119.         }
  5120.     }
  5121.  
  5122.     return( 0 );
  5123. }
  5124.  
  5125. int mbedtls_ssl_handle_message_type( mbedtls_ssl_context *ssl )
  5126. {
  5127.     int ret;
  5128.  
  5129.     /*
  5130.      * Handle particular types of records
  5131.      */
  5132.     if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE )
  5133.     {
  5134.         if( ( ret = mbedtls_ssl_prepare_handshake_record( ssl ) ) != 0 )
  5135.         {
  5136.             return( ret );
  5137.         }
  5138.     }
  5139.  
  5140.     if( ssl->in_msgtype == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC )
  5141.     {
  5142.         if( ssl->in_msglen != 1 )
  5143.         {
  5144.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid CCS message, len: %d",
  5145.                            ssl->in_msglen ) );
  5146.             return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  5147.         }
  5148.  
  5149.         if( ssl->in_msg[0] != 1 )
  5150.         {
  5151.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid CCS message, content: %02x",
  5152.                                         ssl->in_msg[0] ) );
  5153.             return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  5154.         }
  5155.  
  5156. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  5157.         if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  5158.             ssl->state != MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC    &&
  5159.             ssl->state != MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC )
  5160.         {
  5161.             if( ssl->handshake == NULL )
  5162.             {
  5163.                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "dropping ChangeCipherSpec outside handshake" ) );
  5164.                 return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD );
  5165.             }
  5166.  
  5167.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "received out-of-order ChangeCipherSpec - remember" ) );
  5168.             return( MBEDTLS_ERR_SSL_EARLY_MESSAGE );
  5169.         }
  5170. #endif
  5171.     }
  5172.  
  5173.     if( ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT )
  5174.     {
  5175.         if( ssl->in_msglen != 2 )
  5176.         {
  5177.             /* Note: Standard allows for more than one 2 byte alert
  5178.                to be packed in a single message, but Mbed TLS doesn't
  5179.                currently support this. */
  5180.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid alert message, len: %d",
  5181.                            ssl->in_msglen ) );
  5182.             return( MBEDTLS_ERR_SSL_INVALID_RECORD );
  5183.         }
  5184.  
  5185.         MBEDTLS_SSL_DEBUG_MSG( 2, ( "got an alert message, type: [%d:%d]",
  5186.                        ssl->in_msg[0], ssl->in_msg[1] ) );
  5187.  
  5188.         /*
  5189.          * Ignore non-fatal alerts, except close_notify and no_renegotiation
  5190.          */
  5191.         if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_FATAL )
  5192.         {
  5193.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "is a fatal alert message (msg %d)",
  5194.                            ssl->in_msg[1] ) );
  5195.             return( MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE );
  5196.         }
  5197.  
  5198.         if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&
  5199.             ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY )
  5200.         {
  5201.             MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a close notify message" ) );
  5202.             return( MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY );
  5203.         }
  5204.  
  5205. #if defined(MBEDTLS_SSL_RENEGOTIATION_ENABLED)
  5206.         if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&
  5207.             ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION )
  5208.         {
  5209.             MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a SSLv3 no renegotiation alert" ) );
  5210.             /* Will be handled when trying to parse ServerHello */
  5211.             return( 0 );
  5212.         }
  5213. #endif
  5214.  
  5215. #if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_SRV_C)
  5216.         if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 &&
  5217.             ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
  5218.             ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&
  5219.             ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_CERT )
  5220.         {
  5221.             MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a SSLv3 no_cert" ) );
  5222.             /* Will be handled in mbedtls_ssl_parse_certificate() */
  5223.             return( 0 );
  5224.         }
  5225. #endif /* MBEDTLS_SSL_PROTO_SSL3 && MBEDTLS_SSL_SRV_C */
  5226.  
  5227.         /* Silently ignore: fetch new message */
  5228.         return MBEDTLS_ERR_SSL_NON_FATAL;
  5229.     }
  5230.  
  5231. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  5232.     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  5233.         ssl->handshake != NULL &&
  5234.         ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER  )
  5235.     {
  5236.         ssl_handshake_wrapup_free_hs_transform( ssl );
  5237.     }
  5238. #endif
  5239.  
  5240.     return( 0 );
  5241. }
  5242.  
  5243. int mbedtls_ssl_send_fatal_handshake_failure( mbedtls_ssl_context *ssl )
  5244. {
  5245.     int ret;
  5246.  
  5247.     if( ( ret = mbedtls_ssl_send_alert_message( ssl,
  5248.                     MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  5249.                     MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ) ) != 0 )
  5250.     {
  5251.         return( ret );
  5252.     }
  5253.  
  5254.     return( 0 );
  5255. }
  5256.  
  5257. int mbedtls_ssl_send_alert_message( mbedtls_ssl_context *ssl,
  5258.                             unsigned char level,
  5259.                             unsigned char message )
  5260. {
  5261.     int ret;
  5262.  
  5263.     if( ssl == NULL || ssl->conf == NULL )
  5264.         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  5265.  
  5266.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> send alert message" ) );
  5267.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "send alert level=%u message=%u", level, message ));
  5268.  
  5269.     ssl->out_msgtype = MBEDTLS_SSL_MSG_ALERT;
  5270.     ssl->out_msglen = 2;
  5271.     ssl->out_msg[0] = level;
  5272.     ssl->out_msg[1] = message;
  5273.  
  5274.     if( ( ret = mbedtls_ssl_write_record( ssl, SSL_FORCE_FLUSH ) ) != 0 )
  5275.     {
  5276.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
  5277.         return( ret );
  5278.     }
  5279.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= send alert message" ) );
  5280.  
  5281.     return( 0 );
  5282. }
  5283.  
  5284. /*
  5285.  * Handshake functions
  5286.  */
  5287. #if !defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)         && \
  5288.     !defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)     && \
  5289.     !defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)     && \
  5290.     !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED)   && \
  5291.     !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) && \
  5292.     !defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED)    && \
  5293.     !defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
  5294. /* No certificate support -> dummy functions */
  5295. int mbedtls_ssl_write_certificate( mbedtls_ssl_context *ssl )
  5296. {
  5297.     const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
  5298.  
  5299.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate" ) );
  5300.  
  5301.     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
  5302.         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
  5303.         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
  5304.         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
  5305.     {
  5306.         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) );
  5307.         ssl->state++;
  5308.         return( 0 );
  5309.     }
  5310.  
  5311.     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  5312.     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  5313. }
  5314.  
  5315. int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl )
  5316. {
  5317.     const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
  5318.  
  5319.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) );
  5320.  
  5321.     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
  5322.         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
  5323.         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
  5324.         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
  5325.     {
  5326.         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
  5327.         ssl->state++;
  5328.         return( 0 );
  5329.     }
  5330.  
  5331.     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  5332.     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  5333. }
  5334.  
  5335. #else
  5336. /* Some certificate support -> implement write and parse */
  5337.  
  5338. int mbedtls_ssl_write_certificate( mbedtls_ssl_context *ssl )
  5339. {
  5340.     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
  5341.     size_t i, n;
  5342.     const mbedtls_x509_crt *crt;
  5343.     const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
  5344.  
  5345.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate" ) );
  5346.  
  5347.     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
  5348.         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
  5349.         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
  5350.         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
  5351.     {
  5352.         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) );
  5353.         ssl->state++;
  5354.         return( 0 );
  5355.     }
  5356.  
  5357. #if defined(MBEDTLS_SSL_CLI_C)
  5358.     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
  5359.     {
  5360.         if( ssl->client_auth == 0 )
  5361.         {
  5362.             MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) );
  5363.             ssl->state++;
  5364.             return( 0 );
  5365.         }
  5366.  
  5367. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  5368.         /*
  5369.          * If using SSLv3 and got no cert, send an Alert message
  5370.          * (otherwise an empty Certificate message will be sent).
  5371.          */
  5372.         if( mbedtls_ssl_own_cert( ssl )  == NULL &&
  5373.             ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
  5374.         {
  5375.             ssl->out_msglen  = 2;
  5376.             ssl->out_msgtype = MBEDTLS_SSL_MSG_ALERT;
  5377.             ssl->out_msg[0]  = MBEDTLS_SSL_ALERT_LEVEL_WARNING;
  5378.             ssl->out_msg[1]  = MBEDTLS_SSL_ALERT_MSG_NO_CERT;
  5379.  
  5380.             MBEDTLS_SSL_DEBUG_MSG( 2, ( "got no certificate to send" ) );
  5381.             goto write_msg;
  5382.         }
  5383. #endif /* MBEDTLS_SSL_PROTO_SSL3 */
  5384.     }
  5385. #endif /* MBEDTLS_SSL_CLI_C */
  5386. #if defined(MBEDTLS_SSL_SRV_C)
  5387.     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
  5388.     {
  5389.         if( mbedtls_ssl_own_cert( ssl ) == NULL )
  5390.         {
  5391.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no certificate to send" ) );
  5392.             return( MBEDTLS_ERR_SSL_CERTIFICATE_REQUIRED );
  5393.         }
  5394.     }
  5395. #endif
  5396.  
  5397.     MBEDTLS_SSL_DEBUG_CRT( 3, "own certificate", mbedtls_ssl_own_cert( ssl ) );
  5398.  
  5399.     /*
  5400.      *     0  .  0    handshake type
  5401.      *     1  .  3    handshake length
  5402.      *     4  .  6    length of all certs
  5403.      *     7  .  9    length of cert. 1
  5404.      *    10  . n-1   peer certificate
  5405.      *     n  . n+2   length of cert. 2
  5406.      *    n+3 . ...   upper level cert, etc.
  5407.      */
  5408.     i = 7;
  5409.     crt = mbedtls_ssl_own_cert( ssl );
  5410.  
  5411.     while( crt != NULL )
  5412.     {
  5413.         n = crt->raw.len;
  5414.         if( n > MBEDTLS_SSL_OUT_CONTENT_LEN - 3 - i )
  5415.         {
  5416.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "certificate too large, %d > %d",
  5417.                            i + 3 + n, MBEDTLS_SSL_OUT_CONTENT_LEN ) );
  5418.             return( MBEDTLS_ERR_SSL_CERTIFICATE_TOO_LARGE );
  5419.         }
  5420.  
  5421.         ssl->out_msg[i    ] = (unsigned char)( n >> 16 );
  5422.         ssl->out_msg[i + 1] = (unsigned char)( n >>  8 );
  5423.         ssl->out_msg[i + 2] = (unsigned char)( n       );
  5424.  
  5425.         i += 3; memcpy( ssl->out_msg + i, crt->raw.p, n );
  5426.         i += n; crt = crt->next;
  5427.     }
  5428.  
  5429.     ssl->out_msg[4]  = (unsigned char)( ( i - 7 ) >> 16 );
  5430.     ssl->out_msg[5]  = (unsigned char)( ( i - 7 ) >>  8 );
  5431.     ssl->out_msg[6]  = (unsigned char)( ( i - 7 )       );
  5432.  
  5433.     ssl->out_msglen  = i;
  5434.     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
  5435.     ssl->out_msg[0]  = MBEDTLS_SSL_HS_CERTIFICATE;
  5436.  
  5437. #if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_CLI_C)
  5438. write_msg:
  5439. #endif
  5440.  
  5441.     ssl->state++;
  5442.  
  5443.     if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
  5444.     {
  5445.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
  5446.         return( ret );
  5447.     }
  5448.  
  5449.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write certificate" ) );
  5450.  
  5451.     return( ret );
  5452. }
  5453.  
  5454. /*
  5455.  * Once the certificate message is read, parse it into a cert chain and
  5456.  * perform basic checks, but leave actual verification to the caller
  5457.  */
  5458. static int ssl_parse_certificate_chain( mbedtls_ssl_context *ssl )
  5459. {
  5460.     int ret;
  5461.     size_t i, n;
  5462.     uint8_t alert;
  5463.  
  5464. #if defined(MBEDTLS_SSL_SRV_C)
  5465. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  5466.     /*
  5467.      * Check if the client sent an empty certificate
  5468.      */
  5469.     if( ssl->conf->endpoint  == MBEDTLS_SSL_IS_SERVER &&
  5470.         ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
  5471.     {
  5472.         if( ssl->in_msglen  == 2                        &&
  5473.             ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT            &&
  5474.             ssl->in_msg[0]  == MBEDTLS_SSL_ALERT_LEVEL_WARNING  &&
  5475.             ssl->in_msg[1]  == MBEDTLS_SSL_ALERT_MSG_NO_CERT )
  5476.         {
  5477.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "SSLv3 client has no certificate" ) );
  5478.  
  5479.             /* The client was asked for a certificate but didn't send
  5480.                one. The client should know what's going on, so we
  5481.                don't send an alert. */
  5482.             ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_MISSING;
  5483.             return( MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE );
  5484.         }
  5485.     }
  5486. #endif /* MBEDTLS_SSL_PROTO_SSL3 */
  5487.  
  5488. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
  5489.     defined(MBEDTLS_SSL_PROTO_TLS1_2)
  5490.     if( ssl->conf->endpoint  == MBEDTLS_SSL_IS_SERVER &&
  5491.         ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_0 )
  5492.     {
  5493.         if( ssl->in_hslen   == 3 + mbedtls_ssl_hs_hdr_len( ssl ) &&
  5494.             ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE    &&
  5495.             ssl->in_msg[0]  == MBEDTLS_SSL_HS_CERTIFICATE   &&
  5496.             memcmp( ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ), "\0\0\0", 3 ) == 0 )
  5497.         {
  5498.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "TLSv1 client has no certificate" ) );
  5499.  
  5500.             /* The client was asked for a certificate but didn't send
  5501.                one. The client should know what's going on, so we
  5502.                don't send an alert. */
  5503.             ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_MISSING;
  5504.             return( MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE );
  5505.         }
  5506.     }
  5507. #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
  5508.           MBEDTLS_SSL_PROTO_TLS1_2 */
  5509. #endif /* MBEDTLS_SSL_SRV_C */
  5510.  
  5511.     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
  5512.     {
  5513.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
  5514.         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  5515.                                         MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
  5516.         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
  5517.     }
  5518.  
  5519.     if( ssl->in_msg[0] != MBEDTLS_SSL_HS_CERTIFICATE ||
  5520.         ssl->in_hslen < mbedtls_ssl_hs_hdr_len( ssl ) + 3 + 3 )
  5521.     {
  5522.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
  5523.         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  5524.                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  5525.         return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
  5526.     }
  5527.  
  5528.     i = mbedtls_ssl_hs_hdr_len( ssl );
  5529.  
  5530.     /*
  5531.      * Same message structure as in mbedtls_ssl_write_certificate()
  5532.      */
  5533.     n = ( ssl->in_msg[i+1] << 8 ) | ssl->in_msg[i+2];
  5534.  
  5535.     if( ssl->in_msg[i] != 0 ||
  5536.         ssl->in_hslen != n + 3 + mbedtls_ssl_hs_hdr_len( ssl ) )
  5537.     {
  5538.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
  5539.         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  5540.                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  5541.         return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
  5542.     }
  5543.  
  5544.     /* In case we tried to reuse a session but it failed */
  5545.     if( ssl->session_negotiate->peer_cert != NULL )
  5546.     {
  5547.         mbedtls_x509_crt_free( ssl->session_negotiate->peer_cert );
  5548.         mbedtls_free( ssl->session_negotiate->peer_cert );
  5549.     }
  5550.  
  5551.     if( ( ssl->session_negotiate->peer_cert = mbedtls_calloc( 1,
  5552.                     sizeof( mbedtls_x509_crt ) ) ) == NULL )
  5553.     {
  5554.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed",
  5555.                        sizeof( mbedtls_x509_crt ) ) );
  5556.         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  5557.                                         MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
  5558.         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
  5559.     }
  5560.  
  5561.     mbedtls_x509_crt_init( ssl->session_negotiate->peer_cert );
  5562.  
  5563.     i += 3;
  5564.  
  5565.     while( i < ssl->in_hslen )
  5566.     {
  5567.         if ( i + 3 > ssl->in_hslen ) {
  5568.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
  5569.             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  5570.                                            MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  5571.             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
  5572.         }
  5573.         if( ssl->in_msg[i] != 0 )
  5574.         {
  5575.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
  5576.             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  5577.                                             MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  5578.             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
  5579.         }
  5580.  
  5581.         n = ( (unsigned int) ssl->in_msg[i + 1] << 8 )
  5582.             | (unsigned int) ssl->in_msg[i + 2];
  5583.         i += 3;
  5584.  
  5585.         if( n < 128 || i + n > ssl->in_hslen )
  5586.         {
  5587.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
  5588.             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  5589.                                             MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  5590.             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
  5591.         }
  5592.  
  5593.         ret = mbedtls_x509_crt_parse_der( ssl->session_negotiate->peer_cert,
  5594.                                   ssl->in_msg + i, n );
  5595.         switch( ret )
  5596.         {
  5597.         case 0: /*ok*/
  5598.         case MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG + MBEDTLS_ERR_OID_NOT_FOUND:
  5599.             /* Ignore certificate with an unknown algorithm: maybe a
  5600.                prior certificate was already trusted. */
  5601.             break;
  5602.  
  5603.         case MBEDTLS_ERR_X509_ALLOC_FAILED:
  5604.             alert = MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR;
  5605.             goto crt_parse_der_failed;
  5606.  
  5607.         case MBEDTLS_ERR_X509_UNKNOWN_VERSION:
  5608.             alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
  5609.             goto crt_parse_der_failed;
  5610.  
  5611.         default:
  5612.             alert = MBEDTLS_SSL_ALERT_MSG_BAD_CERT;
  5613.         crt_parse_der_failed:
  5614.             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, alert );
  5615.             MBEDTLS_SSL_DEBUG_RET( 1, " mbedtls_x509_crt_parse_der", ret );
  5616.             return( ret );
  5617.         }
  5618.  
  5619.         i += n;
  5620.     }
  5621.  
  5622.     MBEDTLS_SSL_DEBUG_CRT( 3, "peer certificate", ssl->session_negotiate->peer_cert );
  5623.  
  5624.     /*
  5625.      * On client, make sure the server cert doesn't change during renego to
  5626.      * avoid "triple handshake" attack: https://secure-resumption.com/
  5627.      */
  5628. #if defined(MBEDTLS_SSL_RENEGOTIATION) && defined(MBEDTLS_SSL_CLI_C)
  5629.     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&
  5630.         ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
  5631.     {
  5632.         if( ssl->session->peer_cert == NULL )
  5633.         {
  5634.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "new server cert during renegotiation" ) );
  5635.             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  5636.                                             MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED );
  5637.             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
  5638.         }
  5639.  
  5640.         if( ssl->session->peer_cert->raw.len !=
  5641.             ssl->session_negotiate->peer_cert->raw.len ||
  5642.             memcmp( ssl->session->peer_cert->raw.p,
  5643.                     ssl->session_negotiate->peer_cert->raw.p,
  5644.                     ssl->session->peer_cert->raw.len ) != 0 )
  5645.         {
  5646.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "server cert changed during renegotiation" ) );
  5647.             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  5648.                                             MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED );
  5649.             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
  5650.         }
  5651.     }
  5652. #endif /* MBEDTLS_SSL_RENEGOTIATION && MBEDTLS_SSL_CLI_C */
  5653.  
  5654.     return( 0 );
  5655. }
  5656.  
  5657. int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl )
  5658. {
  5659.     int ret;
  5660.     const mbedtls_ssl_ciphersuite_t * const ciphersuite_info =
  5661.           ssl->transform_negotiate->ciphersuite_info;
  5662. #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
  5663.     const int authmode = ssl->handshake->sni_authmode != MBEDTLS_SSL_VERIFY_UNSET
  5664.                        ? ssl->handshake->sni_authmode
  5665.                        : ssl->conf->authmode;
  5666. #else
  5667.     const int authmode = ssl->conf->authmode;
  5668. #endif
  5669.     void *rs_ctx = NULL;
  5670.  
  5671.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) );
  5672.  
  5673.     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
  5674.         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
  5675.         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
  5676.         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
  5677.     {
  5678.         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
  5679.         ssl->state++;
  5680.         return( 0 );
  5681.     }
  5682.  
  5683. #if defined(MBEDTLS_SSL_SRV_C)
  5684.     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
  5685.         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
  5686.     {
  5687.         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
  5688.         ssl->state++;
  5689.         return( 0 );
  5690.     }
  5691.  
  5692.     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
  5693.         authmode == MBEDTLS_SSL_VERIFY_NONE )
  5694.     {
  5695.         ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_SKIP_VERIFY;
  5696.         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
  5697.  
  5698.         ssl->state++;
  5699.         return( 0 );
  5700.     }
  5701. #endif
  5702.  
  5703. #if defined(MBEDTLS_SSL__ECP_RESTARTABLE)
  5704.     if( ssl->handshake->ecrs_enabled &&
  5705.         ssl->handshake->ecrs_state == ssl_ecrs_crt_verify )
  5706.     {
  5707.         goto crt_verify;
  5708.     }
  5709. #endif
  5710.  
  5711.     if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
  5712.     {
  5713.         /* mbedtls_ssl_read_record may have sent an alert already. We
  5714.            let it decide whether to alert. */
  5715.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
  5716.         return( ret );
  5717.     }
  5718.  
  5719.     if( ( ret = ssl_parse_certificate_chain( ssl ) ) != 0 )
  5720.     {
  5721. #if defined(MBEDTLS_SSL_SRV_C)
  5722.         if( ret == MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE &&
  5723.             authmode == MBEDTLS_SSL_VERIFY_OPTIONAL )
  5724.         {
  5725.             ret = 0;
  5726.         }
  5727. #endif
  5728.  
  5729.         ssl->state++;
  5730.         return( ret );
  5731.     }
  5732.  
  5733. #if defined(MBEDTLS_SSL__ECP_RESTARTABLE)
  5734.     if( ssl->handshake->ecrs_enabled)
  5735.         ssl->handshake->ecrs_state = ssl_ecrs_crt_verify;
  5736.  
  5737. crt_verify:
  5738.     if( ssl->handshake->ecrs_enabled)
  5739.         rs_ctx = &ssl->handshake->ecrs_ctx;
  5740. #endif
  5741.  
  5742.     if( authmode != MBEDTLS_SSL_VERIFY_NONE )
  5743.     {
  5744.         mbedtls_x509_crt *ca_chain;
  5745.         mbedtls_x509_crl *ca_crl;
  5746.  
  5747. #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
  5748.         if( ssl->handshake->sni_ca_chain != NULL )
  5749.         {
  5750.             ca_chain = ssl->handshake->sni_ca_chain;
  5751.             ca_crl   = ssl->handshake->sni_ca_crl;
  5752.         }
  5753.         else
  5754. #endif
  5755.         {
  5756.             ca_chain = ssl->conf->ca_chain;
  5757.             ca_crl   = ssl->conf->ca_crl;
  5758.         }
  5759.  
  5760.         /*
  5761.          * Main check: verify certificate
  5762.          */
  5763.         ret = mbedtls_x509_crt_verify_restartable(
  5764.                                 ssl->session_negotiate->peer_cert,
  5765.                                 ca_chain, ca_crl,
  5766.                                 ssl->conf->cert_profile,
  5767.                                 ssl->hostname,
  5768.                                &ssl->session_negotiate->verify_result,
  5769.                                 ssl->conf->f_vrfy, ssl->conf->p_vrfy, rs_ctx );
  5770.  
  5771.         if( ret != 0 )
  5772.         {
  5773.             MBEDTLS_SSL_DEBUG_RET( 1, "x509_verify_cert", ret );
  5774.         }
  5775.  
  5776. #if defined(MBEDTLS_SSL__ECP_RESTARTABLE)
  5777.         if( ret == MBEDTLS_ERR_ECP_IN_PROGRESS )
  5778.             return( MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS );
  5779. #endif
  5780.  
  5781.         /*
  5782.          * Secondary checks: always done, but change 'ret' only if it was 0
  5783.          */
  5784.  
  5785. #if defined(MBEDTLS_ECP_C)
  5786.         {
  5787.             const mbedtls_pk_context *pk = &ssl->session_negotiate->peer_cert->pk;
  5788.  
  5789.             /* If certificate uses an EC key, make sure the curve is OK */
  5790.             if( mbedtls_pk_can_do( pk, MBEDTLS_PK_ECKEY ) &&
  5791.                 mbedtls_ssl_check_curve( ssl, mbedtls_pk_ec( *pk )->grp.id ) != 0 )
  5792.             {
  5793.                 ssl->session_negotiate->verify_result |= MBEDTLS_X509_BADCERT_BAD_KEY;
  5794.  
  5795.                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate (EC key curve)" ) );
  5796.                 if( ret == 0 )
  5797.                     ret = MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE;
  5798.             }
  5799.         }
  5800. #endif /* MBEDTLS_ECP_C */
  5801.  
  5802.         if( mbedtls_ssl_check_cert_usage( ssl->session_negotiate->peer_cert,
  5803.                                  ciphersuite_info,
  5804.                                  ! ssl->conf->endpoint,
  5805.                                  &ssl->session_negotiate->verify_result ) != 0 )
  5806.         {
  5807.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate (usage extensions)" ) );
  5808.             if( ret == 0 )
  5809.                 ret = MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE;
  5810.         }
  5811.  
  5812.         /* mbedtls_x509_crt_verify_with_profile is supposed to report a
  5813.          * verification failure through MBEDTLS_ERR_X509_CERT_VERIFY_FAILED,
  5814.          * with details encoded in the verification flags. All other kinds
  5815.          * of error codes, including those from the user provided f_vrfy
  5816.          * functions, are treated as fatal and lead to a failure of
  5817.          * ssl_parse_certificate even if verification was optional. */
  5818.         if( authmode == MBEDTLS_SSL_VERIFY_OPTIONAL &&
  5819.             ( ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED ||
  5820.               ret == MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE ) )
  5821.         {
  5822.             ret = 0;
  5823.         }
  5824.  
  5825.         if( ca_chain == NULL && authmode == MBEDTLS_SSL_VERIFY_REQUIRED )
  5826.         {
  5827.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no CA chain" ) );
  5828.             ret = MBEDTLS_ERR_SSL_CA_CHAIN_REQUIRED;
  5829.         }
  5830.  
  5831.         if( ret != 0 )
  5832.         {
  5833.             uint8_t alert;
  5834.  
  5835.             /* The certificate may have been rejected for several reasons.
  5836.                Pick one and send the corresponding alert. Which alert to send
  5837.                may be a subject of debate in some cases. */
  5838.             if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_OTHER )
  5839.                 alert = MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED;
  5840.             else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_CN_MISMATCH )
  5841.                 alert = MBEDTLS_SSL_ALERT_MSG_BAD_CERT;
  5842.             else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_KEY_USAGE )
  5843.                 alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
  5844.             else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_EXT_KEY_USAGE )
  5845.                 alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
  5846.             else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_NS_CERT_TYPE )
  5847.                 alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
  5848.             else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_BAD_PK )
  5849.                 alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
  5850.             else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_BAD_KEY )
  5851.                 alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
  5852.             else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_EXPIRED )
  5853.                 alert = MBEDTLS_SSL_ALERT_MSG_CERT_EXPIRED;
  5854.             else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_REVOKED )
  5855.                 alert = MBEDTLS_SSL_ALERT_MSG_CERT_REVOKED;
  5856.             else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_NOT_TRUSTED )
  5857.                 alert = MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA;
  5858.             else
  5859.                 alert = MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN;
  5860.             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  5861.                                             alert );
  5862.         }
  5863.  
  5864. #if defined(MBEDTLS_DEBUG_C)
  5865.         if( ssl->session_negotiate->verify_result != 0 )
  5866.         {
  5867.             MBEDTLS_SSL_DEBUG_MSG( 3, ( "! Certificate verification flags %x",
  5868.                                         ssl->session_negotiate->verify_result ) );
  5869.         }
  5870.         else
  5871.         {
  5872.             MBEDTLS_SSL_DEBUG_MSG( 3, ( "Certificate verification flags clear" ) );
  5873.         }
  5874. #endif /* MBEDTLS_DEBUG_C */
  5875.     }
  5876.  
  5877.     ssl->state++;
  5878.  
  5879.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse certificate" ) );
  5880.  
  5881.     return( ret );
  5882. }
  5883. #endif /* !MBEDTLS_KEY_EXCHANGE_RSA_ENABLED
  5884.           !MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED
  5885.           !MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED
  5886.           !MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED
  5887.           !MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
  5888.           !MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED
  5889.           !MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
  5890.  
  5891. int mbedtls_ssl_write_change_cipher_spec( mbedtls_ssl_context *ssl )
  5892. {
  5893.     int ret;
  5894.  
  5895.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write change cipher spec" ) );
  5896.  
  5897.     ssl->out_msgtype = MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC;
  5898.     ssl->out_msglen  = 1;
  5899.     ssl->out_msg[0]  = 1;
  5900.  
  5901.     ssl->state++;
  5902.  
  5903.     if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
  5904.     {
  5905.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
  5906.         return( ret );
  5907.     }
  5908.  
  5909.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write change cipher spec" ) );
  5910.  
  5911.     return( 0 );
  5912. }
  5913.  
  5914. int mbedtls_ssl_parse_change_cipher_spec( mbedtls_ssl_context *ssl )
  5915. {
  5916.     int ret;
  5917.  
  5918.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse change cipher spec" ) );
  5919.  
  5920.     if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
  5921.     {
  5922.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
  5923.         return( ret );
  5924.     }
  5925.  
  5926.     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC )
  5927.     {
  5928.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad change cipher spec message" ) );
  5929.         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  5930.                                         MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
  5931.         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
  5932.     }
  5933.  
  5934.     /* CCS records are only accepted if they have length 1 and content '1',
  5935.      * so we don't need to check this here. */
  5936.  
  5937.     /*
  5938.      * Switch to our negotiated transform and session parameters for inbound
  5939.      * data.
  5940.      */
  5941.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "switching to new transform spec for inbound data" ) );
  5942.     ssl->transform_in = ssl->transform_negotiate;
  5943.     ssl->session_in = ssl->session_negotiate;
  5944.  
  5945. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  5946.     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  5947.     {
  5948. #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
  5949.         ssl_dtls_replay_reset( ssl );
  5950. #endif
  5951.  
  5952.         /* Increment epoch */
  5953.         if( ++ssl->in_epoch == 0 )
  5954.         {
  5955.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS epoch would wrap" ) );
  5956.             /* This is highly unlikely to happen for legitimate reasons, so
  5957.                treat it as an attack and don't send an alert. */
  5958.             return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
  5959.         }
  5960.     }
  5961.     else
  5962. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  5963.     memset( ssl->in_ctr, 0, 8 );
  5964.  
  5965.     ssl_update_in_pointers( ssl, ssl->transform_negotiate );
  5966.  
  5967. #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
  5968.     if( mbedtls_ssl_hw_record_activate != NULL )
  5969.     {
  5970.         if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_INBOUND ) ) != 0 )
  5971.         {
  5972.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret );
  5973.             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  5974.                                             MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
  5975.             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
  5976.         }
  5977.     }
  5978. #endif
  5979.  
  5980.     ssl->state++;
  5981.  
  5982.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse change cipher spec" ) );
  5983.  
  5984.     return( 0 );
  5985. }
  5986.  
  5987. void mbedtls_ssl_optimize_checksum( mbedtls_ssl_context *ssl,
  5988.                             const mbedtls_ssl_ciphersuite_t *ciphersuite_info )
  5989. {
  5990.     ((void) ciphersuite_info);
  5991.  
  5992. #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
  5993.     defined(MBEDTLS_SSL_PROTO_TLS1_1)
  5994.     if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 )
  5995.         ssl->handshake->update_checksum = ssl_update_checksum_md5sha1;
  5996.     else
  5997. #endif
  5998. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  5999. #if defined(MBEDTLS_SHA512_C)
  6000.     if( ciphersuite_info->mac == MBEDTLS_MD_SHA384 )
  6001.         ssl->handshake->update_checksum = ssl_update_checksum_sha384;
  6002.     else
  6003. #endif
  6004. #if defined(MBEDTLS_SHA256_C)
  6005.     if( ciphersuite_info->mac != MBEDTLS_MD_SHA384 )
  6006.         ssl->handshake->update_checksum = ssl_update_checksum_sha256;
  6007.     else
  6008. #endif
  6009. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  6010.     {
  6011.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  6012.         return;
  6013.     }
  6014. }
  6015.  
  6016. void mbedtls_ssl_reset_checksum( mbedtls_ssl_context *ssl )
  6017. {
  6018. #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
  6019.     defined(MBEDTLS_SSL_PROTO_TLS1_1)
  6020.      mbedtls_md5_starts_ret( &ssl->handshake->fin_md5  );
  6021.     mbedtls_sha1_starts_ret( &ssl->handshake->fin_sha1 );
  6022. #endif
  6023. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  6024. #if defined(MBEDTLS_SHA256_C)
  6025.     mbedtls_sha256_starts_ret( &ssl->handshake->fin_sha256, 0 );
  6026. #endif
  6027. #if defined(MBEDTLS_SHA512_C)
  6028.     mbedtls_sha512_starts_ret( &ssl->handshake->fin_sha512, 1 );
  6029. #endif
  6030. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  6031. }
  6032.  
  6033. static void ssl_update_checksum_start( mbedtls_ssl_context *ssl,
  6034.                                        const unsigned char *buf, size_t len )
  6035. {
  6036. #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
  6037.     defined(MBEDTLS_SSL_PROTO_TLS1_1)
  6038.      mbedtls_md5_update_ret( &ssl->handshake->fin_md5 , buf, len );
  6039.     mbedtls_sha1_update_ret( &ssl->handshake->fin_sha1, buf, len );
  6040. #endif
  6041. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  6042. #if defined(MBEDTLS_SHA256_C)
  6043.     mbedtls_sha256_update_ret( &ssl->handshake->fin_sha256, buf, len );
  6044. #endif
  6045. #if defined(MBEDTLS_SHA512_C)
  6046.     mbedtls_sha512_update_ret( &ssl->handshake->fin_sha512, buf, len );
  6047. #endif
  6048. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  6049. }
  6050.  
  6051. #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
  6052.     defined(MBEDTLS_SSL_PROTO_TLS1_1)
  6053. static void ssl_update_checksum_md5sha1( mbedtls_ssl_context *ssl,
  6054.                                          const unsigned char *buf, size_t len )
  6055. {
  6056.      mbedtls_md5_update_ret( &ssl->handshake->fin_md5 , buf, len );
  6057.     mbedtls_sha1_update_ret( &ssl->handshake->fin_sha1, buf, len );
  6058. }
  6059. #endif
  6060.  
  6061. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  6062. #if defined(MBEDTLS_SHA256_C)
  6063. static void ssl_update_checksum_sha256( mbedtls_ssl_context *ssl,
  6064.                                         const unsigned char *buf, size_t len )
  6065. {
  6066.     mbedtls_sha256_update_ret( &ssl->handshake->fin_sha256, buf, len );
  6067. }
  6068. #endif
  6069.  
  6070. #if defined(MBEDTLS_SHA512_C)
  6071. static void ssl_update_checksum_sha384( mbedtls_ssl_context *ssl,
  6072.                                         const unsigned char *buf, size_t len )
  6073. {
  6074.     mbedtls_sha512_update_ret( &ssl->handshake->fin_sha512, buf, len );
  6075. }
  6076. #endif
  6077. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  6078.  
  6079. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  6080. static void ssl_calc_finished_ssl(
  6081.                 mbedtls_ssl_context *ssl, unsigned char *buf, int from )
  6082. {
  6083.     const char *sender;
  6084.     mbedtls_md5_context  md5;
  6085.     mbedtls_sha1_context sha1;
  6086.  
  6087.     unsigned char padbuf[48];
  6088.     unsigned char md5sum[16];
  6089.     unsigned char sha1sum[20];
  6090.  
  6091.     mbedtls_ssl_session *session = ssl->session_negotiate;
  6092.     if( !session )
  6093.         session = ssl->session;
  6094.  
  6095.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc  finished ssl" ) );
  6096.  
  6097.     mbedtls_md5_init( &md5 );
  6098.     mbedtls_sha1_init( &sha1 );
  6099.  
  6100.     mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
  6101.     mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
  6102.  
  6103.     /*
  6104.      * SSLv3:
  6105.      *   hash =
  6106.      *      MD5( master + pad2 +
  6107.      *          MD5( handshake + sender + master + pad1 ) )
  6108.      *   + SHA1( master + pad2 +
  6109.      *         SHA1( handshake + sender + master + pad1 ) )
  6110.      */
  6111.  
  6112. #if !defined(MBEDTLS_MD5_ALT)
  6113.     MBEDTLS_SSL_DEBUG_BUF( 4, "finished  md5 state", (unsigned char *)
  6114.                     md5.state, sizeof(  md5.state ) );
  6115. #endif
  6116.  
  6117. #if !defined(MBEDTLS_SHA1_ALT)
  6118.     MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha1 state", (unsigned char *)
  6119.                    sha1.state, sizeof( sha1.state ) );
  6120. #endif
  6121.  
  6122.     sender = ( from == MBEDTLS_SSL_IS_CLIENT ) ? "CLNT"
  6123.                                        : "SRVR";
  6124.  
  6125.     memset( padbuf, 0x36, 48 );
  6126.  
  6127.     mbedtls_md5_update_ret( &md5, (const unsigned char *) sender, 4 );
  6128.     mbedtls_md5_update_ret( &md5, session->master, 48 );
  6129.     mbedtls_md5_update_ret( &md5, padbuf, 48 );
  6130.     mbedtls_md5_finish_ret( &md5, md5sum );
  6131.  
  6132.     mbedtls_sha1_update_ret( &sha1, (const unsigned char *) sender, 4 );
  6133.     mbedtls_sha1_update_ret( &sha1, session->master, 48 );
  6134.     mbedtls_sha1_update_ret( &sha1, padbuf, 40 );
  6135.     mbedtls_sha1_finish_ret( &sha1, sha1sum );
  6136.  
  6137.     memset( padbuf, 0x5C, 48 );
  6138.  
  6139.     mbedtls_md5_starts_ret( &md5 );
  6140.     mbedtls_md5_update_ret( &md5, session->master, 48 );
  6141.     mbedtls_md5_update_ret( &md5, padbuf, 48 );
  6142.     mbedtls_md5_update_ret( &md5, md5sum, 16 );
  6143.     mbedtls_md5_finish_ret( &md5, buf );
  6144.  
  6145.     mbedtls_sha1_starts_ret( &sha1 );
  6146.     mbedtls_sha1_update_ret( &sha1, session->master, 48 );
  6147.     mbedtls_sha1_update_ret( &sha1, padbuf , 40 );
  6148.     mbedtls_sha1_update_ret( &sha1, sha1sum, 20 );
  6149.     mbedtls_sha1_finish_ret( &sha1, buf + 16 );
  6150.  
  6151.     MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, 36 );
  6152.  
  6153.     mbedtls_md5_free(  &md5  );
  6154.     mbedtls_sha1_free( &sha1 );
  6155.  
  6156.     mbedtls_platform_zeroize(  padbuf, sizeof(  padbuf ) );
  6157.     mbedtls_platform_zeroize(  md5sum, sizeof(  md5sum ) );
  6158.     mbedtls_platform_zeroize( sha1sum, sizeof( sha1sum ) );
  6159.  
  6160.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc  finished" ) );
  6161. }
  6162. #endif /* MBEDTLS_SSL_PROTO_SSL3 */
  6163.  
  6164. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
  6165. static void ssl_calc_finished_tls(
  6166.                 mbedtls_ssl_context *ssl, unsigned char *buf, int from )
  6167. {
  6168.     int len = 12;
  6169.     const char *sender;
  6170.     mbedtls_md5_context  md5;
  6171.     mbedtls_sha1_context sha1;
  6172.     unsigned char padbuf[36];
  6173.  
  6174.     mbedtls_ssl_session *session = ssl->session_negotiate;
  6175.     if( !session )
  6176.         session = ssl->session;
  6177.  
  6178.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc  finished tls" ) );
  6179.  
  6180.     mbedtls_md5_init( &md5 );
  6181.     mbedtls_sha1_init( &sha1 );
  6182.  
  6183.     mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
  6184.     mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
  6185.  
  6186.     /*
  6187.      * TLSv1:
  6188.      *   hash = PRF( master, finished_label,
  6189.      *               MD5( handshake ) + SHA1( handshake ) )[0..11]
  6190.      */
  6191.  
  6192. #if !defined(MBEDTLS_MD5_ALT)
  6193.     MBEDTLS_SSL_DEBUG_BUF( 4, "finished  md5 state", (unsigned char *)
  6194.                     md5.state, sizeof(  md5.state ) );
  6195. #endif
  6196.  
  6197. #if !defined(MBEDTLS_SHA1_ALT)
  6198.     MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha1 state", (unsigned char *)
  6199.                    sha1.state, sizeof( sha1.state ) );
  6200. #endif
  6201.  
  6202.     sender = ( from == MBEDTLS_SSL_IS_CLIENT )
  6203.              ? "client finished"
  6204.              : "server finished";
  6205.  
  6206.     mbedtls_md5_finish_ret(  &md5, padbuf );
  6207.     mbedtls_sha1_finish_ret( &sha1, padbuf + 16 );
  6208.  
  6209.     ssl->handshake->tls_prf( session->master, 48, sender,
  6210.                              padbuf, 36, buf, len );
  6211.  
  6212.     MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len );
  6213.  
  6214.     mbedtls_md5_free(  &md5  );
  6215.     mbedtls_sha1_free( &sha1 );
  6216.  
  6217.     mbedtls_platform_zeroize(  padbuf, sizeof(  padbuf ) );
  6218.  
  6219.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc  finished" ) );
  6220. }
  6221. #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
  6222.  
  6223. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  6224. #if defined(MBEDTLS_SHA256_C)
  6225. static void ssl_calc_finished_tls_sha256(
  6226.                 mbedtls_ssl_context *ssl, unsigned char *buf, int from )
  6227. {
  6228.     int len = 12;
  6229.     const char *sender;
  6230.     mbedtls_sha256_context sha256;
  6231.     unsigned char padbuf[32];
  6232.  
  6233.     mbedtls_ssl_session *session = ssl->session_negotiate;
  6234.     if( !session )
  6235.         session = ssl->session;
  6236.  
  6237.     mbedtls_sha256_init( &sha256 );
  6238.  
  6239.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc  finished tls sha256" ) );
  6240.  
  6241.     mbedtls_sha256_clone( &sha256, &ssl->handshake->fin_sha256 );
  6242.  
  6243.     /*
  6244.      * TLSv1.2:
  6245.      *   hash = PRF( master, finished_label,
  6246.      *               Hash( handshake ) )[0.11]
  6247.      */
  6248.  
  6249. #if !defined(MBEDTLS_SHA256_ALT)
  6250.     MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha2 state", (unsigned char *)
  6251.                    sha256.state, sizeof( sha256.state ) );
  6252. #endif
  6253.  
  6254.     sender = ( from == MBEDTLS_SSL_IS_CLIENT )
  6255.              ? "client finished"
  6256.              : "server finished";
  6257.  
  6258.     mbedtls_sha256_finish_ret( &sha256, padbuf );
  6259.  
  6260.     ssl->handshake->tls_prf( session->master, 48, sender,
  6261.                              padbuf, 32, buf, len );
  6262.  
  6263.     MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len );
  6264.  
  6265.     mbedtls_sha256_free( &sha256 );
  6266.  
  6267.     mbedtls_platform_zeroize(  padbuf, sizeof(  padbuf ) );
  6268.  
  6269.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc  finished" ) );
  6270. }
  6271. #endif /* MBEDTLS_SHA256_C */
  6272.  
  6273. #if defined(MBEDTLS_SHA512_C)
  6274. static void ssl_calc_finished_tls_sha384(
  6275.                 mbedtls_ssl_context *ssl, unsigned char *buf, int from )
  6276. {
  6277.     int len = 12;
  6278.     const char *sender;
  6279.     mbedtls_sha512_context sha512;
  6280.     unsigned char padbuf[48];
  6281.  
  6282.     mbedtls_ssl_session *session = ssl->session_negotiate;
  6283.     if( !session )
  6284.         session = ssl->session;
  6285.  
  6286.     mbedtls_sha512_init( &sha512 );
  6287.  
  6288.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc  finished tls sha384" ) );
  6289.  
  6290.     mbedtls_sha512_clone( &sha512, &ssl->handshake->fin_sha512 );
  6291.  
  6292.     /*
  6293.      * TLSv1.2:
  6294.      *   hash = PRF( master, finished_label,
  6295.      *               Hash( handshake ) )[0.11]
  6296.      */
  6297.  
  6298. #if !defined(MBEDTLS_SHA512_ALT)
  6299.     MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha512 state", (unsigned char *)
  6300.                    sha512.state, sizeof( sha512.state ) );
  6301. #endif
  6302.  
  6303.     sender = ( from == MBEDTLS_SSL_IS_CLIENT )
  6304.              ? "client finished"
  6305.              : "server finished";
  6306.  
  6307.     mbedtls_sha512_finish_ret( &sha512, padbuf );
  6308.  
  6309.     ssl->handshake->tls_prf( session->master, 48, sender,
  6310.                              padbuf, 48, buf, len );
  6311.  
  6312.     MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len );
  6313.  
  6314.     mbedtls_sha512_free( &sha512 );
  6315.  
  6316.     mbedtls_platform_zeroize(  padbuf, sizeof( padbuf ) );
  6317.  
  6318.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc  finished" ) );
  6319. }
  6320. #endif /* MBEDTLS_SHA512_C */
  6321. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  6322.  
  6323. static void ssl_handshake_wrapup_free_hs_transform( mbedtls_ssl_context *ssl )
  6324. {
  6325.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "=> handshake wrapup: final free" ) );
  6326.  
  6327.     /*
  6328.      * Free our handshake params
  6329.      */
  6330.     mbedtls_ssl_handshake_free( ssl );
  6331.     mbedtls_free( ssl->handshake );
  6332.     ssl->handshake = NULL;
  6333.  
  6334.     /*
  6335.      * Free the previous transform and swith in the current one
  6336.      */
  6337.     if( ssl->transform )
  6338.     {
  6339.         mbedtls_ssl_transform_free( ssl->transform );
  6340.         mbedtls_free( ssl->transform );
  6341.     }
  6342.     ssl->transform = ssl->transform_negotiate;
  6343.     ssl->transform_negotiate = NULL;
  6344.  
  6345.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "<= handshake wrapup: final free" ) );
  6346. }
  6347.  
  6348. void mbedtls_ssl_handshake_wrapup( mbedtls_ssl_context *ssl )
  6349. {
  6350.     int resume = ssl->handshake->resume;
  6351.  
  6352.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "=> handshake wrapup" ) );
  6353.  
  6354. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  6355.     if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
  6356.     {
  6357.         ssl->renego_status =  MBEDTLS_SSL_RENEGOTIATION_DONE;
  6358.         ssl->renego_records_seen = 0;
  6359.     }
  6360. #endif
  6361.  
  6362.     /*
  6363.      * Free the previous session and switch in the current one
  6364.      */
  6365.     if( ssl->session )
  6366.     {
  6367. #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
  6368.         /* RFC 7366 3.1: keep the EtM state */
  6369.         ssl->session_negotiate->encrypt_then_mac =
  6370.                   ssl->session->encrypt_then_mac;
  6371. #endif
  6372.  
  6373.         mbedtls_ssl_session_free( ssl->session );
  6374.         mbedtls_free( ssl->session );
  6375.     }
  6376.     ssl->session = ssl->session_negotiate;
  6377.     ssl->session_negotiate = NULL;
  6378.  
  6379.     /*
  6380.      * Add cache entry
  6381.      */
  6382.     if( ssl->conf->f_set_cache != NULL &&
  6383.         ssl->session->id_len != 0 &&
  6384.         resume == 0 )
  6385.     {
  6386.         if( ssl->conf->f_set_cache( ssl->conf->p_cache, ssl->session ) != 0 )
  6387.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "cache did not store session" ) );
  6388.     }
  6389.  
  6390. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  6391.     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  6392.         ssl->handshake->flight != NULL )
  6393.     {
  6394.         /* Cancel handshake timer */
  6395.         ssl_set_timer( ssl, 0 );
  6396.  
  6397.         /* Keep last flight around in case we need to resend it:
  6398.          * we need the handshake and transform structures for that */
  6399.         MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip freeing handshake and transform" ) );
  6400.     }
  6401.     else
  6402. #endif
  6403.         ssl_handshake_wrapup_free_hs_transform( ssl );
  6404.  
  6405.     ssl->state++;
  6406.  
  6407.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "<= handshake wrapup" ) );
  6408. }
  6409.  
  6410. int mbedtls_ssl_write_finished( mbedtls_ssl_context *ssl )
  6411. {
  6412.     int ret, hash_len;
  6413.  
  6414.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write finished" ) );
  6415.  
  6416.     ssl_update_out_pointers( ssl, ssl->transform_negotiate );
  6417.  
  6418.     ssl->handshake->calc_finished( ssl, ssl->out_msg + 4, ssl->conf->endpoint );
  6419.  
  6420.     /*
  6421.      * RFC 5246 7.4.9 (Page 63) says 12 is the default length and ciphersuites
  6422.      * may define some other value. Currently (early 2016), no defined
  6423.      * ciphersuite does this (and this is unlikely to change as activity has
  6424.      * moved to TLS 1.3 now) so we can keep the hardcoded 12 here.
  6425.      */
  6426.     hash_len = ( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) ? 36 : 12;
  6427.  
  6428. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  6429.     ssl->verify_data_len = hash_len;
  6430.     memcpy( ssl->own_verify_data, ssl->out_msg + 4, hash_len );
  6431. #endif
  6432.  
  6433.     ssl->out_msglen  = 4 + hash_len;
  6434.     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
  6435.     ssl->out_msg[0]  = MBEDTLS_SSL_HS_FINISHED;
  6436.  
  6437.     /*
  6438.      * In case of session resuming, invert the client and server
  6439.      * ChangeCipherSpec messages order.
  6440.      */
  6441.     if( ssl->handshake->resume != 0 )
  6442.     {
  6443. #if defined(MBEDTLS_SSL_CLI_C)
  6444.         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
  6445.             ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
  6446. #endif
  6447. #if defined(MBEDTLS_SSL_SRV_C)
  6448.         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
  6449.             ssl->state = MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC;
  6450. #endif
  6451.     }
  6452.     else
  6453.         ssl->state++;
  6454.  
  6455.     /*
  6456.      * Switch to our negotiated transform and session parameters for outbound
  6457.      * data.
  6458.      */
  6459.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "switching to new transform spec for outbound data" ) );
  6460.  
  6461. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  6462.     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  6463.     {
  6464.         unsigned char i;
  6465.  
  6466.         /* Remember current epoch settings for resending */
  6467.         ssl->handshake->alt_transform_out = ssl->transform_out;
  6468.         memcpy( ssl->handshake->alt_out_ctr, ssl->cur_out_ctr, 8 );
  6469.  
  6470.         /* Set sequence_number to zero */
  6471.         memset( ssl->cur_out_ctr + 2, 0, 6 );
  6472.  
  6473.         /* Increment epoch */
  6474.         for( i = 2; i > 0; i-- )
  6475.             if( ++ssl->cur_out_ctr[i - 1] != 0 )
  6476.                 break;
  6477.  
  6478.         /* The loop goes to its end iff the counter is wrapping */
  6479.         if( i == 0 )
  6480.         {
  6481.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS epoch would wrap" ) );
  6482.             return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
  6483.         }
  6484.     }
  6485.     else
  6486. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  6487.     memset( ssl->cur_out_ctr, 0, 8 );
  6488.  
  6489.     ssl->transform_out = ssl->transform_negotiate;
  6490.     ssl->session_out = ssl->session_negotiate;
  6491.  
  6492. #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
  6493.     if( mbedtls_ssl_hw_record_activate != NULL )
  6494.     {
  6495.         if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_OUTBOUND ) ) != 0 )
  6496.         {
  6497.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret );
  6498.             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
  6499.         }
  6500.     }
  6501. #endif
  6502.  
  6503. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  6504.     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  6505.         mbedtls_ssl_send_flight_completed( ssl );
  6506. #endif
  6507.  
  6508.     if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
  6509.     {
  6510.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
  6511.         return( ret );
  6512.     }
  6513.  
  6514. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  6515.     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  6516.         ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 )
  6517.     {
  6518.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flight_transmit", ret );
  6519.         return( ret );
  6520.     }
  6521. #endif
  6522.  
  6523.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write finished" ) );
  6524.  
  6525.     return( 0 );
  6526. }
  6527.  
  6528. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  6529. #define SSL_MAX_HASH_LEN 36
  6530. #else
  6531. #define SSL_MAX_HASH_LEN 12
  6532. #endif
  6533.  
  6534. int mbedtls_ssl_parse_finished( mbedtls_ssl_context *ssl )
  6535. {
  6536.     int ret;
  6537.     unsigned int hash_len;
  6538.     unsigned char buf[SSL_MAX_HASH_LEN];
  6539.  
  6540.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse finished" ) );
  6541.  
  6542.     ssl->handshake->calc_finished( ssl, buf, ssl->conf->endpoint ^ 1 );
  6543.  
  6544.     if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
  6545.     {
  6546.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
  6547.         return( ret );
  6548.     }
  6549.  
  6550.     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
  6551.     {
  6552.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
  6553.         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  6554.                                         MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
  6555.         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
  6556.     }
  6557.  
  6558.     /* There is currently no ciphersuite using another length with TLS 1.2 */
  6559. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  6560.     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
  6561.         hash_len = 36;
  6562.     else
  6563. #endif
  6564.         hash_len = 12;
  6565.  
  6566.     if( ssl->in_msg[0] != MBEDTLS_SSL_HS_FINISHED ||
  6567.         ssl->in_hslen  != mbedtls_ssl_hs_hdr_len( ssl ) + hash_len )
  6568.     {
  6569.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
  6570.         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  6571.                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  6572.         return( MBEDTLS_ERR_SSL_BAD_HS_FINISHED );
  6573.     }
  6574.  
  6575.     if( mbedtls_ssl_safer_memcmp( ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ),
  6576.                       buf, hash_len ) != 0 )
  6577.     {
  6578.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
  6579.         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  6580.                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
  6581.         return( MBEDTLS_ERR_SSL_BAD_HS_FINISHED );
  6582.     }
  6583.  
  6584. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  6585.     ssl->verify_data_len = hash_len;
  6586.     memcpy( ssl->peer_verify_data, buf, hash_len );
  6587. #endif
  6588.  
  6589.     if( ssl->handshake->resume != 0 )
  6590.     {
  6591. #if defined(MBEDTLS_SSL_CLI_C)
  6592.         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
  6593.             ssl->state = MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC;
  6594. #endif
  6595. #if defined(MBEDTLS_SSL_SRV_C)
  6596.         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
  6597.             ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
  6598. #endif
  6599.     }
  6600.     else
  6601.         ssl->state++;
  6602.  
  6603. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  6604.     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  6605.         mbedtls_ssl_recv_flight_completed( ssl );
  6606. #endif
  6607.  
  6608.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse finished" ) );
  6609.  
  6610.     return( 0 );
  6611. }
  6612.  
  6613. static void ssl_handshake_params_init( mbedtls_ssl_handshake_params *handshake )
  6614. {
  6615.     memset( handshake, 0, sizeof( mbedtls_ssl_handshake_params ) );
  6616.  
  6617. #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
  6618.     defined(MBEDTLS_SSL_PROTO_TLS1_1)
  6619.      mbedtls_md5_init(   &handshake->fin_md5  );
  6620.     mbedtls_sha1_init(   &handshake->fin_sha1 );
  6621.      mbedtls_md5_starts_ret( &handshake->fin_md5  );
  6622.     mbedtls_sha1_starts_ret( &handshake->fin_sha1 );
  6623. #endif
  6624. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  6625. #if defined(MBEDTLS_SHA256_C)
  6626.     mbedtls_sha256_init(   &handshake->fin_sha256    );
  6627.     mbedtls_sha256_starts_ret( &handshake->fin_sha256, 0 );
  6628. #endif
  6629. #if defined(MBEDTLS_SHA512_C)
  6630.     mbedtls_sha512_init(   &handshake->fin_sha512    );
  6631.     mbedtls_sha512_starts_ret( &handshake->fin_sha512, 1 );
  6632. #endif
  6633. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  6634.  
  6635.     handshake->update_checksum = ssl_update_checksum_start;
  6636.  
  6637. #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
  6638.     defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
  6639.     mbedtls_ssl_sig_hash_set_init( &handshake->hash_algs );
  6640. #endif
  6641.  
  6642. #if defined(MBEDTLS_DHM_C)
  6643.     mbedtls_dhm_init( &handshake->dhm_ctx );
  6644. #endif
  6645. #if defined(MBEDTLS_ECDH_C)
  6646.     mbedtls_ecdh_init( &handshake->ecdh_ctx );
  6647. #endif
  6648. #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
  6649.     mbedtls_ecjpake_init( &handshake->ecjpake_ctx );
  6650. #if defined(MBEDTLS_SSL_CLI_C)
  6651.     handshake->ecjpake_cache = NULL;
  6652.     handshake->ecjpake_cache_len = 0;
  6653. #endif
  6654. #endif
  6655.  
  6656. #if defined(MBEDTLS_SSL__ECP_RESTARTABLE)
  6657.     mbedtls_x509_crt_restart_init( &handshake->ecrs_ctx );
  6658. #endif
  6659.  
  6660. #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
  6661.     handshake->sni_authmode = MBEDTLS_SSL_VERIFY_UNSET;
  6662. #endif
  6663. }
  6664.  
  6665. static void ssl_transform_init( mbedtls_ssl_transform *transform )
  6666. {
  6667.     memset( transform, 0, sizeof(mbedtls_ssl_transform) );
  6668.  
  6669.     mbedtls_cipher_init( &transform->cipher_ctx_enc );
  6670.     mbedtls_cipher_init( &transform->cipher_ctx_dec );
  6671.  
  6672.     mbedtls_md_init( &transform->md_ctx_enc );
  6673.     mbedtls_md_init( &transform->md_ctx_dec );
  6674. }
  6675.  
  6676. void mbedtls_ssl_session_init( mbedtls_ssl_session *session )
  6677. {
  6678.     memset( session, 0, sizeof(mbedtls_ssl_session) );
  6679. }
  6680.  
  6681. static int ssl_handshake_init( mbedtls_ssl_context *ssl )
  6682. {
  6683.     /* Clear old handshake information if present */
  6684.     if( ssl->transform_negotiate )
  6685.         mbedtls_ssl_transform_free( ssl->transform_negotiate );
  6686.     if( ssl->session_negotiate )
  6687.         mbedtls_ssl_session_free( ssl->session_negotiate );
  6688.     if( ssl->handshake )
  6689.         mbedtls_ssl_handshake_free( ssl );
  6690.  
  6691.     /*
  6692.      * Either the pointers are now NULL or cleared properly and can be freed.
  6693.      * Now allocate missing structures.
  6694.      */
  6695.     if( ssl->transform_negotiate == NULL )
  6696.     {
  6697.         ssl->transform_negotiate = mbedtls_calloc( 1, sizeof(mbedtls_ssl_transform) );
  6698.     }
  6699.  
  6700.     if( ssl->session_negotiate == NULL )
  6701.     {
  6702.         ssl->session_negotiate = mbedtls_calloc( 1, sizeof(mbedtls_ssl_session) );
  6703.     }
  6704.  
  6705.     if( ssl->handshake == NULL )
  6706.     {
  6707.         ssl->handshake = mbedtls_calloc( 1, sizeof(mbedtls_ssl_handshake_params) );
  6708.     }
  6709.  
  6710.     /* All pointers should exist and can be directly freed without issue */
  6711.     if( ssl->handshake == NULL ||
  6712.         ssl->transform_negotiate == NULL ||
  6713.         ssl->session_negotiate == NULL )
  6714.     {
  6715.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc() of ssl sub-contexts failed" ) );
  6716.  
  6717.         mbedtls_free( ssl->handshake );
  6718.         mbedtls_free( ssl->transform_negotiate );
  6719.         mbedtls_free( ssl->session_negotiate );
  6720.  
  6721.         ssl->handshake = NULL;
  6722.         ssl->transform_negotiate = NULL;
  6723.         ssl->session_negotiate = NULL;
  6724.  
  6725.         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
  6726.     }
  6727.  
  6728.     /* Initialize structures */
  6729.     mbedtls_ssl_session_init( ssl->session_negotiate );
  6730.     ssl_transform_init( ssl->transform_negotiate );
  6731.     ssl_handshake_params_init( ssl->handshake );
  6732.  
  6733. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  6734.     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  6735.     {
  6736.         ssl->handshake->alt_transform_out = ssl->transform_out;
  6737.  
  6738.         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
  6739.             ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_PREPARING;
  6740.         else
  6741.             ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
  6742.  
  6743.         ssl_set_timer( ssl, 0 );
  6744.     }
  6745. #endif
  6746.  
  6747.     return( 0 );
  6748. }
  6749.  
  6750. #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
  6751. /* Dummy cookie callbacks for defaults */
  6752. static int ssl_cookie_write_dummy( void *ctx,
  6753.                       unsigned char **p, unsigned char *end,
  6754.                       const unsigned char *cli_id, size_t cli_id_len )
  6755. {
  6756.     ((void) ctx);
  6757.     ((void) p);
  6758.     ((void) end);
  6759.     ((void) cli_id);
  6760.     ((void) cli_id_len);
  6761.  
  6762.     return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
  6763. }
  6764.  
  6765. static int ssl_cookie_check_dummy( void *ctx,
  6766.                       const unsigned char *cookie, size_t cookie_len,
  6767.                       const unsigned char *cli_id, size_t cli_id_len )
  6768. {
  6769.     ((void) ctx);
  6770.     ((void) cookie);
  6771.     ((void) cookie_len);
  6772.     ((void) cli_id);
  6773.     ((void) cli_id_len);
  6774.  
  6775.     return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
  6776. }
  6777. #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY && MBEDTLS_SSL_SRV_C */
  6778.  
  6779. /* Once ssl->out_hdr as the address of the beginning of the
  6780.  * next outgoing record is set, deduce the other pointers.
  6781.  *
  6782.  * Note: For TLS, we save the implicit record sequence number
  6783.  *       (entering MAC computation) in the 8 bytes before ssl->out_hdr,
  6784.  *       and the caller has to make sure there's space for this.
  6785.  */
  6786.  
  6787. static void ssl_update_out_pointers( mbedtls_ssl_context *ssl,
  6788.                                      mbedtls_ssl_transform *transform )
  6789. {
  6790. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  6791.     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  6792.     {
  6793.         ssl->out_ctr = ssl->out_hdr +  3;
  6794.         ssl->out_len = ssl->out_hdr + 11;
  6795.         ssl->out_iv  = ssl->out_hdr + 13;
  6796.     }
  6797.     else
  6798. #endif
  6799.     {
  6800.         ssl->out_ctr = ssl->out_hdr - 8;
  6801.         ssl->out_len = ssl->out_hdr + 3;
  6802.         ssl->out_iv  = ssl->out_hdr + 5;
  6803.     }
  6804.  
  6805.     /* Adjust out_msg to make space for explicit IV, if used. */
  6806.     if( transform != NULL &&
  6807.         ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
  6808.     {
  6809.         ssl->out_msg = ssl->out_iv + transform->ivlen - transform->fixed_ivlen;
  6810.     }
  6811.     else
  6812.         ssl->out_msg = ssl->out_iv;
  6813. }
  6814.  
  6815. /* Once ssl->in_hdr as the address of the beginning of the
  6816.  * next incoming record is set, deduce the other pointers.
  6817.  *
  6818.  * Note: For TLS, we save the implicit record sequence number
  6819.  *       (entering MAC computation) in the 8 bytes before ssl->in_hdr,
  6820.  *       and the caller has to make sure there's space for this.
  6821.  */
  6822.  
  6823. static void ssl_update_in_pointers( mbedtls_ssl_context *ssl,
  6824.                                     mbedtls_ssl_transform *transform )
  6825. {
  6826. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  6827.     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  6828.     {
  6829.         ssl->in_ctr = ssl->in_hdr +  3;
  6830.         ssl->in_len = ssl->in_hdr + 11;
  6831.         ssl->in_iv  = ssl->in_hdr + 13;
  6832.     }
  6833.     else
  6834. #endif
  6835.     {
  6836.         ssl->in_ctr = ssl->in_hdr - 8;
  6837.         ssl->in_len = ssl->in_hdr + 3;
  6838.         ssl->in_iv  = ssl->in_hdr + 5;
  6839.     }
  6840.  
  6841.     /* Offset in_msg from in_iv to allow space for explicit IV, if used. */
  6842.     if( transform != NULL &&
  6843.         ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
  6844.     {
  6845.         ssl->in_msg = ssl->in_iv + transform->ivlen - transform->fixed_ivlen;
  6846.     }
  6847.     else
  6848.         ssl->in_msg = ssl->in_iv;
  6849. }
  6850.  
  6851. /*
  6852.  * Initialize an SSL context
  6853.  */
  6854. void mbedtls_ssl_init( mbedtls_ssl_context *ssl )
  6855. {
  6856.     memset( ssl, 0, sizeof( mbedtls_ssl_context ) );
  6857. }
  6858.  
  6859. /*
  6860.  * Setup an SSL context
  6861.  */
  6862.  
  6863. static void ssl_reset_in_out_pointers( mbedtls_ssl_context *ssl )
  6864. {
  6865.     /* Set the incoming and outgoing record pointers. */
  6866. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  6867.     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  6868.     {
  6869.         ssl->out_hdr = ssl->out_buf;
  6870.         ssl->in_hdr  = ssl->in_buf;
  6871.     }
  6872.     else
  6873. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  6874.     {
  6875.         ssl->out_hdr = ssl->out_buf + 8;
  6876.         ssl->in_hdr  = ssl->in_buf  + 8;
  6877.     }
  6878.  
  6879.     /* Derive other internal pointers. */
  6880.     ssl_update_out_pointers( ssl, NULL /* no transform enabled */ );
  6881.     ssl_update_in_pointers ( ssl, NULL /* no transform enabled */ );
  6882. }
  6883.  
  6884. int mbedtls_ssl_setup( mbedtls_ssl_context *ssl,
  6885.                        const mbedtls_ssl_config *conf )
  6886. {
  6887.     int ret;
  6888.  
  6889.     ssl->conf = conf;
  6890.  
  6891.     /*
  6892.      * Prepare base structures
  6893.      */
  6894.  
  6895.     /* Set to NULL in case of an error condition */
  6896.     ssl->out_buf = NULL;
  6897.  
  6898.     ssl->in_buf = mbedtls_calloc( 1, MBEDTLS_SSL_IN_BUFFER_LEN );
  6899.     if( ssl->in_buf == NULL )
  6900.     {
  6901.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed", MBEDTLS_SSL_IN_BUFFER_LEN) );
  6902.         ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
  6903.         goto error;
  6904.     }
  6905.  
  6906.     ssl->out_buf = mbedtls_calloc( 1, MBEDTLS_SSL_OUT_BUFFER_LEN );
  6907.     if( ssl->out_buf == NULL )
  6908.     {
  6909.         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed", MBEDTLS_SSL_OUT_BUFFER_LEN) );
  6910.         ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
  6911.         goto error;
  6912.     }
  6913.  
  6914.     ssl_reset_in_out_pointers( ssl );
  6915.  
  6916.     if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
  6917.         goto error;
  6918.  
  6919.     return( 0 );
  6920.  
  6921. error:
  6922.     mbedtls_free( ssl->in_buf );
  6923.     mbedtls_free( ssl->out_buf );
  6924.  
  6925.     ssl->conf = NULL;
  6926.  
  6927.     ssl->in_buf = NULL;
  6928.     ssl->out_buf = NULL;
  6929.  
  6930.     ssl->in_hdr = NULL;
  6931.     ssl->in_ctr = NULL;
  6932.     ssl->in_len = NULL;
  6933.     ssl->in_iv = NULL;
  6934.     ssl->in_msg = NULL;
  6935.  
  6936.     ssl->out_hdr = NULL;
  6937.     ssl->out_ctr = NULL;
  6938.     ssl->out_len = NULL;
  6939.     ssl->out_iv = NULL;
  6940.     ssl->out_msg = NULL;
  6941.  
  6942.     return( ret );
  6943. }
  6944.  
  6945. /*
  6946.  * Reset an initialized and used SSL context for re-use while retaining
  6947.  * all application-set variables, function pointers and data.
  6948.  *
  6949.  * If partial is non-zero, keep data in the input buffer and client ID.
  6950.  * (Use when a DTLS client reconnects from the same port.)
  6951.  */
  6952. static int ssl_session_reset_int( mbedtls_ssl_context *ssl, int partial )
  6953. {
  6954.     int ret;
  6955.  
  6956. #if !defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) ||     \
  6957.     !defined(MBEDTLS_SSL_SRV_C)
  6958.     ((void) partial);
  6959. #endif
  6960.  
  6961.     ssl->state = MBEDTLS_SSL_HELLO_REQUEST;
  6962.  
  6963.     /* Cancel any possibly running timer */
  6964.     ssl_set_timer( ssl, 0 );
  6965.  
  6966. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  6967.     ssl->renego_status = MBEDTLS_SSL_INITIAL_HANDSHAKE;
  6968.     ssl->renego_records_seen = 0;
  6969.  
  6970.     ssl->verify_data_len = 0;
  6971.     memset( ssl->own_verify_data, 0, MBEDTLS_SSL_VERIFY_DATA_MAX_LEN );
  6972.     memset( ssl->peer_verify_data, 0, MBEDTLS_SSL_VERIFY_DATA_MAX_LEN );
  6973. #endif
  6974.     ssl->secure_renegotiation = MBEDTLS_SSL_LEGACY_RENEGOTIATION;
  6975.  
  6976.     ssl->in_offt = NULL;
  6977.     ssl_reset_in_out_pointers( ssl );
  6978.  
  6979.     ssl->in_msgtype = 0;
  6980.     ssl->in_msglen = 0;
  6981. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  6982.     ssl->next_record_offset = 0;
  6983.     ssl->in_epoch = 0;
  6984. #endif
  6985. #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
  6986.     ssl_dtls_replay_reset( ssl );
  6987. #endif
  6988.  
  6989.     ssl->in_hslen = 0;
  6990.     ssl->nb_zero = 0;
  6991.  
  6992.     ssl->keep_current_message = 0;
  6993.  
  6994.     ssl->out_msgtype = 0;
  6995.     ssl->out_msglen = 0;
  6996.     ssl->out_left = 0;
  6997. #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
  6998.     if( ssl->split_done != MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED )
  6999.         ssl->split_done = 0;
  7000. #endif
  7001.  
  7002.     memset( ssl->cur_out_ctr, 0, sizeof( ssl->cur_out_ctr ) );
  7003.  
  7004.     ssl->transform_in = NULL;
  7005.     ssl->transform_out = NULL;
  7006.  
  7007.     ssl->session_in = NULL;
  7008.     ssl->session_out = NULL;
  7009.  
  7010.     memset( ssl->out_buf, 0, MBEDTLS_SSL_OUT_BUFFER_LEN );
  7011.  
  7012. #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
  7013.     if( partial == 0 )
  7014. #endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */
  7015.     {
  7016.         ssl->in_left = 0;
  7017.         memset( ssl->in_buf, 0, MBEDTLS_SSL_IN_BUFFER_LEN );
  7018.     }
  7019.  
  7020. #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
  7021.     if( mbedtls_ssl_hw_record_reset != NULL )
  7022.     {
  7023.         MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_reset()" ) );
  7024.         if( ( ret = mbedtls_ssl_hw_record_reset( ssl ) ) != 0 )
  7025.         {
  7026.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_reset", ret );
  7027.             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
  7028.         }
  7029.     }
  7030. #endif
  7031.  
  7032.     if( ssl->transform )
  7033.     {
  7034.         mbedtls_ssl_transform_free( ssl->transform );
  7035.         mbedtls_free( ssl->transform );
  7036.         ssl->transform = NULL;
  7037.     }
  7038.  
  7039.     if( ssl->session )
  7040.     {
  7041.         mbedtls_ssl_session_free( ssl->session );
  7042.         mbedtls_free( ssl->session );
  7043.         ssl->session = NULL;
  7044.     }
  7045.  
  7046. #if defined(MBEDTLS_SSL_ALPN)
  7047.     ssl->alpn_chosen = NULL;
  7048. #endif
  7049.  
  7050. #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
  7051. #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE)
  7052.     if( partial == 0 )
  7053. #endif
  7054.     {
  7055.         mbedtls_free( ssl->cli_id );
  7056.         ssl->cli_id = NULL;
  7057.         ssl->cli_id_len = 0;
  7058.     }
  7059. #endif
  7060.  
  7061.     if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
  7062.         return( ret );
  7063.  
  7064.     return( 0 );
  7065. }
  7066.  
  7067. /*
  7068.  * Reset an initialized and used SSL context for re-use while retaining
  7069.  * all application-set variables, function pointers and data.
  7070.  */
  7071. int mbedtls_ssl_session_reset( mbedtls_ssl_context *ssl )
  7072. {
  7073.     return( ssl_session_reset_int( ssl, 0 ) );
  7074. }
  7075.  
  7076. /*
  7077.  * SSL set accessors
  7078.  */
  7079. void mbedtls_ssl_conf_endpoint( mbedtls_ssl_config *conf, int endpoint )
  7080. {
  7081.     conf->endpoint   = endpoint;
  7082. }
  7083.  
  7084. void mbedtls_ssl_conf_transport( mbedtls_ssl_config *conf, int transport )
  7085. {
  7086.     conf->transport = transport;
  7087. }
  7088.  
  7089. #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
  7090. void mbedtls_ssl_conf_dtls_anti_replay( mbedtls_ssl_config *conf, char mode )
  7091. {
  7092.     conf->anti_replay = mode;
  7093. }
  7094. #endif
  7095.  
  7096. #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT)
  7097. void mbedtls_ssl_conf_dtls_badmac_limit( mbedtls_ssl_config *conf, unsigned limit )
  7098. {
  7099.     conf->badmac_limit = limit;
  7100. }
  7101. #endif
  7102.  
  7103. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  7104.  
  7105. void mbedtls_ssl_set_datagram_packing( mbedtls_ssl_context *ssl,
  7106.                                        unsigned allow_packing )
  7107. {
  7108.     ssl->disable_datagram_packing = !allow_packing;
  7109. }
  7110.  
  7111. void mbedtls_ssl_conf_handshake_timeout( mbedtls_ssl_config *conf,
  7112.                                          uint32_t min, uint32_t max )
  7113. {
  7114.     conf->hs_timeout_min = min;
  7115.     conf->hs_timeout_max = max;
  7116. }
  7117. #endif
  7118.  
  7119. void mbedtls_ssl_conf_authmode( mbedtls_ssl_config *conf, int authmode )
  7120. {
  7121.     conf->authmode   = authmode;
  7122. }
  7123.  
  7124. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  7125. void mbedtls_ssl_conf_verify( mbedtls_ssl_config *conf,
  7126.                      int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
  7127.                      void *p_vrfy )
  7128. {
  7129.     conf->f_vrfy      = f_vrfy;
  7130.     conf->p_vrfy      = p_vrfy;
  7131. }
  7132. #endif /* MBEDTLS_X509_CRT_PARSE_C */
  7133.  
  7134. void mbedtls_ssl_conf_rng( mbedtls_ssl_config *conf,
  7135.                   int (*f_rng)(void *, unsigned char *, size_t),
  7136.                   void *p_rng )
  7137. {
  7138.     conf->f_rng      = f_rng;
  7139.     conf->p_rng      = p_rng;
  7140. }
  7141.  
  7142. void mbedtls_ssl_conf_dbg( mbedtls_ssl_config *conf,
  7143.                   void (*f_dbg)(void *, int, const char *, int, const char *),
  7144.                   void  *p_dbg )
  7145. {
  7146.     conf->f_dbg      = f_dbg;
  7147.     conf->p_dbg      = p_dbg;
  7148. }
  7149.  
  7150. void mbedtls_ssl_set_bio( mbedtls_ssl_context *ssl,
  7151.         void *p_bio,
  7152.         mbedtls_ssl_send_t *f_send,
  7153.         mbedtls_ssl_recv_t *f_recv,
  7154.         mbedtls_ssl_recv_timeout_t *f_recv_timeout )
  7155. {
  7156.     ssl->p_bio          = p_bio;
  7157.     ssl->f_send         = f_send;
  7158.     ssl->f_recv         = f_recv;
  7159.     ssl->f_recv_timeout = f_recv_timeout;
  7160. }
  7161.  
  7162. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  7163. void mbedtls_ssl_set_mtu( mbedtls_ssl_context *ssl, uint16_t mtu )
  7164. {
  7165.     ssl->mtu = mtu;
  7166. }
  7167. #endif
  7168.  
  7169. void mbedtls_ssl_conf_read_timeout( mbedtls_ssl_config *conf, uint32_t timeout )
  7170. {
  7171.     conf->read_timeout   = timeout;
  7172. }
  7173.  
  7174. void mbedtls_ssl_set_timer_cb( mbedtls_ssl_context *ssl,
  7175.                                void *p_timer,
  7176.                                mbedtls_ssl_set_timer_t *f_set_timer,
  7177.                                mbedtls_ssl_get_timer_t *f_get_timer )
  7178. {
  7179.     ssl->p_timer        = p_timer;
  7180.     ssl->f_set_timer    = f_set_timer;
  7181.     ssl->f_get_timer    = f_get_timer;
  7182.  
  7183.     /* Make sure we start with no timer running */
  7184.     ssl_set_timer( ssl, 0 );
  7185. }
  7186.  
  7187. #if defined(MBEDTLS_SSL_SRV_C)
  7188. void mbedtls_ssl_conf_session_cache( mbedtls_ssl_config *conf,
  7189.         void *p_cache,
  7190.         int (*f_get_cache)(void *, mbedtls_ssl_session *),
  7191.         int (*f_set_cache)(void *, const mbedtls_ssl_session *) )
  7192. {
  7193.     conf->p_cache = p_cache;
  7194.     conf->f_get_cache = f_get_cache;
  7195.     conf->f_set_cache = f_set_cache;
  7196. }
  7197. #endif /* MBEDTLS_SSL_SRV_C */
  7198.  
  7199. #if defined(MBEDTLS_SSL_CLI_C)
  7200. int mbedtls_ssl_set_session( mbedtls_ssl_context *ssl, const mbedtls_ssl_session *session )
  7201. {
  7202.     int ret;
  7203.  
  7204.     if( ssl == NULL ||
  7205.         session == NULL ||
  7206.         ssl->session_negotiate == NULL ||
  7207.         ssl->conf->endpoint != MBEDTLS_SSL_IS_CLIENT )
  7208.     {
  7209.         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  7210.     }
  7211.  
  7212.     if( ( ret = ssl_session_copy( ssl->session_negotiate, session ) ) != 0 )
  7213.         return( ret );
  7214.  
  7215.     ssl->handshake->resume = 1;
  7216.  
  7217.     return( 0 );
  7218. }
  7219. #endif /* MBEDTLS_SSL_CLI_C */
  7220.  
  7221. void mbedtls_ssl_conf_ciphersuites( mbedtls_ssl_config *conf,
  7222.                                    const int *ciphersuites )
  7223. {
  7224.     conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] = ciphersuites;
  7225.     conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] = ciphersuites;
  7226.     conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] = ciphersuites;
  7227.     conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] = ciphersuites;
  7228. }
  7229.  
  7230. void mbedtls_ssl_conf_ciphersuites_for_version( mbedtls_ssl_config *conf,
  7231.                                        const int *ciphersuites,
  7232.                                        int major, int minor )
  7233. {
  7234.     if( major != MBEDTLS_SSL_MAJOR_VERSION_3 )
  7235.         return;
  7236.  
  7237.     if( minor < MBEDTLS_SSL_MINOR_VERSION_0 || minor > MBEDTLS_SSL_MINOR_VERSION_3 )
  7238.         return;
  7239.  
  7240.     conf->ciphersuite_list[minor] = ciphersuites;
  7241. }
  7242.  
  7243. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  7244. void mbedtls_ssl_conf_cert_profile( mbedtls_ssl_config *conf,
  7245.                                     const mbedtls_x509_crt_profile *profile )
  7246. {
  7247.     conf->cert_profile = profile;
  7248. }
  7249.  
  7250. /* Append a new keycert entry to a (possibly empty) list */
  7251. static int ssl_append_key_cert( mbedtls_ssl_key_cert **head,
  7252.                                 mbedtls_x509_crt *cert,
  7253.                                 mbedtls_pk_context *key )
  7254. {
  7255.     mbedtls_ssl_key_cert *new_cert;
  7256.  
  7257.     new_cert = mbedtls_calloc( 1, sizeof( mbedtls_ssl_key_cert ) );
  7258.     if( new_cert == NULL )
  7259.         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
  7260.  
  7261.     new_cert->cert = cert;
  7262.     new_cert->key  = key;
  7263.     new_cert->next = NULL;
  7264.  
  7265.     /* Update head is the list was null, else add to the end */
  7266.     if( *head == NULL )
  7267.     {
  7268.         *head = new_cert;
  7269.     }
  7270.     else
  7271.     {
  7272.         mbedtls_ssl_key_cert *cur = *head;
  7273.         while( cur->next != NULL )
  7274.             cur = cur->next;
  7275.         cur->next = new_cert;
  7276.     }
  7277.  
  7278.     return( 0 );
  7279. }
  7280.  
  7281. int mbedtls_ssl_conf_own_cert( mbedtls_ssl_config *conf,
  7282.                               mbedtls_x509_crt *own_cert,
  7283.                               mbedtls_pk_context *pk_key )
  7284. {
  7285.     return( ssl_append_key_cert( &conf->key_cert, own_cert, pk_key ) );
  7286. }
  7287.  
  7288. void mbedtls_ssl_conf_ca_chain( mbedtls_ssl_config *conf,
  7289.                                mbedtls_x509_crt *ca_chain,
  7290.                                mbedtls_x509_crl *ca_crl )
  7291. {
  7292.     conf->ca_chain   = ca_chain;
  7293.     conf->ca_crl     = ca_crl;
  7294. }
  7295. #endif /* MBEDTLS_X509_CRT_PARSE_C */
  7296.  
  7297. #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
  7298. int mbedtls_ssl_set_hs_own_cert( mbedtls_ssl_context *ssl,
  7299.                                  mbedtls_x509_crt *own_cert,
  7300.                                  mbedtls_pk_context *pk_key )
  7301. {
  7302.     return( ssl_append_key_cert( &ssl->handshake->sni_key_cert,
  7303.                                  own_cert, pk_key ) );
  7304. }
  7305.  
  7306. void mbedtls_ssl_set_hs_ca_chain( mbedtls_ssl_context *ssl,
  7307.                                   mbedtls_x509_crt *ca_chain,
  7308.                                   mbedtls_x509_crl *ca_crl )
  7309. {
  7310.     ssl->handshake->sni_ca_chain   = ca_chain;
  7311.     ssl->handshake->sni_ca_crl     = ca_crl;
  7312. }
  7313.  
  7314. void mbedtls_ssl_set_hs_authmode( mbedtls_ssl_context *ssl,
  7315.                                   int authmode )
  7316. {
  7317.     ssl->handshake->sni_authmode = authmode;
  7318. }
  7319. #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
  7320.  
  7321. #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
  7322. /*
  7323.  * Set EC J-PAKE password for current handshake
  7324.  */
  7325. int mbedtls_ssl_set_hs_ecjpake_password( mbedtls_ssl_context *ssl,
  7326.                                          const unsigned char *pw,
  7327.                                          size_t pw_len )
  7328. {
  7329.     mbedtls_ecjpake_role role;
  7330.  
  7331.     if( ssl->handshake == NULL || ssl->conf == NULL )
  7332.         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  7333.  
  7334.     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
  7335.         role = MBEDTLS_ECJPAKE_SERVER;
  7336.     else
  7337.         role = MBEDTLS_ECJPAKE_CLIENT;
  7338.  
  7339.     return( mbedtls_ecjpake_setup( &ssl->handshake->ecjpake_ctx,
  7340.                                    role,
  7341.                                    MBEDTLS_MD_SHA256,
  7342.                                    MBEDTLS_ECP_DP_SECP256R1,
  7343.                                    pw, pw_len ) );
  7344. }
  7345. #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
  7346.  
  7347. #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
  7348. int mbedtls_ssl_conf_psk( mbedtls_ssl_config *conf,
  7349.                 const unsigned char *psk, size_t psk_len,
  7350.                 const unsigned char *psk_identity, size_t psk_identity_len )
  7351. {
  7352.     if( psk == NULL || psk_identity == NULL )
  7353.         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  7354.  
  7355.     if( psk_len > MBEDTLS_PSK_MAX_LEN )
  7356.         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  7357.  
  7358.     /* Identity len will be encoded on two bytes */
  7359.     if( ( psk_identity_len >> 16 ) != 0 ||
  7360.         psk_identity_len > MBEDTLS_SSL_OUT_CONTENT_LEN )
  7361.     {
  7362.         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  7363.     }
  7364.  
  7365.     if( conf->psk != NULL )
  7366.     {
  7367.         mbedtls_platform_zeroize( conf->psk, conf->psk_len );
  7368.  
  7369.         mbedtls_free( conf->psk );
  7370.         conf->psk = NULL;
  7371.         conf->psk_len = 0;
  7372.     }
  7373.     if( conf->psk_identity != NULL )
  7374.     {
  7375.         mbedtls_free( conf->psk_identity );
  7376.         conf->psk_identity = NULL;
  7377.         conf->psk_identity_len = 0;
  7378.     }
  7379.  
  7380.     if( ( conf->psk = mbedtls_calloc( 1, psk_len ) ) == NULL ||
  7381.         ( conf->psk_identity = mbedtls_calloc( 1, psk_identity_len ) ) == NULL )
  7382.     {
  7383.         mbedtls_free( conf->psk );
  7384.         mbedtls_free( conf->psk_identity );
  7385.         conf->psk = NULL;
  7386.         conf->psk_identity = NULL;
  7387.         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
  7388.     }
  7389.  
  7390.     conf->psk_len = psk_len;
  7391.     conf->psk_identity_len = psk_identity_len;
  7392.  
  7393.     memcpy( conf->psk, psk, conf->psk_len );
  7394.     memcpy( conf->psk_identity, psk_identity, conf->psk_identity_len );
  7395.  
  7396.     return( 0 );
  7397. }
  7398.  
  7399. int mbedtls_ssl_set_hs_psk( mbedtls_ssl_context *ssl,
  7400.                             const unsigned char *psk, size_t psk_len )
  7401. {
  7402.     if( psk == NULL || ssl->handshake == NULL )
  7403.         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  7404.  
  7405.     if( psk_len > MBEDTLS_PSK_MAX_LEN )
  7406.         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  7407.  
  7408.     if( ssl->handshake->psk != NULL )
  7409.     {
  7410.         mbedtls_platform_zeroize( ssl->handshake->psk,
  7411.                                   ssl->handshake->psk_len );
  7412.         mbedtls_free( ssl->handshake->psk );
  7413.         ssl->handshake->psk_len = 0;
  7414.     }
  7415.  
  7416.     if( ( ssl->handshake->psk = mbedtls_calloc( 1, psk_len ) ) == NULL )
  7417.         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
  7418.  
  7419.     ssl->handshake->psk_len = psk_len;
  7420.     memcpy( ssl->handshake->psk, psk, ssl->handshake->psk_len );
  7421.  
  7422.     return( 0 );
  7423. }
  7424.  
  7425. void mbedtls_ssl_conf_psk_cb( mbedtls_ssl_config *conf,
  7426.                      int (*f_psk)(void *, mbedtls_ssl_context *, const unsigned char *,
  7427.                      size_t),
  7428.                      void *p_psk )
  7429. {
  7430.     conf->f_psk = f_psk;
  7431.     conf->p_psk = p_psk;
  7432. }
  7433. #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
  7434.  
  7435. #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
  7436.  
  7437. #if !defined(MBEDTLS_DEPRECATED_REMOVED)
  7438. int mbedtls_ssl_conf_dh_param( mbedtls_ssl_config *conf, const char *dhm_P, const char *dhm_G )
  7439. {
  7440.     int ret;
  7441.  
  7442.     if( ( ret = mbedtls_mpi_read_string( &conf->dhm_P, 16, dhm_P ) ) != 0 ||
  7443.         ( ret = mbedtls_mpi_read_string( &conf->dhm_G, 16, dhm_G ) ) != 0 )
  7444.     {
  7445.         mbedtls_mpi_free( &conf->dhm_P );
  7446.         mbedtls_mpi_free( &conf->dhm_G );
  7447.         return( ret );
  7448.     }
  7449.  
  7450.     return( 0 );
  7451. }
  7452. #endif /* MBEDTLS_DEPRECATED_REMOVED */
  7453.  
  7454. int mbedtls_ssl_conf_dh_param_bin( mbedtls_ssl_config *conf,
  7455.                                    const unsigned char *dhm_P, size_t P_len,
  7456.                                    const unsigned char *dhm_G, size_t G_len )
  7457. {
  7458.     int ret;
  7459.  
  7460.     if( ( ret = mbedtls_mpi_read_binary( &conf->dhm_P, dhm_P, P_len ) ) != 0 ||
  7461.         ( ret = mbedtls_mpi_read_binary( &conf->dhm_G, dhm_G, G_len ) ) != 0 )
  7462.     {
  7463.         mbedtls_mpi_free( &conf->dhm_P );
  7464.         mbedtls_mpi_free( &conf->dhm_G );
  7465.         return( ret );
  7466.     }
  7467.  
  7468.     return( 0 );
  7469. }
  7470.  
  7471. int mbedtls_ssl_conf_dh_param_ctx( mbedtls_ssl_config *conf, mbedtls_dhm_context *dhm_ctx )
  7472. {
  7473.     int ret;
  7474.  
  7475.     if( ( ret = mbedtls_mpi_copy( &conf->dhm_P, &dhm_ctx->P ) ) != 0 ||
  7476.         ( ret = mbedtls_mpi_copy( &conf->dhm_G, &dhm_ctx->G ) ) != 0 )
  7477.     {
  7478.         mbedtls_mpi_free( &conf->dhm_P );
  7479.         mbedtls_mpi_free( &conf->dhm_G );
  7480.         return( ret );
  7481.     }
  7482.  
  7483.     return( 0 );
  7484. }
  7485. #endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_SRV_C */
  7486.  
  7487. #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C)
  7488. /*
  7489.  * Set the minimum length for Diffie-Hellman parameters
  7490.  */
  7491. void mbedtls_ssl_conf_dhm_min_bitlen( mbedtls_ssl_config *conf,
  7492.                                       unsigned int bitlen )
  7493. {
  7494.     conf->dhm_min_bitlen = bitlen;
  7495. }
  7496. #endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_CLI_C */
  7497.  
  7498. #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
  7499. /*
  7500.  * Set allowed/preferred hashes for handshake signatures
  7501.  */
  7502. void mbedtls_ssl_conf_sig_hashes( mbedtls_ssl_config *conf,
  7503.                                   const int *hashes )
  7504. {
  7505.     conf->sig_hashes = hashes;
  7506. }
  7507. #endif /* MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
  7508.  
  7509. #if defined(MBEDTLS_ECP_C)
  7510. /*
  7511.  * Set the allowed elliptic curves
  7512.  */
  7513. void mbedtls_ssl_conf_curves( mbedtls_ssl_config *conf,
  7514.                              const mbedtls_ecp_group_id *curve_list )
  7515. {
  7516.     conf->curve_list = curve_list;
  7517. }
  7518. #endif /* MBEDTLS_ECP_C */
  7519.  
  7520. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  7521. int mbedtls_ssl_set_hostname( mbedtls_ssl_context *ssl, const char *hostname )
  7522. {
  7523.     /* Initialize to suppress unnecessary compiler warning */
  7524.     size_t hostname_len = 0;
  7525.  
  7526.     /* Check if new hostname is valid before
  7527.      * making any change to current one */
  7528.     if( hostname != NULL )
  7529.     {
  7530.         hostname_len = strlen( hostname );
  7531.  
  7532.         if( hostname_len > MBEDTLS_SSL_MAX_HOST_NAME_LEN )
  7533.             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  7534.     }
  7535.  
  7536.     /* Now it's clear that we will overwrite the old hostname,
  7537.      * so we can free it safely */
  7538.  
  7539.     if( ssl->hostname != NULL )
  7540.     {
  7541.         mbedtls_platform_zeroize( ssl->hostname, strlen( ssl->hostname ) );
  7542.         mbedtls_free( ssl->hostname );
  7543.     }
  7544.  
  7545.     /* Passing NULL as hostname shall clear the old one */
  7546.  
  7547.     if( hostname == NULL )
  7548.     {
  7549.         ssl->hostname = NULL;
  7550.     }
  7551.     else
  7552.     {
  7553.         ssl->hostname = mbedtls_calloc( 1, hostname_len + 1 );
  7554.         if( ssl->hostname == NULL )
  7555.             return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
  7556.  
  7557.         memcpy( ssl->hostname, hostname, hostname_len );
  7558.  
  7559.         ssl->hostname[hostname_len] = '\0';
  7560.     }
  7561.  
  7562.     return( 0 );
  7563. }
  7564. #endif /* MBEDTLS_X509_CRT_PARSE_C */
  7565.  
  7566. #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
  7567. void mbedtls_ssl_conf_sni( mbedtls_ssl_config *conf,
  7568.                   int (*f_sni)(void *, mbedtls_ssl_context *,
  7569.                                 const unsigned char *, size_t),
  7570.                   void *p_sni )
  7571. {
  7572.     conf->f_sni = f_sni;
  7573.     conf->p_sni = p_sni;
  7574. }
  7575. #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
  7576.  
  7577. #if defined(MBEDTLS_SSL_ALPN)
  7578. int mbedtls_ssl_conf_alpn_protocols( mbedtls_ssl_config *conf, const char **protos )
  7579. {
  7580.     size_t cur_len, tot_len;
  7581.     const char **p;
  7582.  
  7583.     /*
  7584.      * RFC 7301 3.1: "Empty strings MUST NOT be included and byte strings
  7585.      * MUST NOT be truncated."
  7586.      * We check lengths now rather than later.
  7587.      */
  7588.     tot_len = 0;
  7589.     for( p = protos; *p != NULL; p++ )
  7590.     {
  7591.         cur_len = strlen( *p );
  7592.         tot_len += cur_len;
  7593.  
  7594.         if( cur_len == 0 || cur_len > 255 || tot_len > 65535 )
  7595.             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  7596.     }
  7597.  
  7598.     conf->alpn_list = protos;
  7599.  
  7600.     return( 0 );
  7601. }
  7602.  
  7603. const char *mbedtls_ssl_get_alpn_protocol( const mbedtls_ssl_context *ssl )
  7604. {
  7605.     return( ssl->alpn_chosen );
  7606. }
  7607. #endif /* MBEDTLS_SSL_ALPN */
  7608.  
  7609. void mbedtls_ssl_conf_max_version( mbedtls_ssl_config *conf, int major, int minor )
  7610. {
  7611.     conf->max_major_ver = major;
  7612.     conf->max_minor_ver = minor;
  7613. }
  7614.  
  7615. void mbedtls_ssl_conf_min_version( mbedtls_ssl_config *conf, int major, int minor )
  7616. {
  7617.     conf->min_major_ver = major;
  7618.     conf->min_minor_ver = minor;
  7619. }
  7620.  
  7621. #if defined(MBEDTLS_SSL_FALLBACK_SCSV) && defined(MBEDTLS_SSL_CLI_C)
  7622. void mbedtls_ssl_conf_fallback( mbedtls_ssl_config *conf, char fallback )
  7623. {
  7624.     conf->fallback = fallback;
  7625. }
  7626. #endif
  7627.  
  7628. #if defined(MBEDTLS_SSL_SRV_C)
  7629. void mbedtls_ssl_conf_cert_req_ca_list( mbedtls_ssl_config *conf,
  7630.                                           char cert_req_ca_list )
  7631. {
  7632.     conf->cert_req_ca_list = cert_req_ca_list;
  7633. }
  7634. #endif
  7635.  
  7636. #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
  7637. void mbedtls_ssl_conf_encrypt_then_mac( mbedtls_ssl_config *conf, char etm )
  7638. {
  7639.     conf->encrypt_then_mac = etm;
  7640. }
  7641. #endif
  7642.  
  7643. #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
  7644. void mbedtls_ssl_conf_extended_master_secret( mbedtls_ssl_config *conf, char ems )
  7645. {
  7646.     conf->extended_ms = ems;
  7647. }
  7648. #endif
  7649.  
  7650. #if defined(MBEDTLS_ARC4_C)
  7651. void mbedtls_ssl_conf_arc4_support( mbedtls_ssl_config *conf, char arc4 )
  7652. {
  7653.     conf->arc4_disabled = arc4;
  7654. }
  7655. #endif
  7656.  
  7657. #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
  7658. int mbedtls_ssl_conf_max_frag_len( mbedtls_ssl_config *conf, unsigned char mfl_code )
  7659. {
  7660.     if( mfl_code >= MBEDTLS_SSL_MAX_FRAG_LEN_INVALID ||
  7661.         ssl_mfl_code_to_length( mfl_code ) > MBEDTLS_TLS_EXT_ADV_CONTENT_LEN )
  7662.     {
  7663.         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  7664.     }
  7665.  
  7666.     conf->mfl_code = mfl_code;
  7667.  
  7668.     return( 0 );
  7669. }
  7670. #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
  7671.  
  7672. #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
  7673. void mbedtls_ssl_conf_truncated_hmac( mbedtls_ssl_config *conf, int truncate )
  7674. {
  7675.     conf->trunc_hmac = truncate;
  7676. }
  7677. #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
  7678.  
  7679. #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
  7680. void mbedtls_ssl_conf_cbc_record_splitting( mbedtls_ssl_config *conf, char split )
  7681. {
  7682.     conf->cbc_record_splitting = split;
  7683. }
  7684. #endif
  7685.  
  7686. void mbedtls_ssl_conf_legacy_renegotiation( mbedtls_ssl_config *conf, int allow_legacy )
  7687. {
  7688.     conf->allow_legacy_renegotiation = allow_legacy;
  7689. }
  7690.  
  7691. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  7692. void mbedtls_ssl_conf_renegotiation( mbedtls_ssl_config *conf, int renegotiation )
  7693. {
  7694.     conf->disable_renegotiation = renegotiation;
  7695. }
  7696.  
  7697. void mbedtls_ssl_conf_renegotiation_enforced( mbedtls_ssl_config *conf, int max_records )
  7698. {
  7699.     conf->renego_max_records = max_records;
  7700. }
  7701.  
  7702. void mbedtls_ssl_conf_renegotiation_period( mbedtls_ssl_config *conf,
  7703.                                    const unsigned char period[8] )
  7704. {
  7705.     memcpy( conf->renego_period, period, 8 );
  7706. }
  7707. #endif /* MBEDTLS_SSL_RENEGOTIATION */
  7708.  
  7709. #if defined(MBEDTLS_SSL_SESSION_TICKETS)
  7710. #if defined(MBEDTLS_SSL_CLI_C)
  7711. void mbedtls_ssl_conf_session_tickets( mbedtls_ssl_config *conf, int use_tickets )
  7712. {
  7713.     conf->session_tickets = use_tickets;
  7714. }
  7715. #endif
  7716.  
  7717. #if defined(MBEDTLS_SSL_SRV_C)
  7718. void mbedtls_ssl_conf_session_tickets_cb( mbedtls_ssl_config *conf,
  7719.         mbedtls_ssl_ticket_write_t *f_ticket_write,
  7720.         mbedtls_ssl_ticket_parse_t *f_ticket_parse,
  7721.         void *p_ticket )
  7722. {
  7723.     conf->f_ticket_write = f_ticket_write;
  7724.     conf->f_ticket_parse = f_ticket_parse;
  7725.     conf->p_ticket       = p_ticket;
  7726. }
  7727. #endif
  7728. #endif /* MBEDTLS_SSL_SESSION_TICKETS */
  7729.  
  7730. #if defined(MBEDTLS_SSL_EXPORT_KEYS)
  7731. void mbedtls_ssl_conf_export_keys_cb( mbedtls_ssl_config *conf,
  7732.         mbedtls_ssl_export_keys_t *f_export_keys,
  7733.         void *p_export_keys )
  7734. {
  7735.     conf->f_export_keys = f_export_keys;
  7736.     conf->p_export_keys = p_export_keys;
  7737. }
  7738. #endif
  7739.  
  7740. #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
  7741. void mbedtls_ssl_conf_async_private_cb(
  7742.     mbedtls_ssl_config *conf,
  7743.     mbedtls_ssl_async_sign_t *f_async_sign,
  7744.     mbedtls_ssl_async_decrypt_t *f_async_decrypt,
  7745.     mbedtls_ssl_async_resume_t *f_async_resume,
  7746.     mbedtls_ssl_async_cancel_t *f_async_cancel,
  7747.     void *async_config_data )
  7748. {
  7749.     conf->f_async_sign_start = f_async_sign;
  7750.     conf->f_async_decrypt_start = f_async_decrypt;
  7751.     conf->f_async_resume = f_async_resume;
  7752.     conf->f_async_cancel = f_async_cancel;
  7753.     conf->p_async_config_data = async_config_data;
  7754. }
  7755.  
  7756. void *mbedtls_ssl_conf_get_async_config_data( const mbedtls_ssl_config *conf )
  7757. {
  7758.     return( conf->p_async_config_data );
  7759. }
  7760.  
  7761. void *mbedtls_ssl_get_async_operation_data( const mbedtls_ssl_context *ssl )
  7762. {
  7763.     if( ssl->handshake == NULL )
  7764.         return( NULL );
  7765.     else
  7766.         return( ssl->handshake->user_async_ctx );
  7767. }
  7768.  
  7769. void mbedtls_ssl_set_async_operation_data( mbedtls_ssl_context *ssl,
  7770.                                  void *ctx )
  7771. {
  7772.     if( ssl->handshake != NULL )
  7773.         ssl->handshake->user_async_ctx = ctx;
  7774. }
  7775. #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
  7776.  
  7777. /*
  7778.  * SSL get accessors
  7779.  */
  7780. size_t mbedtls_ssl_get_bytes_avail( const mbedtls_ssl_context *ssl )
  7781. {
  7782.     return( ssl->in_offt == NULL ? 0 : ssl->in_msglen );
  7783. }
  7784.  
  7785. int mbedtls_ssl_check_pending( const mbedtls_ssl_context *ssl )
  7786. {
  7787.     /*
  7788.      * Case A: We're currently holding back
  7789.      * a message for further processing.
  7790.      */
  7791.  
  7792.     if( ssl->keep_current_message == 1 )
  7793.     {
  7794.         MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: record held back for processing" ) );
  7795.         return( 1 );
  7796.     }
  7797.  
  7798.     /*
  7799.      * Case B: Further records are pending in the current datagram.
  7800.      */
  7801.  
  7802. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  7803.     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  7804.         ssl->in_left > ssl->next_record_offset )
  7805.     {
  7806.         MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: more records within current datagram" ) );
  7807.         return( 1 );
  7808.     }
  7809. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  7810.  
  7811.     /*
  7812.      * Case C: A handshake message is being processed.
  7813.      */
  7814.  
  7815.     if( ssl->in_hslen > 0 && ssl->in_hslen < ssl->in_msglen )
  7816.     {
  7817.         MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: more handshake messages within current record" ) );
  7818.         return( 1 );
  7819.     }
  7820.  
  7821.     /*
  7822.      * Case D: An application data message is being processed
  7823.      */
  7824.     if( ssl->in_offt != NULL )
  7825.     {
  7826.         MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: application data record is being processed" ) );
  7827.         return( 1 );
  7828.     }
  7829.  
  7830.     /*
  7831.      * In all other cases, the rest of the message can be dropped.
  7832.      * As in ssl_get_next_record, this needs to be adapted if
  7833.      * we implement support for multiple alerts in single records.
  7834.      */
  7835.  
  7836.     MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: nothing pending" ) );
  7837.     return( 0 );
  7838. }
  7839.  
  7840. uint32_t mbedtls_ssl_get_verify_result( const mbedtls_ssl_context *ssl )
  7841. {
  7842.     if( ssl->session != NULL )
  7843.         return( ssl->session->verify_result );
  7844.  
  7845.     if( ssl->session_negotiate != NULL )
  7846.         return( ssl->session_negotiate->verify_result );
  7847.  
  7848.     return( 0xFFFFFFFF );
  7849. }
  7850.  
  7851. const char *mbedtls_ssl_get_ciphersuite( const mbedtls_ssl_context *ssl )
  7852. {
  7853.     if( ssl == NULL || ssl->session == NULL )
  7854.         return( NULL );
  7855.  
  7856.     return mbedtls_ssl_get_ciphersuite_name( ssl->session->ciphersuite );
  7857. }
  7858.  
  7859. const char *mbedtls_ssl_get_version( const mbedtls_ssl_context *ssl )
  7860. {
  7861. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  7862.     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  7863.     {
  7864.         switch( ssl->minor_ver )
  7865.         {
  7866.             case MBEDTLS_SSL_MINOR_VERSION_2:
  7867.                 return( "DTLSv1.0" );
  7868.  
  7869.             case MBEDTLS_SSL_MINOR_VERSION_3:
  7870.                 return( "DTLSv1.2" );
  7871.  
  7872.             default:
  7873.                 return( "unknown (DTLS)" );
  7874.         }
  7875.     }
  7876. #endif
  7877.  
  7878.     switch( ssl->minor_ver )
  7879.     {
  7880.         case MBEDTLS_SSL_MINOR_VERSION_0:
  7881.             return( "SSLv3.0" );
  7882.  
  7883.         case MBEDTLS_SSL_MINOR_VERSION_1:
  7884.             return( "TLSv1.0" );
  7885.  
  7886.         case MBEDTLS_SSL_MINOR_VERSION_2:
  7887.             return( "TLSv1.1" );
  7888.  
  7889.         case MBEDTLS_SSL_MINOR_VERSION_3:
  7890.             return( "TLSv1.2" );
  7891.  
  7892.         default:
  7893.             return( "unknown" );
  7894.     }
  7895. }
  7896.  
  7897. int mbedtls_ssl_get_record_expansion( const mbedtls_ssl_context *ssl )
  7898. {
  7899.     size_t transform_expansion = 0;
  7900.     const mbedtls_ssl_transform *transform = ssl->transform_out;
  7901.     unsigned block_size;
  7902.  
  7903.     if( transform == NULL )
  7904.         return( (int) mbedtls_ssl_hdr_len( ssl ) );
  7905.  
  7906. #if defined(MBEDTLS_ZLIB_SUPPORT)
  7907.     if( ssl->session_out->compression != MBEDTLS_SSL_COMPRESS_NULL )
  7908.         return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
  7909. #endif
  7910.  
  7911.     switch( mbedtls_cipher_get_cipher_mode( &transform->cipher_ctx_enc ) )
  7912.     {
  7913.         case MBEDTLS_MODE_GCM:
  7914.         case MBEDTLS_MODE_CCM:
  7915.         case MBEDTLS_MODE_CHACHAPOLY:
  7916.         case MBEDTLS_MODE_STREAM:
  7917.             transform_expansion = transform->minlen;
  7918.             break;
  7919.  
  7920.         case MBEDTLS_MODE_CBC:
  7921.  
  7922.             block_size = mbedtls_cipher_get_block_size(
  7923.                 &transform->cipher_ctx_enc );
  7924.  
  7925.             /* Expansion due to the addition of the MAC. */
  7926.             transform_expansion += transform->maclen;
  7927.  
  7928.             /* Expansion due to the addition of CBC padding;
  7929.              * Theoretically up to 256 bytes, but we never use
  7930.              * more than the block size of the underlying cipher. */
  7931.             transform_expansion += block_size;
  7932.  
  7933.             /* For TLS 1.1 or higher, an explicit IV is added
  7934.              * after the record header. */
  7935. #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
  7936.             if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
  7937.                 transform_expansion += block_size;
  7938. #endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */
  7939.  
  7940.             break;
  7941.  
  7942.         default:
  7943.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  7944.             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  7945.     }
  7946.  
  7947.     return( (int)( mbedtls_ssl_hdr_len( ssl ) + transform_expansion ) );
  7948. }
  7949.  
  7950. #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
  7951. size_t mbedtls_ssl_get_max_frag_len( const mbedtls_ssl_context *ssl )
  7952. {
  7953.     size_t max_len;
  7954.  
  7955.     /*
  7956.      * Assume mfl_code is correct since it was checked when set
  7957.      */
  7958.     max_len = ssl_mfl_code_to_length( ssl->conf->mfl_code );
  7959.  
  7960.     /* Check if a smaller max length was negotiated */
  7961.     if( ssl->session_out != NULL &&
  7962.         ssl_mfl_code_to_length( ssl->session_out->mfl_code ) < max_len )
  7963.     {
  7964.         max_len = ssl_mfl_code_to_length( ssl->session_out->mfl_code );
  7965.     }
  7966.  
  7967.     /* During a handshake, use the value being negotiated */
  7968.     if( ssl->session_negotiate != NULL &&
  7969.         ssl_mfl_code_to_length( ssl->session_negotiate->mfl_code ) < max_len )
  7970.     {
  7971.         max_len = ssl_mfl_code_to_length( ssl->session_negotiate->mfl_code );
  7972.     }
  7973.  
  7974.     return( max_len );
  7975. }
  7976. #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
  7977.  
  7978. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  7979. static size_t ssl_get_current_mtu( const mbedtls_ssl_context *ssl )
  7980. {
  7981.     /* Return unlimited mtu for client hello messages to avoid fragmentation. */
  7982.     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&
  7983.         ( ssl->state == MBEDTLS_SSL_CLIENT_HELLO ||
  7984.           ssl->state == MBEDTLS_SSL_SERVER_HELLO ) )
  7985.         return ( 0 );
  7986.  
  7987.     if( ssl->handshake == NULL || ssl->handshake->mtu == 0 )
  7988.         return( ssl->mtu );
  7989.  
  7990.     if( ssl->mtu == 0 )
  7991.         return( ssl->handshake->mtu );
  7992.  
  7993.     return( ssl->mtu < ssl->handshake->mtu ?
  7994.             ssl->mtu : ssl->handshake->mtu );
  7995. }
  7996. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  7997.  
  7998. int mbedtls_ssl_get_max_out_record_payload( const mbedtls_ssl_context *ssl )
  7999. {
  8000.     size_t max_len = MBEDTLS_SSL_OUT_CONTENT_LEN;
  8001.  
  8002. #if !defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) && \
  8003.     !defined(MBEDTLS_SSL_PROTO_DTLS)
  8004.     (void) ssl;
  8005. #endif
  8006.  
  8007. #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
  8008.     const size_t mfl = mbedtls_ssl_get_max_frag_len( ssl );
  8009.  
  8010.     if( max_len > mfl )
  8011.         max_len = mfl;
  8012. #endif
  8013.  
  8014. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  8015.     if( ssl_get_current_mtu( ssl ) != 0 )
  8016.     {
  8017.         const size_t mtu = ssl_get_current_mtu( ssl );
  8018.         const int ret = mbedtls_ssl_get_record_expansion( ssl );
  8019.         const size_t overhead = (size_t) ret;
  8020.  
  8021.         if( ret < 0 )
  8022.             return( ret );
  8023.  
  8024.         if( mtu <= overhead )
  8025.         {
  8026.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "MTU too low for record expansion" ) );
  8027.             return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
  8028.         }
  8029.  
  8030.         if( max_len > mtu - overhead )
  8031.             max_len = mtu - overhead;
  8032.     }
  8033. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  8034.  
  8035. #if !defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) &&        \
  8036.     !defined(MBEDTLS_SSL_PROTO_DTLS)
  8037.     ((void) ssl);
  8038. #endif
  8039.  
  8040.     return( (int) max_len );
  8041. }
  8042.  
  8043. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  8044. const mbedtls_x509_crt *mbedtls_ssl_get_peer_cert( const mbedtls_ssl_context *ssl )
  8045. {
  8046.     if( ssl == NULL || ssl->session == NULL )
  8047.         return( NULL );
  8048.  
  8049.     return( ssl->session->peer_cert );
  8050. }
  8051. #endif /* MBEDTLS_X509_CRT_PARSE_C */
  8052.  
  8053. #if defined(MBEDTLS_SSL_CLI_C)
  8054. int mbedtls_ssl_get_session( const mbedtls_ssl_context *ssl, mbedtls_ssl_session *dst )
  8055. {
  8056.     if( ssl == NULL ||
  8057.         dst == NULL ||
  8058.         ssl->session == NULL ||
  8059.         ssl->conf->endpoint != MBEDTLS_SSL_IS_CLIENT )
  8060.     {
  8061.         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  8062.     }
  8063.  
  8064.     return( ssl_session_copy( dst, ssl->session ) );
  8065. }
  8066. #endif /* MBEDTLS_SSL_CLI_C */
  8067.  
  8068. /*
  8069.  * Perform a single step of the SSL handshake
  8070.  */
  8071. int mbedtls_ssl_handshake_step( mbedtls_ssl_context *ssl )
  8072. {
  8073.     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
  8074.  
  8075.     if( ssl == NULL || ssl->conf == NULL )
  8076.         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  8077.  
  8078. #if defined(MBEDTLS_SSL_CLI_C)
  8079.     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
  8080.         ret = mbedtls_ssl_handshake_client_step( ssl );
  8081. #endif
  8082. #if defined(MBEDTLS_SSL_SRV_C)
  8083.     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
  8084.         ret = mbedtls_ssl_handshake_server_step( ssl );
  8085. #endif
  8086.  
  8087.     return( ret );
  8088. }
  8089.  
  8090. /*
  8091.  * Perform the SSL handshake
  8092.  */
  8093. int mbedtls_ssl_handshake( mbedtls_ssl_context *ssl )
  8094. {
  8095.     int ret = 0;
  8096.  
  8097.     if( ssl == NULL || ssl->conf == NULL )
  8098.         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  8099.  
  8100.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> handshake" ) );
  8101.  
  8102.     while( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
  8103.     {
  8104.         ret = mbedtls_ssl_handshake_step( ssl );
  8105.  
  8106.         if( ret != 0 )
  8107.             break;
  8108.     }
  8109.  
  8110.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= handshake" ) );
  8111.  
  8112.     return( ret );
  8113. }
  8114.  
  8115. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  8116. #if defined(MBEDTLS_SSL_SRV_C)
  8117. /*
  8118.  * Write HelloRequest to request renegotiation on server
  8119.  */
  8120. static int ssl_write_hello_request( mbedtls_ssl_context *ssl )
  8121. {
  8122.     int ret;
  8123.  
  8124.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write hello request" ) );
  8125.  
  8126.     ssl->out_msglen  = 4;
  8127.     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
  8128.     ssl->out_msg[0]  = MBEDTLS_SSL_HS_HELLO_REQUEST;
  8129.  
  8130.     if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
  8131.     {
  8132.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
  8133.         return( ret );
  8134.     }
  8135.  
  8136.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write hello request" ) );
  8137.  
  8138.     return( 0 );
  8139. }
  8140. #endif /* MBEDTLS_SSL_SRV_C */
  8141.  
  8142. /*
  8143.  * Actually renegotiate current connection, triggered by either:
  8144.  * - any side: calling mbedtls_ssl_renegotiate(),
  8145.  * - client: receiving a HelloRequest during mbedtls_ssl_read(),
  8146.  * - server: receiving any handshake message on server during mbedtls_ssl_read() after
  8147.  *   the initial handshake is completed.
  8148.  * If the handshake doesn't complete due to waiting for I/O, it will continue
  8149.  * during the next calls to mbedtls_ssl_renegotiate() or mbedtls_ssl_read() respectively.
  8150.  */
  8151. static int ssl_start_renegotiation( mbedtls_ssl_context *ssl )
  8152. {
  8153.     int ret;
  8154.  
  8155.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> renegotiate" ) );
  8156.  
  8157.     if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
  8158.         return( ret );
  8159.  
  8160.     /* RFC 6347 4.2.2: "[...] the HelloRequest will have message_seq = 0 and
  8161.      * the ServerHello will have message_seq = 1" */
  8162. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  8163.     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  8164.         ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
  8165.     {
  8166.         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
  8167.             ssl->handshake->out_msg_seq = 1;
  8168.         else
  8169.             ssl->handshake->in_msg_seq = 1;
  8170.     }
  8171. #endif
  8172.  
  8173.     ssl->state = MBEDTLS_SSL_HELLO_REQUEST;
  8174.     ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS;
  8175.  
  8176.     if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 )
  8177.     {
  8178.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
  8179.         return( ret );
  8180.     }
  8181.  
  8182.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= renegotiate" ) );
  8183.  
  8184.     return( 0 );
  8185. }
  8186.  
  8187. /*
  8188.  * Renegotiate current connection on client,
  8189.  * or request renegotiation on server
  8190.  */
  8191. int mbedtls_ssl_renegotiate( mbedtls_ssl_context *ssl )
  8192. {
  8193.     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
  8194.  
  8195.     if( ssl == NULL || ssl->conf == NULL )
  8196.         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  8197.  
  8198. #if defined(MBEDTLS_SSL_SRV_C)
  8199.     /* On server, just send the request */
  8200.     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
  8201.     {
  8202.         if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
  8203.             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  8204.  
  8205.         ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_PENDING;
  8206.  
  8207.         /* Did we already try/start sending HelloRequest? */
  8208.         if( ssl->out_left != 0 )
  8209.             return( mbedtls_ssl_flush_output( ssl ) );
  8210.  
  8211.         return( ssl_write_hello_request( ssl ) );
  8212.     }
  8213. #endif /* MBEDTLS_SSL_SRV_C */
  8214.  
  8215. #if defined(MBEDTLS_SSL_CLI_C)
  8216.     /*
  8217.      * On client, either start the renegotiation process or,
  8218.      * if already in progress, continue the handshake
  8219.      */
  8220.     if( ssl->renego_status != MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
  8221.     {
  8222.         if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
  8223.             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  8224.  
  8225.         if( ( ret = ssl_start_renegotiation( ssl ) ) != 0 )
  8226.         {
  8227.             MBEDTLS_SSL_DEBUG_RET( 1, "ssl_start_renegotiation", ret );
  8228.             return( ret );
  8229.         }
  8230.     }
  8231.     else
  8232.     {
  8233.         if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 )
  8234.         {
  8235.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
  8236.             return( ret );
  8237.         }
  8238.     }
  8239. #endif /* MBEDTLS_SSL_CLI_C */
  8240.  
  8241.     return( ret );
  8242. }
  8243.  
  8244. /*
  8245.  * Check record counters and renegotiate if they're above the limit.
  8246.  */
  8247. static int ssl_check_ctr_renegotiate( mbedtls_ssl_context *ssl )
  8248. {
  8249.     size_t ep_len = ssl_ep_len( ssl );
  8250.     int in_ctr_cmp;
  8251.     int out_ctr_cmp;
  8252.  
  8253.     if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ||
  8254.         ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING ||
  8255.         ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED )
  8256.     {
  8257.         return( 0 );
  8258.     }
  8259.  
  8260.     in_ctr_cmp = memcmp( ssl->in_ctr + ep_len,
  8261.                         ssl->conf->renego_period + ep_len, 8 - ep_len );
  8262.     out_ctr_cmp = memcmp( ssl->cur_out_ctr + ep_len,
  8263.                           ssl->conf->renego_period + ep_len, 8 - ep_len );
  8264.  
  8265.     if( in_ctr_cmp <= 0 && out_ctr_cmp <= 0 )
  8266.     {
  8267.         return( 0 );
  8268.     }
  8269.  
  8270.     MBEDTLS_SSL_DEBUG_MSG( 1, ( "record counter limit reached: renegotiate" ) );
  8271.     return( mbedtls_ssl_renegotiate( ssl ) );
  8272. }
  8273. #endif /* MBEDTLS_SSL_RENEGOTIATION */
  8274.  
  8275. /*
  8276.  * Receive application data decrypted from the SSL layer
  8277.  */
  8278. int mbedtls_ssl_read( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len )
  8279. {
  8280.     int ret;
  8281.     size_t n;
  8282.  
  8283.     if( ssl == NULL || ssl->conf == NULL )
  8284.         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  8285.  
  8286.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> read" ) );
  8287.  
  8288. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  8289.     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  8290.     {
  8291.         if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
  8292.             return( ret );
  8293.  
  8294.         if( ssl->handshake != NULL &&
  8295.             ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING )
  8296.         {
  8297.             if( ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 )
  8298.                 return( ret );
  8299.         }
  8300.     }
  8301. #endif
  8302.  
  8303.     /*
  8304.      * Check if renegotiation is necessary and/or handshake is
  8305.      * in process. If yes, perform/continue, and fall through
  8306.      * if an unexpected packet is received while the client
  8307.      * is waiting for the ServerHello.
  8308.      *
  8309.      * (There is no equivalent to the last condition on
  8310.      *  the server-side as it is not treated as within
  8311.      *  a handshake while waiting for the ClientHello
  8312.      *  after a renegotiation request.)
  8313.      */
  8314.  
  8315. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  8316.     ret = ssl_check_ctr_renegotiate( ssl );
  8317.     if( ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO &&
  8318.         ret != 0 )
  8319.     {
  8320.         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_check_ctr_renegotiate", ret );
  8321.         return( ret );
  8322.     }
  8323. #endif
  8324.  
  8325.     if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
  8326.     {
  8327.         ret = mbedtls_ssl_handshake( ssl );
  8328.         if( ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO &&
  8329.             ret != 0 )
  8330.         {
  8331.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
  8332.             return( ret );
  8333.         }
  8334.     }
  8335.  
  8336.     /* Loop as long as no application data record is available */
  8337.     while( ssl->in_offt == NULL )
  8338.     {
  8339.         /* Start timer if not already running */
  8340.         if( ssl->f_get_timer != NULL &&
  8341.             ssl->f_get_timer( ssl->p_timer ) == -1 )
  8342.         {
  8343.             ssl_set_timer( ssl, ssl->conf->read_timeout );
  8344.         }
  8345.  
  8346.         if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
  8347.         {
  8348.             if( ret == MBEDTLS_ERR_SSL_CONN_EOF )
  8349.                 return( 0 );
  8350.  
  8351.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
  8352.             return( ret );
  8353.         }
  8354.  
  8355.         if( ssl->in_msglen  == 0 &&
  8356.             ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA )
  8357.         {
  8358.             /*
  8359.              * OpenSSL sends empty messages to randomize the IV
  8360.              */
  8361.             if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
  8362.             {
  8363.                 if( ret == MBEDTLS_ERR_SSL_CONN_EOF )
  8364.                     return( 0 );
  8365.  
  8366.                 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
  8367.                 return( ret );
  8368.             }
  8369.         }
  8370.  
  8371.         if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE )
  8372.         {
  8373.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "received handshake message" ) );
  8374.  
  8375.             /*
  8376.              * - For client-side, expect SERVER_HELLO_REQUEST.
  8377.              * - For server-side, expect CLIENT_HELLO.
  8378.              * - Fail (TLS) or silently drop record (DTLS) in other cases.
  8379.              */
  8380.  
  8381. #if defined(MBEDTLS_SSL_CLI_C)
  8382.             if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&
  8383.                 ( ssl->in_msg[0] != MBEDTLS_SSL_HS_HELLO_REQUEST ||
  8384.                   ssl->in_hslen  != mbedtls_ssl_hs_hdr_len( ssl ) ) )
  8385.             {
  8386.                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake received (not HelloRequest)" ) );
  8387.  
  8388.                 /* With DTLS, drop the packet (probably from last handshake) */
  8389. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  8390.                 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  8391.                 {
  8392.                     continue;
  8393.                 }
  8394. #endif
  8395.                 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
  8396.             }
  8397. #endif /* MBEDTLS_SSL_CLI_C */
  8398.  
  8399. #if defined(MBEDTLS_SSL_SRV_C)
  8400.             if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
  8401.                 ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_HELLO )
  8402.             {
  8403.                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake received (not ClientHello)" ) );
  8404.  
  8405.                 /* With DTLS, drop the packet (probably from last handshake) */
  8406. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  8407.                 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  8408.                 {
  8409.                     continue;
  8410.                 }
  8411. #endif
  8412.                 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
  8413.             }
  8414. #endif /* MBEDTLS_SSL_SRV_C */
  8415.  
  8416. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  8417.             /* Determine whether renegotiation attempt should be accepted */
  8418.             if( ! ( ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED ||
  8419.                     ( ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
  8420.                       ssl->conf->allow_legacy_renegotiation ==
  8421.                                                    MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION ) ) )
  8422.             {
  8423.                 /*
  8424.                  * Accept renegotiation request
  8425.                  */
  8426.  
  8427.                 /* DTLS clients need to know renego is server-initiated */
  8428. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  8429.                 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
  8430.                     ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
  8431.                 {
  8432.                     ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_PENDING;
  8433.                 }
  8434. #endif
  8435.                 ret = ssl_start_renegotiation( ssl );
  8436.                 if( ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO &&
  8437.                     ret != 0 )
  8438.                 {
  8439.                     MBEDTLS_SSL_DEBUG_RET( 1, "ssl_start_renegotiation", ret );
  8440.                     return( ret );
  8441.                 }
  8442.             }
  8443.             else
  8444. #endif /* MBEDTLS_SSL_RENEGOTIATION */
  8445.             {
  8446.                 /*
  8447.                  * Refuse renegotiation
  8448.                  */
  8449.  
  8450.                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "refusing renegotiation, sending alert" ) );
  8451.  
  8452. #if defined(MBEDTLS_SSL_PROTO_SSL3)
  8453.                 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
  8454.                 {
  8455.                     /* SSLv3 does not have a "no_renegotiation" warning, so
  8456.                        we send a fatal alert and abort the connection. */
  8457.                     mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  8458.                                                     MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
  8459.                     return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
  8460.                 }
  8461.                 else
  8462. #endif /* MBEDTLS_SSL_PROTO_SSL3 */
  8463. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
  8464.     defined(MBEDTLS_SSL_PROTO_TLS1_2)
  8465.                 if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 )
  8466.                 {
  8467.                     if( ( ret = mbedtls_ssl_send_alert_message( ssl,
  8468.                                     MBEDTLS_SSL_ALERT_LEVEL_WARNING,
  8469.                                     MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION ) ) != 0 )
  8470.                     {
  8471.                         return( ret );
  8472.                     }
  8473.                 }
  8474.                 else
  8475. #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 ||
  8476.           MBEDTLS_SSL_PROTO_TLS1_2 */
  8477.                 {
  8478.                     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
  8479.                     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
  8480.                 }
  8481.             }
  8482.  
  8483.             /* At this point, we don't know whether the renegotiation has been
  8484.              * completed or not. The cases to consider are the following:
  8485.              * 1) The renegotiation is complete. In this case, no new record
  8486.              *    has been read yet.
  8487.              * 2) The renegotiation is incomplete because the client received
  8488.              *    an application data record while awaiting the ServerHello.
  8489.              * 3) The renegotiation is incomplete because the client received
  8490.              *    a non-handshake, non-application data message while awaiting
  8491.              *    the ServerHello.
  8492.              * In each of these case, looping will be the proper action:
  8493.              * - For 1), the next iteration will read a new record and check
  8494.              *   if it's application data.
  8495.              * - For 2), the loop condition isn't satisfied as application data
  8496.              *   is present, hence continue is the same as break
  8497.              * - For 3), the loop condition is satisfied and read_record
  8498.              *   will re-deliver the message that was held back by the client
  8499.              *   when expecting the ServerHello.
  8500.              */
  8501.             continue;
  8502.         }
  8503. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  8504.         else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
  8505.         {
  8506.             if( ssl->conf->renego_max_records >= 0 )
  8507.             {
  8508.                 if( ++ssl->renego_records_seen > ssl->conf->renego_max_records )
  8509.                 {
  8510.                     MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation requested, "
  8511.                                         "but not honored by client" ) );
  8512.                     return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
  8513.                 }
  8514.             }
  8515.         }
  8516. #endif /* MBEDTLS_SSL_RENEGOTIATION */
  8517.  
  8518.         /* Fatal and closure alerts handled by mbedtls_ssl_read_record() */
  8519.         if( ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT )
  8520.         {
  8521.             MBEDTLS_SSL_DEBUG_MSG( 2, ( "ignoring non-fatal non-closure alert" ) );
  8522.             return( MBEDTLS_ERR_SSL_WANT_READ );
  8523.         }
  8524.  
  8525.         if( ssl->in_msgtype != MBEDTLS_SSL_MSG_APPLICATION_DATA )
  8526.         {
  8527.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad application data message" ) );
  8528.             return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
  8529.         }
  8530.  
  8531.         ssl->in_offt = ssl->in_msg;
  8532.  
  8533.         /* We're going to return something now, cancel timer,
  8534.          * except if handshake (renegotiation) is in progress */
  8535.         if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )
  8536.             ssl_set_timer( ssl, 0 );
  8537.  
  8538. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  8539.         /* If we requested renego but received AppData, resend HelloRequest.
  8540.          * Do it now, after setting in_offt, to avoid taking this branch
  8541.          * again if ssl_write_hello_request() returns WANT_WRITE */
  8542. #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
  8543.         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
  8544.             ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
  8545.         {
  8546.             if( ( ret = ssl_resend_hello_request( ssl ) ) != 0 )
  8547.             {
  8548.                 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_resend_hello_request", ret );
  8549.                 return( ret );
  8550.             }
  8551.         }
  8552. #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
  8553. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  8554.     }
  8555.  
  8556.     n = ( len < ssl->in_msglen )
  8557.         ? len : ssl->in_msglen;
  8558.  
  8559.     memcpy( buf, ssl->in_offt, n );
  8560.     ssl->in_msglen -= n;
  8561.  
  8562.     if( ssl->in_msglen == 0 )
  8563.     {
  8564.         /* all bytes consumed */
  8565.         ssl->in_offt = NULL;
  8566.         ssl->keep_current_message = 0;
  8567.     }
  8568.     else
  8569.     {
  8570.         /* more data available */
  8571.         ssl->in_offt += n;
  8572.     }
  8573.  
  8574.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= read" ) );
  8575.  
  8576.     return( (int) n );
  8577. }
  8578.  
  8579. /*
  8580.  * Send application data to be encrypted by the SSL layer, taking care of max
  8581.  * fragment length and buffer size.
  8582.  *
  8583.  * According to RFC 5246 Section 6.2.1:
  8584.  *
  8585.  *      Zero-length fragments of Application data MAY be sent as they are
  8586.  *      potentially useful as a traffic analysis countermeasure.
  8587.  *
  8588.  * Therefore, it is possible that the input message length is 0 and the
  8589.  * corresponding return code is 0 on success.
  8590.  */
  8591. static int ssl_write_real( mbedtls_ssl_context *ssl,
  8592.                            const unsigned char *buf, size_t len )
  8593. {
  8594.     int ret = mbedtls_ssl_get_max_out_record_payload( ssl );
  8595.     const size_t max_len = (size_t) ret;
  8596.  
  8597.     if( ret < 0 )
  8598.     {
  8599.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_get_max_out_record_payload", ret );
  8600.         return( ret );
  8601.     }
  8602.  
  8603.     if( len > max_len )
  8604.     {
  8605. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  8606.         if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  8607.         {
  8608.             MBEDTLS_SSL_DEBUG_MSG( 1, ( "fragment larger than the (negotiated) "
  8609.                                 "maximum fragment length: %d > %d",
  8610.                                 len, max_len ) );
  8611.             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  8612.         }
  8613.         else
  8614. #endif
  8615.             len = max_len;
  8616.     }
  8617.  
  8618.     if( ssl->out_left != 0 )
  8619.     {
  8620.         /*
  8621.          * The user has previously tried to send the data and
  8622.          * MBEDTLS_ERR_SSL_WANT_WRITE or the message was only partially
  8623.          * written. In this case, we expect the high-level write function
  8624.          * (e.g. mbedtls_ssl_write()) to be called with the same parameters
  8625.          */
  8626.         if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
  8627.         {
  8628.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flush_output", ret );
  8629.             return( ret );
  8630.         }
  8631.     }
  8632.     else
  8633.     {
  8634.         /*
  8635.          * The user is trying to send a message the first time, so we need to
  8636.          * copy the data into the internal buffers and setup the data structure
  8637.          * to keep track of partial writes
  8638.          */
  8639.         ssl->out_msglen  = len;
  8640.         ssl->out_msgtype = MBEDTLS_SSL_MSG_APPLICATION_DATA;
  8641.         memcpy( ssl->out_msg, buf, len );
  8642.  
  8643.         if( ( ret = mbedtls_ssl_write_record( ssl, SSL_FORCE_FLUSH ) ) != 0 )
  8644.         {
  8645.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
  8646.             return( ret );
  8647.         }
  8648.     }
  8649.  
  8650.     return( (int) len );
  8651. }
  8652.  
  8653. /*
  8654.  * Write application data, doing 1/n-1 splitting if necessary.
  8655.  *
  8656.  * With non-blocking I/O, ssl_write_real() may return WANT_WRITE,
  8657.  * then the caller will call us again with the same arguments, so
  8658.  * remember whether we already did the split or not.
  8659.  */
  8660. #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
  8661. static int ssl_write_split( mbedtls_ssl_context *ssl,
  8662.                             const unsigned char *buf, size_t len )
  8663. {
  8664.     int ret;
  8665.  
  8666.     if( ssl->conf->cbc_record_splitting ==
  8667.             MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED ||
  8668.         len <= 1 ||
  8669.         ssl->minor_ver > MBEDTLS_SSL_MINOR_VERSION_1 ||
  8670.         mbedtls_cipher_get_cipher_mode( &ssl->transform_out->cipher_ctx_enc )
  8671.                                 != MBEDTLS_MODE_CBC )
  8672.     {
  8673.         return( ssl_write_real( ssl, buf, len ) );
  8674.     }
  8675.  
  8676.     if( ssl->split_done == 0 )
  8677.     {
  8678.         if( ( ret = ssl_write_real( ssl, buf, 1 ) ) <= 0 )
  8679.             return( ret );
  8680.         ssl->split_done = 1;
  8681.     }
  8682.  
  8683.     if( ( ret = ssl_write_real( ssl, buf + 1, len - 1 ) ) <= 0 )
  8684.         return( ret );
  8685.     ssl->split_done = 0;
  8686.  
  8687.     return( ret + 1 );
  8688. }
  8689. #endif /* MBEDTLS_SSL_CBC_RECORD_SPLITTING */
  8690.  
  8691. /*
  8692.  * Write application data (public-facing wrapper)
  8693.  */
  8694. int mbedtls_ssl_write( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len )
  8695. {
  8696.     int ret;
  8697.  
  8698.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write" ) );
  8699.  
  8700.     if( ssl == NULL || ssl->conf == NULL )
  8701.         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  8702.  
  8703. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  8704.     if( ( ret = ssl_check_ctr_renegotiate( ssl ) ) != 0 )
  8705.     {
  8706.         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_check_ctr_renegotiate", ret );
  8707.         return( ret );
  8708.     }
  8709. #endif
  8710.  
  8711.     if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
  8712.     {
  8713.         if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 )
  8714.         {
  8715.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
  8716.             return( ret );
  8717.         }
  8718.     }
  8719.  
  8720. #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
  8721.     ret = ssl_write_split( ssl, buf, len );
  8722. #else
  8723.     ret = ssl_write_real( ssl, buf, len );
  8724. #endif
  8725.  
  8726.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write" ) );
  8727.  
  8728.     return( ret );
  8729. }
  8730.  
  8731. /*
  8732.  * Notify the peer that the connection is being closed
  8733.  */
  8734. int mbedtls_ssl_close_notify( mbedtls_ssl_context *ssl )
  8735. {
  8736.     int ret;
  8737.  
  8738.     if( ssl == NULL || ssl->conf == NULL )
  8739.         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
  8740.  
  8741.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write close notify" ) );
  8742.  
  8743.     if( ssl->out_left != 0 )
  8744.         return( mbedtls_ssl_flush_output( ssl ) );
  8745.  
  8746.     if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )
  8747.     {
  8748.         if( ( ret = mbedtls_ssl_send_alert_message( ssl,
  8749.                         MBEDTLS_SSL_ALERT_LEVEL_WARNING,
  8750.                         MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY ) ) != 0 )
  8751.         {
  8752.             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_send_alert_message", ret );
  8753.             return( ret );
  8754.         }
  8755.     }
  8756.  
  8757.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write close notify" ) );
  8758.  
  8759.     return( 0 );
  8760. }
  8761.  
  8762. void mbedtls_ssl_transform_free( mbedtls_ssl_transform *transform )
  8763. {
  8764.     if( transform == NULL )
  8765.         return;
  8766.  
  8767. #if defined(MBEDTLS_ZLIB_SUPPORT)
  8768.     deflateEnd( &transform->ctx_deflate );
  8769.     inflateEnd( &transform->ctx_inflate );
  8770. #endif
  8771.  
  8772.     mbedtls_cipher_free( &transform->cipher_ctx_enc );
  8773.     mbedtls_cipher_free( &transform->cipher_ctx_dec );
  8774.  
  8775.     mbedtls_md_free( &transform->md_ctx_enc );
  8776.     mbedtls_md_free( &transform->md_ctx_dec );
  8777.  
  8778.     mbedtls_platform_zeroize( transform, sizeof( mbedtls_ssl_transform ) );
  8779. }
  8780.  
  8781. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  8782. static void ssl_key_cert_free( mbedtls_ssl_key_cert *key_cert )
  8783. {
  8784.     mbedtls_ssl_key_cert *cur = key_cert, *next;
  8785.  
  8786.     while( cur != NULL )
  8787.     {
  8788.         next = cur->next;
  8789.         mbedtls_free( cur );
  8790.         cur = next;
  8791.     }
  8792. }
  8793. #endif /* MBEDTLS_X509_CRT_PARSE_C */
  8794.  
  8795. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  8796.  
  8797. static void ssl_buffering_free( mbedtls_ssl_context *ssl )
  8798. {
  8799.     unsigned offset;
  8800.     mbedtls_ssl_handshake_params * const hs = ssl->handshake;
  8801.  
  8802.     if( hs == NULL )
  8803.         return;
  8804.  
  8805.     ssl_free_buffered_record( ssl );
  8806.  
  8807.     for( offset = 0; offset < MBEDTLS_SSL_MAX_BUFFERED_HS; offset++ )
  8808.         ssl_buffering_free_slot( ssl, offset );
  8809. }
  8810.  
  8811. static void ssl_buffering_free_slot( mbedtls_ssl_context *ssl,
  8812.                                      uint8_t slot )
  8813. {
  8814.     mbedtls_ssl_handshake_params * const hs = ssl->handshake;
  8815.     mbedtls_ssl_hs_buffer * const hs_buf = &hs->buffering.hs[slot];
  8816.  
  8817.     if( slot >= MBEDTLS_SSL_MAX_BUFFERED_HS )
  8818.         return;
  8819.  
  8820.     if( hs_buf->is_valid == 1 )
  8821.     {
  8822.         hs->buffering.total_bytes_buffered -= hs_buf->data_len;
  8823.         mbedtls_platform_zeroize( hs_buf->data, hs_buf->data_len );
  8824.         mbedtls_free( hs_buf->data );
  8825.         memset( hs_buf, 0, sizeof( mbedtls_ssl_hs_buffer ) );
  8826.     }
  8827. }
  8828.  
  8829. #endif /* MBEDTLS_SSL_PROTO_DTLS */
  8830.  
  8831. void mbedtls_ssl_handshake_free( mbedtls_ssl_context *ssl )
  8832. {
  8833.     mbedtls_ssl_handshake_params *handshake = ssl->handshake;
  8834.  
  8835.     if( handshake == NULL )
  8836.         return;
  8837.  
  8838. #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
  8839.     if( ssl->conf->f_async_cancel != NULL && handshake->async_in_progress != 0 )
  8840.     {
  8841.         ssl->conf->f_async_cancel( ssl );
  8842.         handshake->async_in_progress = 0;
  8843.     }
  8844. #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
  8845.  
  8846. #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
  8847.     defined(MBEDTLS_SSL_PROTO_TLS1_1)
  8848.     mbedtls_md5_free(    &handshake->fin_md5  );
  8849.     mbedtls_sha1_free(   &handshake->fin_sha1 );
  8850. #endif
  8851. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  8852. #if defined(MBEDTLS_SHA256_C)
  8853.     mbedtls_sha256_free(   &handshake->fin_sha256    );
  8854. #endif
  8855. #if defined(MBEDTLS_SHA512_C)
  8856.     mbedtls_sha512_free(   &handshake->fin_sha512    );
  8857. #endif
  8858. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  8859.  
  8860. #if defined(MBEDTLS_DHM_C)
  8861.     mbedtls_dhm_free( &handshake->dhm_ctx );
  8862. #endif
  8863. #if defined(MBEDTLS_ECDH_C)
  8864.     mbedtls_ecdh_free( &handshake->ecdh_ctx );
  8865. #endif
  8866. #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
  8867.     mbedtls_ecjpake_free( &handshake->ecjpake_ctx );
  8868. #if defined(MBEDTLS_SSL_CLI_C)
  8869.     mbedtls_free( handshake->ecjpake_cache );
  8870.     handshake->ecjpake_cache = NULL;
  8871.     handshake->ecjpake_cache_len = 0;
  8872. #endif
  8873. #endif
  8874.  
  8875. #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
  8876.     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
  8877.     /* explicit void pointer cast for buggy MS compiler */
  8878.     mbedtls_free( (void *) handshake->curves );
  8879. #endif
  8880.  
  8881. #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
  8882.     if( handshake->psk != NULL )
  8883.     {
  8884.         mbedtls_platform_zeroize( handshake->psk, handshake->psk_len );
  8885.         mbedtls_free( handshake->psk );
  8886.     }
  8887. #endif
  8888.  
  8889. #if defined(MBEDTLS_X509_CRT_PARSE_C) && \
  8890.     defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
  8891.     /*
  8892.      * Free only the linked list wrapper, not the keys themselves
  8893.      * since the belong to the SNI callback
  8894.      */
  8895.     if( handshake->sni_key_cert != NULL )
  8896.     {
  8897.         mbedtls_ssl_key_cert *cur = handshake->sni_key_cert, *next;
  8898.  
  8899.         while( cur != NULL )
  8900.         {
  8901.             next = cur->next;
  8902.             mbedtls_free( cur );
  8903.             cur = next;
  8904.         }
  8905.     }
  8906. #endif /* MBEDTLS_X509_CRT_PARSE_C && MBEDTLS_SSL_SERVER_NAME_INDICATION */
  8907.  
  8908. #if defined(MBEDTLS_SSL__ECP_RESTARTABLE)
  8909.     mbedtls_x509_crt_restart_free( &handshake->ecrs_ctx );
  8910. #endif
  8911.  
  8912. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  8913.     mbedtls_free( handshake->verify_cookie );
  8914.     ssl_flight_free( handshake->flight );
  8915.     ssl_buffering_free( ssl );
  8916. #endif
  8917.  
  8918.     mbedtls_platform_zeroize( handshake,
  8919.                               sizeof( mbedtls_ssl_handshake_params ) );
  8920. }
  8921.  
  8922. void mbedtls_ssl_session_free( mbedtls_ssl_session *session )
  8923. {
  8924.     if( session == NULL )
  8925.         return;
  8926.  
  8927. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  8928.     if( session->peer_cert != NULL )
  8929.     {
  8930.         mbedtls_x509_crt_free( session->peer_cert );
  8931.         mbedtls_free( session->peer_cert );
  8932.     }
  8933. #endif
  8934.  
  8935. #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
  8936.     mbedtls_free( session->ticket );
  8937. #endif
  8938.  
  8939.     mbedtls_platform_zeroize( session, sizeof( mbedtls_ssl_session ) );
  8940. }
  8941.  
  8942. /*
  8943.  * Free an SSL context
  8944.  */
  8945. void mbedtls_ssl_free( mbedtls_ssl_context *ssl )
  8946. {
  8947.     if( ssl == NULL )
  8948.         return;
  8949.  
  8950.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> free" ) );
  8951.  
  8952.     if( ssl->out_buf != NULL )
  8953.     {
  8954.         mbedtls_platform_zeroize( ssl->out_buf, MBEDTLS_SSL_OUT_BUFFER_LEN );
  8955.         mbedtls_free( ssl->out_buf );
  8956.     }
  8957.  
  8958.     if( ssl->in_buf != NULL )
  8959.     {
  8960.         mbedtls_platform_zeroize( ssl->in_buf, MBEDTLS_SSL_IN_BUFFER_LEN );
  8961.         mbedtls_free( ssl->in_buf );
  8962.     }
  8963.  
  8964. #if defined(MBEDTLS_ZLIB_SUPPORT)
  8965.     if( ssl->compress_buf != NULL )
  8966.     {
  8967.         mbedtls_platform_zeroize( ssl->compress_buf, MBEDTLS_SSL_COMPRESS_BUFFER_LEN );
  8968.         mbedtls_free( ssl->compress_buf );
  8969.     }
  8970. #endif
  8971.  
  8972.     if( ssl->transform )
  8973.     {
  8974.         mbedtls_ssl_transform_free( ssl->transform );
  8975.         mbedtls_free( ssl->transform );
  8976.     }
  8977.  
  8978.     if( ssl->handshake )
  8979.     {
  8980.         mbedtls_ssl_handshake_free( ssl );
  8981.         mbedtls_ssl_transform_free( ssl->transform_negotiate );
  8982.         mbedtls_ssl_session_free( ssl->session_negotiate );
  8983.  
  8984.         mbedtls_free( ssl->handshake );
  8985.         mbedtls_free( ssl->transform_negotiate );
  8986.         mbedtls_free( ssl->session_negotiate );
  8987.     }
  8988.  
  8989.     if( ssl->session )
  8990.     {
  8991.         mbedtls_ssl_session_free( ssl->session );
  8992.         mbedtls_free( ssl->session );
  8993.     }
  8994.  
  8995. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  8996.     if( ssl->hostname != NULL )
  8997.     {
  8998.         mbedtls_platform_zeroize( ssl->hostname, strlen( ssl->hostname ) );
  8999.         mbedtls_free( ssl->hostname );
  9000.     }
  9001. #endif
  9002.  
  9003. #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
  9004.     if( mbedtls_ssl_hw_record_finish != NULL )
  9005.     {
  9006.         MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_finish()" ) );
  9007.         mbedtls_ssl_hw_record_finish( ssl );
  9008.     }
  9009. #endif
  9010.  
  9011. #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
  9012.     mbedtls_free( ssl->cli_id );
  9013. #endif
  9014.  
  9015.     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= free" ) );
  9016.  
  9017.     /* Actually clear after last debug message */
  9018.     mbedtls_platform_zeroize( ssl, sizeof( mbedtls_ssl_context ) );
  9019. }
  9020.  
  9021. /*
  9022.  * Initialze mbedtls_ssl_config
  9023.  */
  9024. void mbedtls_ssl_config_init( mbedtls_ssl_config *conf )
  9025. {
  9026.     memset( conf, 0, sizeof( mbedtls_ssl_config ) );
  9027. }
  9028.  
  9029. #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
  9030. static int ssl_preset_default_hashes[] = {
  9031. #if defined(MBEDTLS_SHA512_C)
  9032.     MBEDTLS_MD_SHA512,
  9033.     MBEDTLS_MD_SHA384,
  9034. #endif
  9035. #if defined(MBEDTLS_SHA256_C)
  9036.     MBEDTLS_MD_SHA256,
  9037.     MBEDTLS_MD_SHA224,
  9038. #endif
  9039. #if defined(MBEDTLS_SHA1_C) && defined(MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_KEY_EXCHANGE)
  9040.     MBEDTLS_MD_SHA1,
  9041. #endif
  9042.     MBEDTLS_MD_NONE
  9043. };
  9044. #endif
  9045.  
  9046. static int ssl_preset_suiteb_ciphersuites[] = {
  9047.     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  9048.     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  9049.     0
  9050. };
  9051.  
  9052. #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
  9053. static int ssl_preset_suiteb_hashes[] = {
  9054.     MBEDTLS_MD_SHA256,
  9055.     MBEDTLS_MD_SHA384,
  9056.     MBEDTLS_MD_NONE
  9057. };
  9058. #endif
  9059.  
  9060. #if defined(MBEDTLS_ECP_C)
  9061. static mbedtls_ecp_group_id ssl_preset_suiteb_curves[] = {
  9062. #if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED)
  9063.     MBEDTLS_ECP_DP_SECP256R1,
  9064. #endif
  9065. #if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)
  9066.     MBEDTLS_ECP_DP_SECP384R1,
  9067. #endif
  9068.     MBEDTLS_ECP_DP_NONE
  9069. };
  9070. #endif
  9071.  
  9072. /*
  9073.  * Load default in mbedtls_ssl_config
  9074.  */
  9075. int mbedtls_ssl_config_defaults( mbedtls_ssl_config *conf,
  9076.                                  int endpoint, int transport, int preset )
  9077. {
  9078. #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
  9079.     int ret;
  9080. #endif
  9081.  
  9082.     /* Use the functions here so that they are covered in tests,
  9083.      * but otherwise access member directly for efficiency */
  9084.     mbedtls_ssl_conf_endpoint( conf, endpoint );
  9085.     mbedtls_ssl_conf_transport( conf, transport );
  9086.  
  9087.     /*
  9088.      * Things that are common to all presets
  9089.      */
  9090. #if defined(MBEDTLS_SSL_CLI_C)
  9091.     if( endpoint == MBEDTLS_SSL_IS_CLIENT )
  9092.     {
  9093.         conf->authmode = MBEDTLS_SSL_VERIFY_REQUIRED;
  9094. #if defined(MBEDTLS_SSL_SESSION_TICKETS)
  9095.         conf->session_tickets = MBEDTLS_SSL_SESSION_TICKETS_ENABLED;
  9096. #endif
  9097.     }
  9098. #endif
  9099.  
  9100. #if defined(MBEDTLS_ARC4_C)
  9101.     conf->arc4_disabled = MBEDTLS_SSL_ARC4_DISABLED;
  9102. #endif
  9103.  
  9104. #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
  9105.     conf->encrypt_then_mac = MBEDTLS_SSL_ETM_ENABLED;
  9106. #endif
  9107.  
  9108. #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
  9109.     conf->extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED;
  9110. #endif
  9111.  
  9112. #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
  9113.     conf->cbc_record_splitting = MBEDTLS_SSL_CBC_RECORD_SPLITTING_ENABLED;
  9114. #endif
  9115.  
  9116. #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
  9117.     conf->f_cookie_write = ssl_cookie_write_dummy;
  9118.     conf->f_cookie_check = ssl_cookie_check_dummy;
  9119. #endif
  9120.  
  9121. #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
  9122.     conf->anti_replay = MBEDTLS_SSL_ANTI_REPLAY_ENABLED;
  9123. #endif
  9124.  
  9125. #if defined(MBEDTLS_SSL_SRV_C)
  9126.     conf->cert_req_ca_list = MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED;
  9127. #endif
  9128.  
  9129. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  9130.     conf->hs_timeout_min = MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MIN;
  9131.     conf->hs_timeout_max = MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MAX;
  9132. #endif
  9133.  
  9134. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  9135.     conf->renego_max_records = MBEDTLS_SSL_RENEGO_MAX_RECORDS_DEFAULT;
  9136.     memset( conf->renego_period,     0x00, 2 );
  9137.     memset( conf->renego_period + 2, 0xFF, 6 );
  9138. #endif
  9139.  
  9140. #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
  9141.             if( endpoint == MBEDTLS_SSL_IS_SERVER )
  9142.             {
  9143.                 const unsigned char dhm_p[] =
  9144.                     MBEDTLS_DHM_RFC3526_MODP_2048_P_BIN;
  9145.                 const unsigned char dhm_g[] =
  9146.                     MBEDTLS_DHM_RFC3526_MODP_2048_G_BIN;
  9147.  
  9148.                 if ( ( ret = mbedtls_ssl_conf_dh_param_bin( conf,
  9149.                                                dhm_p, sizeof( dhm_p ),
  9150.                                                dhm_g, sizeof( dhm_g ) ) ) != 0 )
  9151.                 {
  9152.                     return( ret );
  9153.                 }
  9154.             }
  9155. #endif
  9156.  
  9157.     /*
  9158.      * Preset-specific defaults
  9159.      */
  9160.     switch( preset )
  9161.     {
  9162.         /*
  9163.          * NSA Suite B
  9164.          */
  9165.         case MBEDTLS_SSL_PRESET_SUITEB:
  9166.             conf->min_major_ver = MBEDTLS_SSL_MAJOR_VERSION_3;
  9167.             conf->min_minor_ver = MBEDTLS_SSL_MINOR_VERSION_3; /* TLS 1.2 */
  9168.             conf->max_major_ver = MBEDTLS_SSL_MAX_MAJOR_VERSION;
  9169.             conf->max_minor_ver = MBEDTLS_SSL_MAX_MINOR_VERSION;
  9170.  
  9171.             conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] =
  9172.             conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] =
  9173.             conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] =
  9174.             conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] =
  9175.                                    ssl_preset_suiteb_ciphersuites;
  9176.  
  9177. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  9178.             conf->cert_profile = &mbedtls_x509_crt_profile_suiteb;
  9179. #endif
  9180.  
  9181. #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
  9182.             conf->sig_hashes = ssl_preset_suiteb_hashes;
  9183. #endif
  9184.  
  9185. #if defined(MBEDTLS_ECP_C)
  9186.             conf->curve_list = ssl_preset_suiteb_curves;
  9187. #endif
  9188.             break;
  9189.  
  9190.         /*
  9191.          * Default
  9192.          */
  9193.         default:
  9194.             conf->min_major_ver = ( MBEDTLS_SSL_MIN_MAJOR_VERSION >
  9195.                                     MBEDTLS_SSL_MIN_VALID_MAJOR_VERSION ) ?
  9196.                                     MBEDTLS_SSL_MIN_MAJOR_VERSION :
  9197.                                     MBEDTLS_SSL_MIN_VALID_MAJOR_VERSION;
  9198.             conf->min_minor_ver = ( MBEDTLS_SSL_MIN_MINOR_VERSION >
  9199.                                     MBEDTLS_SSL_MIN_VALID_MINOR_VERSION ) ?
  9200.                                     MBEDTLS_SSL_MIN_MINOR_VERSION :
  9201.                                     MBEDTLS_SSL_MIN_VALID_MINOR_VERSION;
  9202.             conf->max_major_ver = MBEDTLS_SSL_MAX_MAJOR_VERSION;
  9203.             conf->max_minor_ver = MBEDTLS_SSL_MAX_MINOR_VERSION;
  9204.  
  9205. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  9206.             if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  9207.                 conf->min_minor_ver = MBEDTLS_SSL_MINOR_VERSION_2;
  9208. #endif
  9209.  
  9210.             conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] =
  9211.             conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] =
  9212.             conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] =
  9213.             conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] =
  9214.                                    mbedtls_ssl_list_ciphersuites();
  9215.  
  9216. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  9217.             conf->cert_profile = &mbedtls_x509_crt_profile_default;
  9218. #endif
  9219.  
  9220. #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
  9221.             conf->sig_hashes = ssl_preset_default_hashes;
  9222. #endif
  9223.  
  9224. #if defined(MBEDTLS_ECP_C)
  9225.             conf->curve_list = mbedtls_ecp_grp_id_list();
  9226. #endif
  9227.  
  9228. #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C)
  9229.             conf->dhm_min_bitlen = 1024;
  9230. #endif
  9231.     }
  9232.  
  9233.     return( 0 );
  9234. }
  9235.  
  9236. /*
  9237.  * Free mbedtls_ssl_config
  9238.  */
  9239. void mbedtls_ssl_config_free( mbedtls_ssl_config *conf )
  9240. {
  9241. #if defined(MBEDTLS_DHM_C)
  9242.     mbedtls_mpi_free( &conf->dhm_P );
  9243.     mbedtls_mpi_free( &conf->dhm_G );
  9244. #endif
  9245.  
  9246. #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
  9247.     if( conf->psk != NULL )
  9248.     {
  9249.         mbedtls_platform_zeroize( conf->psk, conf->psk_len );
  9250.         mbedtls_free( conf->psk );
  9251.         conf->psk = NULL;
  9252.         conf->psk_len = 0;
  9253.     }
  9254.  
  9255.     if( conf->psk_identity != NULL )
  9256.     {
  9257.         mbedtls_platform_zeroize( conf->psk_identity, conf->psk_identity_len );
  9258.         mbedtls_free( conf->psk_identity );
  9259.         conf->psk_identity = NULL;
  9260.         conf->psk_identity_len = 0;
  9261.     }
  9262. #endif
  9263.  
  9264. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  9265.     ssl_key_cert_free( conf->key_cert );
  9266. #endif
  9267.  
  9268.     mbedtls_platform_zeroize( conf, sizeof( mbedtls_ssl_config ) );
  9269. }
  9270.  
  9271. #if defined(MBEDTLS_PK_C) && \
  9272.     ( defined(MBEDTLS_RSA_C) || defined(MBEDTLS_ECDSA_C) )
  9273. /*
  9274.  * Convert between MBEDTLS_PK_XXX and SSL_SIG_XXX
  9275.  */
  9276. unsigned char mbedtls_ssl_sig_from_pk( mbedtls_pk_context *pk )
  9277. {
  9278. #if defined(MBEDTLS_RSA_C)
  9279.     if( mbedtls_pk_can_do( pk, MBEDTLS_PK_RSA ) )
  9280.         return( MBEDTLS_SSL_SIG_RSA );
  9281. #endif
  9282. #if defined(MBEDTLS_ECDSA_C)
  9283.     if( mbedtls_pk_can_do( pk, MBEDTLS_PK_ECDSA ) )
  9284.         return( MBEDTLS_SSL_SIG_ECDSA );
  9285. #endif
  9286.     return( MBEDTLS_SSL_SIG_ANON );
  9287. }
  9288.  
  9289. unsigned char mbedtls_ssl_sig_from_pk_alg( mbedtls_pk_type_t type )
  9290. {
  9291.     switch( type ) {
  9292.         case MBEDTLS_PK_RSA:
  9293.             return( MBEDTLS_SSL_SIG_RSA );
  9294.         case MBEDTLS_PK_ECDSA:
  9295.         case MBEDTLS_PK_ECKEY:
  9296.             return( MBEDTLS_SSL_SIG_ECDSA );
  9297.         default:
  9298.             return( MBEDTLS_SSL_SIG_ANON );
  9299.     }
  9300. }
  9301.  
  9302. mbedtls_pk_type_t mbedtls_ssl_pk_alg_from_sig( unsigned char sig )
  9303. {
  9304.     switch( sig )
  9305.     {
  9306. #if defined(MBEDTLS_RSA_C)
  9307.         case MBEDTLS_SSL_SIG_RSA:
  9308.             return( MBEDTLS_PK_RSA );
  9309. #endif
  9310. #if defined(MBEDTLS_ECDSA_C)
  9311.         case MBEDTLS_SSL_SIG_ECDSA:
  9312.             return( MBEDTLS_PK_ECDSA );
  9313. #endif
  9314.         default:
  9315.             return( MBEDTLS_PK_NONE );
  9316.     }
  9317. }
  9318. #endif /* MBEDTLS_PK_C && ( MBEDTLS_RSA_C || MBEDTLS_ECDSA_C ) */
  9319.  
  9320. #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
  9321.     defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
  9322.  
  9323. /* Find an entry in a signature-hash set matching a given hash algorithm. */
  9324. mbedtls_md_type_t mbedtls_ssl_sig_hash_set_find( mbedtls_ssl_sig_hash_set_t *set,
  9325.                                                  mbedtls_pk_type_t sig_alg )
  9326. {
  9327.     switch( sig_alg )
  9328.     {
  9329.         case MBEDTLS_PK_RSA:
  9330.             return( set->rsa );
  9331.         case MBEDTLS_PK_ECDSA:
  9332.             return( set->ecdsa );
  9333.         default:
  9334.             return( MBEDTLS_MD_NONE );
  9335.     }
  9336. }
  9337.  
  9338. /* Add a signature-hash-pair to a signature-hash set */
  9339. void mbedtls_ssl_sig_hash_set_add( mbedtls_ssl_sig_hash_set_t *set,
  9340.                                    mbedtls_pk_type_t sig_alg,
  9341.                                    mbedtls_md_type_t md_alg )
  9342. {
  9343.     switch( sig_alg )
  9344.     {
  9345.         case MBEDTLS_PK_RSA:
  9346.             if( set->rsa == MBEDTLS_MD_NONE )
  9347.                 set->rsa = md_alg;
  9348.             break;
  9349.  
  9350.         case MBEDTLS_PK_ECDSA:
  9351.             if( set->ecdsa == MBEDTLS_MD_NONE )
  9352.                 set->ecdsa = md_alg;
  9353.             break;
  9354.  
  9355.         default:
  9356.             break;
  9357.     }
  9358. }
  9359.  
  9360. /* Allow exactly one hash algorithm for each signature. */
  9361. void mbedtls_ssl_sig_hash_set_const_hash( mbedtls_ssl_sig_hash_set_t *set,
  9362.                                           mbedtls_md_type_t md_alg )
  9363. {
  9364.     set->rsa   = md_alg;
  9365.     set->ecdsa = md_alg;
  9366. }
  9367.  
  9368. #endif /* MBEDTLS_SSL_PROTO_TLS1_2) &&
  9369.           MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
  9370.  
  9371. /*
  9372.  * Convert from MBEDTLS_SSL_HASH_XXX to MBEDTLS_MD_XXX
  9373.  */
  9374. mbedtls_md_type_t mbedtls_ssl_md_alg_from_hash( unsigned char hash )
  9375. {
  9376.     switch( hash )
  9377.     {
  9378. #if defined(MBEDTLS_MD5_C)
  9379.         case MBEDTLS_SSL_HASH_MD5:
  9380.             return( MBEDTLS_MD_MD5 );
  9381. #endif
  9382. #if defined(MBEDTLS_SHA1_C)
  9383.         case MBEDTLS_SSL_HASH_SHA1:
  9384.             return( MBEDTLS_MD_SHA1 );
  9385. #endif
  9386. #if defined(MBEDTLS_SHA256_C)
  9387.         case MBEDTLS_SSL_HASH_SHA224:
  9388.             return( MBEDTLS_MD_SHA224 );
  9389.         case MBEDTLS_SSL_HASH_SHA256:
  9390.             return( MBEDTLS_MD_SHA256 );
  9391. #endif
  9392. #if defined(MBEDTLS_SHA512_C)
  9393.         case MBEDTLS_SSL_HASH_SHA384:
  9394.             return( MBEDTLS_MD_SHA384 );
  9395.         case MBEDTLS_SSL_HASH_SHA512:
  9396.             return( MBEDTLS_MD_SHA512 );
  9397. #endif
  9398.         default:
  9399.             return( MBEDTLS_MD_NONE );
  9400.     }
  9401. }
  9402.  
  9403. /*
  9404.  * Convert from MBEDTLS_MD_XXX to MBEDTLS_SSL_HASH_XXX
  9405.  */
  9406. unsigned char mbedtls_ssl_hash_from_md_alg( int md )
  9407. {
  9408.     switch( md )
  9409.     {
  9410. #if defined(MBEDTLS_MD5_C)
  9411.         case MBEDTLS_MD_MD5:
  9412.             return( MBEDTLS_SSL_HASH_MD5 );
  9413. #endif
  9414. #if defined(MBEDTLS_SHA1_C)
  9415.         case MBEDTLS_MD_SHA1:
  9416.             return( MBEDTLS_SSL_HASH_SHA1 );
  9417. #endif
  9418. #if defined(MBEDTLS_SHA256_C)
  9419.         case MBEDTLS_MD_SHA224:
  9420.             return( MBEDTLS_SSL_HASH_SHA224 );
  9421.         case MBEDTLS_MD_SHA256:
  9422.             return( MBEDTLS_SSL_HASH_SHA256 );
  9423. #endif
  9424. #if defined(MBEDTLS_SHA512_C)
  9425.         case MBEDTLS_MD_SHA384:
  9426.             return( MBEDTLS_SSL_HASH_SHA384 );
  9427.         case MBEDTLS_MD_SHA512:
  9428.             return( MBEDTLS_SSL_HASH_SHA512 );
  9429. #endif
  9430.         default:
  9431.             return( MBEDTLS_SSL_HASH_NONE );
  9432.     }
  9433. }
  9434.  
  9435. #if defined(MBEDTLS_ECP_C)
  9436. /*
  9437.  * Check if a curve proposed by the peer is in our list.
  9438.  * Return 0 if we're willing to use it, -1 otherwise.
  9439.  */
  9440. int mbedtls_ssl_check_curve( const mbedtls_ssl_context *ssl, mbedtls_ecp_group_id grp_id )
  9441. {
  9442.     const mbedtls_ecp_group_id *gid;
  9443.  
  9444.     if( ssl->conf->curve_list == NULL )
  9445.         return( -1 );
  9446.  
  9447.     for( gid = ssl->conf->curve_list; *gid != MBEDTLS_ECP_DP_NONE; gid++ )
  9448.         if( *gid == grp_id )
  9449.             return( 0 );
  9450.  
  9451.     return( -1 );
  9452. }
  9453. #endif /* MBEDTLS_ECP_C */
  9454.  
  9455. #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
  9456. /*
  9457.  * Check if a hash proposed by the peer is in our list.
  9458.  * Return 0 if we're willing to use it, -1 otherwise.
  9459.  */
  9460. int mbedtls_ssl_check_sig_hash( const mbedtls_ssl_context *ssl,
  9461.                                 mbedtls_md_type_t md )
  9462. {
  9463.     const int *cur;
  9464.  
  9465.     if( ssl->conf->sig_hashes == NULL )
  9466.         return( -1 );
  9467.  
  9468.     for( cur = ssl->conf->sig_hashes; *cur != MBEDTLS_MD_NONE; cur++ )
  9469.         if( *cur == (int) md )
  9470.             return( 0 );
  9471.  
  9472.     return( -1 );
  9473. }
  9474. #endif /* MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
  9475.  
  9476. #if defined(MBEDTLS_X509_CRT_PARSE_C)
  9477. int mbedtls_ssl_check_cert_usage( const mbedtls_x509_crt *cert,
  9478.                           const mbedtls_ssl_ciphersuite_t *ciphersuite,
  9479.                           int cert_endpoint,
  9480.                           uint32_t *flags )
  9481. {
  9482.     int ret = 0;
  9483. #if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
  9484.     int usage = 0;
  9485. #endif
  9486. #if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
  9487.     const char *ext_oid;
  9488.     size_t ext_len;
  9489. #endif
  9490.  
  9491. #if !defined(MBEDTLS_X509_CHECK_KEY_USAGE) &&          \
  9492.     !defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
  9493.     ((void) cert);
  9494.     ((void) cert_endpoint);
  9495.     ((void) flags);
  9496. #endif
  9497.  
  9498. #if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
  9499.     if( cert_endpoint == MBEDTLS_SSL_IS_SERVER )
  9500.     {
  9501.         /* Server part of the key exchange */
  9502.         switch( ciphersuite->key_exchange )
  9503.         {
  9504.             case MBEDTLS_KEY_EXCHANGE_RSA:
  9505.             case MBEDTLS_KEY_EXCHANGE_RSA_PSK:
  9506.                 usage = MBEDTLS_X509_KU_KEY_ENCIPHERMENT;
  9507.                 break;
  9508.  
  9509.             case MBEDTLS_KEY_EXCHANGE_DHE_RSA:
  9510.             case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
  9511.             case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
  9512.                 usage = MBEDTLS_X509_KU_DIGITAL_SIGNATURE;
  9513.                 break;
  9514.  
  9515.             case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:
  9516.             case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:
  9517.                 usage = MBEDTLS_X509_KU_KEY_AGREEMENT;
  9518.                 break;
  9519.  
  9520.             /* Don't use default: we want warnings when adding new values */
  9521.             case MBEDTLS_KEY_EXCHANGE_NONE:
  9522.             case MBEDTLS_KEY_EXCHANGE_PSK:
  9523.             case MBEDTLS_KEY_EXCHANGE_DHE_PSK:
  9524.             case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK:
  9525.             case MBEDTLS_KEY_EXCHANGE_ECJPAKE:
  9526.                 usage = 0;
  9527.         }
  9528.     }
  9529.     else
  9530.     {
  9531.         /* Client auth: we only implement rsa_sign and mbedtls_ecdsa_sign for now */
  9532.         usage = MBEDTLS_X509_KU_DIGITAL_SIGNATURE;
  9533.     }
  9534.  
  9535.     if( mbedtls_x509_crt_check_key_usage( cert, usage ) != 0 )
  9536.     {
  9537.         *flags |= MBEDTLS_X509_BADCERT_KEY_USAGE;
  9538.         ret = -1;
  9539.     }
  9540. #else
  9541.     ((void) ciphersuite);
  9542. #endif /* MBEDTLS_X509_CHECK_KEY_USAGE */
  9543.  
  9544. #if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
  9545.     if( cert_endpoint == MBEDTLS_SSL_IS_SERVER )
  9546.     {
  9547.         ext_oid = MBEDTLS_OID_SERVER_AUTH;
  9548.         ext_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_SERVER_AUTH );
  9549.     }
  9550.     else
  9551.     {
  9552.         ext_oid = MBEDTLS_OID_CLIENT_AUTH;
  9553.         ext_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_CLIENT_AUTH );
  9554.     }
  9555.  
  9556.     if( mbedtls_x509_crt_check_extended_key_usage( cert, ext_oid, ext_len ) != 0 )
  9557.     {
  9558.         *flags |= MBEDTLS_X509_BADCERT_EXT_KEY_USAGE;
  9559.         ret = -1;
  9560.     }
  9561. #endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE */
  9562.  
  9563.     return( ret );
  9564. }
  9565. #endif /* MBEDTLS_X509_CRT_PARSE_C */
  9566.  
  9567. /*
  9568.  * Convert version numbers to/from wire format
  9569.  * and, for DTLS, to/from TLS equivalent.
  9570.  *
  9571.  * For TLS this is the identity.
  9572.  * For DTLS, use 1's complement (v -> 255 - v, and then map as follows:
  9573.  * 1.0 <-> 3.2      (DTLS 1.0 is based on TLS 1.1)
  9574.  * 1.x <-> 3.x+1    for x != 0 (DTLS 1.2 based on TLS 1.2)
  9575.  */
  9576. void mbedtls_ssl_write_version( int major, int minor, int transport,
  9577.                         unsigned char ver[2] )
  9578. {
  9579. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  9580.     if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  9581.     {
  9582.         if( minor == MBEDTLS_SSL_MINOR_VERSION_2 )
  9583.             --minor; /* DTLS 1.0 stored as TLS 1.1 internally */
  9584.  
  9585.         ver[0] = (unsigned char)( 255 - ( major - 2 ) );
  9586.         ver[1] = (unsigned char)( 255 - ( minor - 1 ) );
  9587.     }
  9588.     else
  9589. #else
  9590.     ((void) transport);
  9591. #endif
  9592.     {
  9593.         ver[0] = (unsigned char) major;
  9594.         ver[1] = (unsigned char) minor;
  9595.     }
  9596. }
  9597.  
  9598. void mbedtls_ssl_read_version( int *major, int *minor, int transport,
  9599.                        const unsigned char ver[2] )
  9600. {
  9601. #if defined(MBEDTLS_SSL_PROTO_DTLS)
  9602.     if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
  9603.     {
  9604.         *major = 255 - ver[0] + 2;
  9605.         *minor = 255 - ver[1] + 1;
  9606.  
  9607.         if( *minor == MBEDTLS_SSL_MINOR_VERSION_1 )
  9608.             ++*minor; /* DTLS 1.0 stored as TLS 1.1 internally */
  9609.     }
  9610.     else
  9611. #else
  9612.     ((void) transport);
  9613. #endif
  9614.     {
  9615.         *major = ver[0];
  9616.         *minor = ver[1];
  9617.     }
  9618. }
  9619.  
  9620. int mbedtls_ssl_set_calc_verify_md( mbedtls_ssl_context *ssl, int md )
  9621. {
  9622. #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
  9623.     if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
  9624.         return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
  9625.  
  9626.     switch( md )
  9627.     {
  9628. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
  9629. #if defined(MBEDTLS_MD5_C)
  9630.         case MBEDTLS_SSL_HASH_MD5:
  9631.             return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
  9632. #endif
  9633. #if defined(MBEDTLS_SHA1_C)
  9634.         case MBEDTLS_SSL_HASH_SHA1:
  9635.             ssl->handshake->calc_verify = ssl_calc_verify_tls;
  9636.             break;
  9637. #endif
  9638. #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
  9639. #if defined(MBEDTLS_SHA512_C)
  9640.         case MBEDTLS_SSL_HASH_SHA384:
  9641.             ssl->handshake->calc_verify = ssl_calc_verify_tls_sha384;
  9642.             break;
  9643. #endif
  9644. #if defined(MBEDTLS_SHA256_C)
  9645.         case MBEDTLS_SSL_HASH_SHA256:
  9646.             ssl->handshake->calc_verify = ssl_calc_verify_tls_sha256;
  9647.             break;
  9648. #endif
  9649.         default:
  9650.             return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
  9651.     }
  9652.  
  9653.     return 0;
  9654. #else /* !MBEDTLS_SSL_PROTO_TLS1_2 */
  9655.     (void) ssl;
  9656.     (void) md;
  9657.  
  9658.     return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
  9659. #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
  9660. }
  9661.  
  9662. #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
  9663.     defined(MBEDTLS_SSL_PROTO_TLS1_1)
  9664. int mbedtls_ssl_get_key_exchange_md_ssl_tls( mbedtls_ssl_context *ssl,
  9665.                                         unsigned char *output,
  9666.                                         unsigned char *data, size_t data_len )
  9667. {
  9668.     int ret = 0;
  9669.     mbedtls_md5_context mbedtls_md5;
  9670.     mbedtls_sha1_context mbedtls_sha1;
  9671.  
  9672.     mbedtls_md5_init( &mbedtls_md5 );
  9673.     mbedtls_sha1_init( &mbedtls_sha1 );
  9674.  
  9675.     /*
  9676.      * digitally-signed struct {
  9677.      *     opaque md5_hash[16];
  9678.      *     opaque sha_hash[20];
  9679.      * };
  9680.      *
  9681.      * md5_hash
  9682.      *     MD5(ClientHello.random + ServerHello.random
  9683.      *                            + ServerParams);
  9684.      * sha_hash
  9685.      *     SHA(ClientHello.random + ServerHello.random
  9686.      *                            + ServerParams);
  9687.      */
  9688.     if( ( ret = mbedtls_md5_starts_ret( &mbedtls_md5 ) ) != 0 )
  9689.     {
  9690.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md5_starts_ret", ret );
  9691.         goto exit;
  9692.     }
  9693.     if( ( ret = mbedtls_md5_update_ret( &mbedtls_md5,
  9694.                                         ssl->handshake->randbytes, 64 ) ) != 0 )
  9695.     {
  9696.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md5_update_ret", ret );
  9697.         goto exit;
  9698.     }
  9699.     if( ( ret = mbedtls_md5_update_ret( &mbedtls_md5, data, data_len ) ) != 0 )
  9700.     {
  9701.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md5_update_ret", ret );
  9702.         goto exit;
  9703.     }
  9704.     if( ( ret = mbedtls_md5_finish_ret( &mbedtls_md5, output ) ) != 0 )
  9705.     {
  9706.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md5_finish_ret", ret );
  9707.         goto exit;
  9708.     }
  9709.  
  9710.     if( ( ret = mbedtls_sha1_starts_ret( &mbedtls_sha1 ) ) != 0 )
  9711.     {
  9712.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha1_starts_ret", ret );
  9713.         goto exit;
  9714.     }
  9715.     if( ( ret = mbedtls_sha1_update_ret( &mbedtls_sha1,
  9716.                                          ssl->handshake->randbytes, 64 ) ) != 0 )
  9717.     {
  9718.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha1_update_ret", ret );
  9719.         goto exit;
  9720.     }
  9721.     if( ( ret = mbedtls_sha1_update_ret( &mbedtls_sha1, data,
  9722.                                          data_len ) ) != 0 )
  9723.     {
  9724.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha1_update_ret", ret );
  9725.         goto exit;
  9726.     }
  9727.     if( ( ret = mbedtls_sha1_finish_ret( &mbedtls_sha1,
  9728.                                          output + 16 ) ) != 0 )
  9729.     {
  9730.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha1_finish_ret", ret );
  9731.         goto exit;
  9732.     }
  9733.  
  9734. exit:
  9735.     mbedtls_md5_free( &mbedtls_md5 );
  9736.     mbedtls_sha1_free( &mbedtls_sha1 );
  9737.  
  9738.     if( ret != 0 )
  9739.         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  9740.                                         MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
  9741.  
  9742.     return( ret );
  9743.  
  9744. }
  9745. #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
  9746.           MBEDTLS_SSL_PROTO_TLS1_1 */
  9747.  
  9748. #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
  9749.     defined(MBEDTLS_SSL_PROTO_TLS1_2)
  9750. int mbedtls_ssl_get_key_exchange_md_tls1_2( mbedtls_ssl_context *ssl,
  9751.                                             unsigned char *hash, size_t *hashlen,
  9752.                                             unsigned char *data, size_t data_len,
  9753.                                             mbedtls_md_type_t md_alg )
  9754. {
  9755.     int ret = 0;
  9756.     mbedtls_md_context_t ctx;
  9757.     const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type( md_alg );
  9758.     *hashlen = mbedtls_md_get_size( md_info );
  9759.  
  9760.     mbedtls_md_init( &ctx );
  9761.  
  9762.     /*
  9763.      * digitally-signed struct {
  9764.      *     opaque client_random[32];
  9765.      *     opaque server_random[32];
  9766.      *     ServerDHParams params;
  9767.      * };
  9768.      */
  9769.     if( ( ret = mbedtls_md_setup( &ctx, md_info, 0 ) ) != 0 )
  9770.     {
  9771.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_setup", ret );
  9772.         goto exit;
  9773.     }
  9774.     if( ( ret = mbedtls_md_starts( &ctx ) ) != 0 )
  9775.     {
  9776.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_starts", ret );
  9777.         goto exit;
  9778.     }
  9779.     if( ( ret = mbedtls_md_update( &ctx, ssl->handshake->randbytes, 64 ) ) != 0 )
  9780.     {
  9781.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_update", ret );
  9782.         goto exit;
  9783.     }
  9784.     if( ( ret = mbedtls_md_update( &ctx, data, data_len ) ) != 0 )
  9785.     {
  9786.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_update", ret );
  9787.         goto exit;
  9788.     }
  9789.     if( ( ret = mbedtls_md_finish( &ctx, hash ) ) != 0 )
  9790.     {
  9791.         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_finish", ret );
  9792.         goto exit;
  9793.     }
  9794.  
  9795. exit:
  9796.     mbedtls_md_free( &ctx );
  9797.  
  9798.     if( ret != 0 )
  9799.         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
  9800.                                         MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
  9801.  
  9802.     return( ret );
  9803. }
  9804. #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
  9805.           MBEDTLS_SSL_PROTO_TLS1_2 */
  9806.  
  9807. #endif /* MBEDTLS_SSL_TLS_C */
  9808.