Kenji Arai / mbed-os_TYBLE16

Dependents:   TYBLE16_simple_data_logger TYBLE16_MP3_Air

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers ssl_tls.c Source File

ssl_tls.c

00001 /*
00002  *  SSLv3/TLSv1 shared functions
00003  *
00004  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
00005  *  SPDX-License-Identifier: Apache-2.0
00006  *
00007  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
00008  *  not use this file except in compliance with the License.
00009  *  You may obtain a copy of the License at
00010  *
00011  *  http://www.apache.org/licenses/LICENSE-2.0
00012  *
00013  *  Unless required by applicable law or agreed to in writing, software
00014  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
00015  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00016  *  See the License for the specific language governing permissions and
00017  *  limitations under the License.
00018  *
00019  *  This file is part of mbed TLS (https://tls.mbed.org)
00020  */
00021 /*
00022  *  The SSL 3.0 specification was drafted by Netscape in 1996,
00023  *  and became an IETF standard in 1999.
00024  *
00025  *  http://wp.netscape.com/eng/ssl3/
00026  *  http://www.ietf.org/rfc/rfc2246.txt
00027  *  http://www.ietf.org/rfc/rfc4346.txt
00028  */
00029 
00030 #if !defined(MBEDTLS_CONFIG_FILE)
00031 #include "mbedtls/config.h"
00032 #else
00033 #include MBEDTLS_CONFIG_FILE
00034 #endif
00035 
00036 #if defined(MBEDTLS_SSL_TLS_C)
00037 
00038 #if defined(MBEDTLS_PLATFORM_C)
00039 #include "mbedtls/platform.h"
00040 #else
00041 #include <stdlib.h>
00042 #define mbedtls_calloc    calloc
00043 #define mbedtls_free      free
00044 #endif
00045 
00046 #include "mbedtls/debug.h"
00047 #include "mbedtls/ssl.h"
00048 #include "mbedtls/ssl_internal.h"
00049 #include "mbedtls/platform_util.h"
00050 #include "mbedtls/version.h"
00051 
00052 #include <string.h>
00053 
00054 #if defined(MBEDTLS_USE_PSA_CRYPTO)
00055 #include "mbedtls/psa_util.h"
00056 #include "psa/crypto.h"
00057 #endif
00058 
00059 #if defined(MBEDTLS_X509_CRT_PARSE_C)
00060 #include "mbedtls/oid.h"
00061 #endif
00062 
00063 static void ssl_reset_in_out_pointers( mbedtls_ssl_context *ssl );
00064 static uint32_t ssl_get_hs_total_len( mbedtls_ssl_context const *ssl );
00065 
00066 /* Length of the "epoch" field in the record header */
00067 static inline size_t ssl_ep_len( const mbedtls_ssl_context *ssl )
00068 {
00069 #if defined(MBEDTLS_SSL_PROTO_DTLS)
00070     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
00071         return( 2 );
00072 #else
00073     ((void) ssl);
00074 #endif
00075     return( 0 );
00076 }
00077 
00078 /*
00079  * Start a timer.
00080  * Passing millisecs = 0 cancels a running timer.
00081  */
00082 static void ssl_set_timer( mbedtls_ssl_context *ssl, uint32_t millisecs )
00083 {
00084     if( ssl->f_set_timer == NULL )
00085         return;
00086 
00087     MBEDTLS_SSL_DEBUG_MSG( 3, ( "set_timer to %d ms", (int) millisecs ) );
00088     ssl->f_set_timer( ssl->p_timer, millisecs / 4, millisecs );
00089 }
00090 
00091 /*
00092  * Return -1 is timer is expired, 0 if it isn't.
00093  */
00094 static int ssl_check_timer( mbedtls_ssl_context *ssl )
00095 {
00096     if( ssl->f_get_timer == NULL )
00097         return( 0 );
00098 
00099     if( ssl->f_get_timer( ssl->p_timer ) == 2 )
00100     {
00101         MBEDTLS_SSL_DEBUG_MSG( 3, ( "timer expired" ) );
00102         return( -1 );
00103     }
00104 
00105     return( 0 );
00106 }
00107 
00108 static void ssl_update_out_pointers( mbedtls_ssl_context *ssl,
00109                                      mbedtls_ssl_transform *transform );
00110 static void ssl_update_in_pointers( mbedtls_ssl_context *ssl );
00111 
00112 #if defined(MBEDTLS_SSL_RECORD_CHECKING)
00113 static int ssl_parse_record_header( mbedtls_ssl_context const *ssl,
00114                                     unsigned char *buf,
00115                                     size_t len,
00116                                     mbedtls_record *rec );
00117 
00118 int mbedtls_ssl_check_record( mbedtls_ssl_context const *ssl,
00119                               unsigned char *buf,
00120                               size_t buflen )
00121 {
00122     int ret = 0;
00123     mbedtls_record rec;
00124     MBEDTLS_SSL_DEBUG_MSG( 1, ( "=> mbedtls_ssl_check_record" ) );
00125     MBEDTLS_SSL_DEBUG_BUF( 3, "record buffer", buf, buflen );
00126 
00127     /* We don't support record checking in TLS because
00128      * (a) there doesn't seem to be a usecase for it, and
00129      * (b) In SSLv3 and TLS 1.0, CBC record decryption has state
00130      *     and we'd need to backup the transform here.
00131      */
00132     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_STREAM )
00133     {
00134         ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
00135         goto exit;
00136     }
00137 #if defined(MBEDTLS_SSL_PROTO_DTLS)
00138     else
00139     {
00140         ret = ssl_parse_record_header( ssl, buf, buflen, &rec );
00141         if( ret != 0 )
00142         {
00143             MBEDTLS_SSL_DEBUG_RET( 3, "ssl_parse_record_header", ret );
00144             goto exit;
00145         }
00146 
00147         if( ssl->transform_in != NULL )
00148         {
00149             ret = mbedtls_ssl_decrypt_buf( ssl, ssl->transform_in, &rec );
00150             if( ret != 0 )
00151             {
00152                 MBEDTLS_SSL_DEBUG_RET( 3, "mbedtls_ssl_decrypt_buf", ret );
00153                 goto exit;
00154             }
00155         }
00156     }
00157 #endif /* MBEDTLS_SSL_PROTO_DTLS */
00158 
00159 exit:
00160     /* On success, we have decrypted the buffer in-place, so make
00161      * sure we don't leak any plaintext data. */
00162     mbedtls_platform_zeroize( buf, buflen );
00163 
00164     /* For the purpose of this API, treat messages with unexpected CID
00165      * as well as such from future epochs as unexpected. */
00166     if( ret == MBEDTLS_ERR_SSL_UNEXPECTED_CID ||
00167         ret == MBEDTLS_ERR_SSL_EARLY_MESSAGE )
00168     {
00169         ret = MBEDTLS_ERR_SSL_UNEXPECTED_RECORD;
00170     }
00171 
00172     MBEDTLS_SSL_DEBUG_MSG( 1, ( "<= mbedtls_ssl_check_record" ) );
00173     return( ret );
00174 }
00175 #endif /* MBEDTLS_SSL_RECORD_CHECKING */
00176 
00177 #define SSL_DONT_FORCE_FLUSH 0
00178 #define SSL_FORCE_FLUSH      1
00179 
00180 #if defined(MBEDTLS_SSL_PROTO_DTLS)
00181 
00182 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
00183 /* Top-level Connection ID API */
00184 
00185 int mbedtls_ssl_conf_cid( mbedtls_ssl_config *conf,
00186                           size_t len,
00187                           int ignore_other_cid )
00188 {
00189     if( len > MBEDTLS_SSL_CID_IN_LEN_MAX )
00190         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
00191 
00192     if( ignore_other_cid != MBEDTLS_SSL_UNEXPECTED_CID_FAIL &&
00193         ignore_other_cid != MBEDTLS_SSL_UNEXPECTED_CID_IGNORE )
00194     {
00195         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
00196     }
00197 
00198     conf->ignore_unexpected_cid  = ignore_other_cid;
00199     conf->cid_len  = len;
00200     return( 0 );
00201 }
00202 
00203 int mbedtls_ssl_set_cid( mbedtls_ssl_context *ssl,
00204                          int enable,
00205                          unsigned char const *own_cid,
00206                          size_t own_cid_len )
00207 {
00208     if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM )
00209         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
00210 
00211     ssl->negotiate_cid = enable;
00212     if( enable == MBEDTLS_SSL_CID_DISABLED )
00213     {
00214         MBEDTLS_SSL_DEBUG_MSG( 3, ( "Disable use of CID extension." ) );
00215         return( 0 );
00216     }
00217     MBEDTLS_SSL_DEBUG_MSG( 3, ( "Enable use of CID extension." ) );
00218     MBEDTLS_SSL_DEBUG_BUF( 3, "Own CID", own_cid, own_cid_len );
00219 
00220     if( own_cid_len != ssl->conf->cid_len )
00221     {
00222         MBEDTLS_SSL_DEBUG_MSG( 3, ( "CID length %u does not match CID length %u in config",
00223                                     (unsigned) own_cid_len,
00224                                     (unsigned) ssl->conf->cid_len ) );
00225         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
00226     }
00227 
00228     memcpy( ssl->own_cid, own_cid, own_cid_len );
00229     /* Truncation is not an issue here because
00230      * MBEDTLS_SSL_CID_IN_LEN_MAX at most 255. */
00231     ssl->own_cid_len = (uint8_t) own_cid_len;
00232 
00233     return( 0 );
00234 }
00235 
00236 int mbedtls_ssl_get_peer_cid( mbedtls_ssl_context *ssl,
00237                      int *enabled,
00238                      unsigned char peer_cid[ MBEDTLS_SSL_CID_OUT_LEN_MAX ],
00239                      size_t *peer_cid_len )
00240 {
00241     *enabled = MBEDTLS_SSL_CID_DISABLED;
00242 
00243     if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM ||
00244         ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
00245     {
00246         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
00247     }
00248 
00249     /* We report MBEDTLS_SSL_CID_DISABLED in case the CID extensions
00250      * were used, but client and server requested the empty CID.
00251      * This is indistinguishable from not using the CID extension
00252      * in the first place. */
00253     if( ssl->transform_in->in_cid_len  == 0 &&
00254         ssl->transform_in->out_cid_len == 0 )
00255     {
00256         return( 0 );
00257     }
00258 
00259     if( peer_cid_len != NULL )
00260     {
00261         *peer_cid_len = ssl->transform_in->out_cid_len;
00262         if( peer_cid != NULL )
00263         {
00264             memcpy( peer_cid, ssl->transform_in->out_cid,
00265                     ssl->transform_in->out_cid_len );
00266         }
00267     }
00268 
00269     *enabled = MBEDTLS_SSL_CID_ENABLED;
00270 
00271     return( 0 );
00272 }
00273 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
00274 
00275 /* Forward declarations for functions related to message buffering. */
00276 static void ssl_buffering_free( mbedtls_ssl_context *ssl );
00277 static void ssl_buffering_free_slot( mbedtls_ssl_context *ssl,
00278                                      uint8_t slot );
00279 static void ssl_free_buffered_record( mbedtls_ssl_context *ssl );
00280 static int ssl_load_buffered_message( mbedtls_ssl_context *ssl );
00281 static int ssl_load_buffered_record( mbedtls_ssl_context *ssl );
00282 static int ssl_buffer_message( mbedtls_ssl_context *ssl );
00283 static int ssl_buffer_future_record( mbedtls_ssl_context *ssl,
00284                                      mbedtls_record const *rec );
00285 static int ssl_next_record_is_in_datagram( mbedtls_ssl_context *ssl );
00286 
00287 static size_t ssl_get_current_mtu( const mbedtls_ssl_context *ssl );
00288 static size_t ssl_get_maximum_datagram_size( mbedtls_ssl_context const *ssl )
00289 {
00290     size_t mtu = ssl_get_current_mtu( ssl );
00291 
00292     if( mtu != 0 && mtu < MBEDTLS_SSL_OUT_BUFFER_LEN )
00293         return( mtu );
00294 
00295     return( MBEDTLS_SSL_OUT_BUFFER_LEN );
00296 }
00297 
00298 static int ssl_get_remaining_space_in_datagram( mbedtls_ssl_context const *ssl )
00299 {
00300     size_t const bytes_written = ssl->out_left;
00301     size_t const mtu           = ssl_get_maximum_datagram_size( ssl );
00302 
00303     /* Double-check that the write-index hasn't gone
00304      * past what we can transmit in a single datagram. */
00305     if( bytes_written > mtu )
00306     {
00307         /* Should never happen... */
00308         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
00309     }
00310 
00311     return( (int) ( mtu - bytes_written ) );
00312 }
00313 
00314 static int ssl_get_remaining_payload_in_datagram( mbedtls_ssl_context const *ssl )
00315 {
00316     int ret;
00317     size_t remaining, expansion;
00318     size_t max_len = MBEDTLS_SSL_OUT_CONTENT_LEN;
00319 
00320 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
00321     const size_t mfl = mbedtls_ssl_get_max_frag_len( ssl );
00322 
00323     if( max_len > mfl )
00324         max_len = mfl;
00325 
00326     /* By the standard (RFC 6066 Sect. 4), the MFL extension
00327      * only limits the maximum record payload size, so in theory
00328      * we would be allowed to pack multiple records of payload size
00329      * MFL into a single datagram. However, this would mean that there's
00330      * no way to explicitly communicate MTU restrictions to the peer.
00331      *
00332      * The following reduction of max_len makes sure that we never
00333      * write datagrams larger than MFL + Record Expansion Overhead.
00334      */
00335     if( max_len <= ssl->out_left )
00336         return( 0 );
00337 
00338     max_len -= ssl->out_left;
00339 #endif
00340 
00341     ret = ssl_get_remaining_space_in_datagram( ssl );
00342     if( ret < 0 )
00343         return( ret );
00344     remaining = (size_t) ret;
00345 
00346     ret = mbedtls_ssl_get_record_expansion( ssl );
00347     if( ret < 0 )
00348         return( ret );
00349     expansion = (size_t) ret;
00350 
00351     if( remaining <= expansion )
00352         return( 0 );
00353 
00354     remaining -= expansion;
00355     if( remaining >= max_len )
00356         remaining = max_len;
00357 
00358     return( (int) remaining );
00359 }
00360 
00361 /*
00362  * Double the retransmit timeout value, within the allowed range,
00363  * returning -1 if the maximum value has already been reached.
00364  */
00365 static int ssl_double_retransmit_timeout( mbedtls_ssl_context *ssl )
00366 {
00367     uint32_t new_timeout;
00368 
00369     if( ssl->handshake->retransmit_timeout >= ssl->conf->hs_timeout_max )
00370         return( -1 );
00371 
00372     /* Implement the final paragraph of RFC 6347 section 4.1.1.1
00373      * in the following way: after the initial transmission and a first
00374      * retransmission, back off to a temporary estimated MTU of 508 bytes.
00375      * This value is guaranteed to be deliverable (if not guaranteed to be
00376      * delivered) of any compliant IPv4 (and IPv6) network, and should work
00377      * on most non-IP stacks too. */
00378     if( ssl->handshake->retransmit_timeout != ssl->conf->hs_timeout_min )
00379     {
00380         ssl->handshake->mtu = 508;
00381         MBEDTLS_SSL_DEBUG_MSG( 2, ( "mtu autoreduction to %d bytes", ssl->handshake->mtu ) );
00382     }
00383 
00384     new_timeout = 2 * ssl->handshake->retransmit_timeout;
00385 
00386     /* Avoid arithmetic overflow and range overflow */
00387     if( new_timeout < ssl->handshake->retransmit_timeout ||
00388         new_timeout > ssl->conf->hs_timeout_max )
00389     {
00390         new_timeout = ssl->conf->hs_timeout_max;
00391     }
00392 
00393     ssl->handshake->retransmit_timeout = new_timeout;
00394     MBEDTLS_SSL_DEBUG_MSG( 3, ( "update timeout value to %d millisecs",
00395                         ssl->handshake->retransmit_timeout ) );
00396 
00397     return( 0 );
00398 }
00399 
00400 static void ssl_reset_retransmit_timeout( mbedtls_ssl_context *ssl )
00401 {
00402     ssl->handshake->retransmit_timeout = ssl->conf->hs_timeout_min;
00403     MBEDTLS_SSL_DEBUG_MSG( 3, ( "update timeout value to %d millisecs",
00404                         ssl->handshake->retransmit_timeout ) );
00405 }
00406 #endif /* MBEDTLS_SSL_PROTO_DTLS */
00407 
00408 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
00409 /*
00410  * Convert max_fragment_length codes to length.
00411  * RFC 6066 says:
00412  *    enum{
00413  *        2^9(1), 2^10(2), 2^11(3), 2^12(4), (255)
00414  *    } MaxFragmentLength;
00415  * and we add 0 -> extension unused
00416  */
00417 static unsigned int ssl_mfl_code_to_length( int mfl )
00418 {
00419     switch( mfl )
00420     {
00421     case MBEDTLS_SSL_MAX_FRAG_LEN_NONE:
00422         return ( MBEDTLS_TLS_EXT_ADV_CONTENT_LEN );
00423     case MBEDTLS_SSL_MAX_FRAG_LEN_512:
00424         return 512;
00425     case MBEDTLS_SSL_MAX_FRAG_LEN_1024:
00426         return 1024;
00427     case MBEDTLS_SSL_MAX_FRAG_LEN_2048:
00428         return 2048;
00429     case MBEDTLS_SSL_MAX_FRAG_LEN_4096:
00430         return 4096;
00431     default:
00432         return ( MBEDTLS_TLS_EXT_ADV_CONTENT_LEN );
00433     }
00434 }
00435 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
00436 
00437 int mbedtls_ssl_session_copy( mbedtls_ssl_session *dst,
00438                               const mbedtls_ssl_session *src )
00439 {
00440     mbedtls_ssl_session_free( dst );
00441     memcpy( dst, src, sizeof( mbedtls_ssl_session ) );
00442 
00443 #if defined(MBEDTLS_X509_CRT_PARSE_C)
00444 
00445 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
00446     if( src->peer_cert != NULL )
00447     {
00448         int ret;
00449 
00450         dst->peer_cert = mbedtls_calloc( 1, sizeof(mbedtls_x509_crt) );
00451         if( dst->peer_cert == NULL )
00452             return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
00453 
00454         mbedtls_x509_crt_init( dst->peer_cert );
00455 
00456         if( ( ret = mbedtls_x509_crt_parse_der( dst->peer_cert, src->peer_cert->raw.p,
00457                                         src->peer_cert->raw.len ) ) != 0 )
00458         {
00459             mbedtls_free( dst->peer_cert );
00460             dst->peer_cert = NULL;
00461             return( ret );
00462         }
00463     }
00464 #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
00465     if( src->peer_cert_digest != NULL )
00466     {
00467         dst->peer_cert_digest =
00468             mbedtls_calloc( 1, src->peer_cert_digest_len );
00469         if( dst->peer_cert_digest == NULL )
00470             return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
00471 
00472         memcpy( dst->peer_cert_digest, src->peer_cert_digest,
00473                 src->peer_cert_digest_len );
00474         dst->peer_cert_digest_type = src->peer_cert_digest_type;
00475         dst->peer_cert_digest_len = src->peer_cert_digest_len;
00476     }
00477 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
00478 
00479 #endif /* MBEDTLS_X509_CRT_PARSE_C */
00480 
00481 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
00482     if( src->ticket != NULL )
00483     {
00484         dst->ticket = mbedtls_calloc( 1, src->ticket_len );
00485         if( dst->ticket == NULL )
00486             return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
00487 
00488         memcpy( dst->ticket, src->ticket, src->ticket_len );
00489     }
00490 #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */
00491 
00492     return( 0 );
00493 }
00494 
00495 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
00496 int (*mbedtls_ssl_hw_record_init)( mbedtls_ssl_context *ssl,
00497                      const unsigned char *key_enc, const unsigned char *key_dec,
00498                      size_t keylen,
00499                      const unsigned char *iv_enc,  const unsigned char *iv_dec,
00500                      size_t ivlen,
00501                      const unsigned char *mac_enc, const unsigned char *mac_dec,
00502                      size_t maclen ) = NULL;
00503 int (*mbedtls_ssl_hw_record_activate)( mbedtls_ssl_context *ssl, int direction) = NULL;
00504 int (*mbedtls_ssl_hw_record_reset)( mbedtls_ssl_context *ssl ) = NULL;
00505 int (*mbedtls_ssl_hw_record_write)( mbedtls_ssl_context *ssl ) = NULL;
00506 int (*mbedtls_ssl_hw_record_read)( mbedtls_ssl_context *ssl ) = NULL;
00507 int (*mbedtls_ssl_hw_record_finish)( mbedtls_ssl_context *ssl ) = NULL;
00508 #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
00509 
00510 /*
00511  * Key material generation
00512  */
00513 #if defined(MBEDTLS_SSL_PROTO_SSL3)
00514 static int ssl3_prf( const unsigned char *secret, size_t slen,
00515                      const char *label,
00516                      const unsigned char *random, size_t rlen,
00517                      unsigned char *dstbuf, size_t dlen )
00518 {
00519     int ret = 0;
00520     size_t i;
00521     mbedtls_md5_context md5;
00522     mbedtls_sha1_context sha1;
00523     unsigned char padding[16];
00524     unsigned char sha1sum[20];
00525     ((void)label);
00526 
00527     mbedtls_md5_init(  &md5  );
00528     mbedtls_sha1_init( &sha1 );
00529 
00530     /*
00531      *  SSLv3:
00532      *    block =
00533      *      MD5( secret + SHA1( 'A'    + secret + random ) ) +
00534      *      MD5( secret + SHA1( 'BB'   + secret + random ) ) +
00535      *      MD5( secret + SHA1( 'CCC'  + secret + random ) ) +
00536      *      ...
00537      */
00538     for( i = 0; i < dlen / 16; i++ )
00539     {
00540         memset( padding, (unsigned char) ('A' + i), 1 + i );
00541 
00542         if( ( ret = mbedtls_sha1_starts_ret( &sha1 ) ) != 0 )
00543             goto exit;
00544         if( ( ret = mbedtls_sha1_update_ret( &sha1, padding, 1 + i ) ) != 0 )
00545             goto exit;
00546         if( ( ret = mbedtls_sha1_update_ret( &sha1, secret, slen ) ) != 0 )
00547             goto exit;
00548         if( ( ret = mbedtls_sha1_update_ret( &sha1, random, rlen ) ) != 0 )
00549             goto exit;
00550         if( ( ret = mbedtls_sha1_finish_ret( &sha1, sha1sum ) ) != 0 )
00551             goto exit;
00552 
00553         if( ( ret = mbedtls_md5_starts_ret( &md5 ) ) != 0 )
00554             goto exit;
00555         if( ( ret = mbedtls_md5_update_ret( &md5, secret, slen ) ) != 0 )
00556             goto exit;
00557         if( ( ret = mbedtls_md5_update_ret( &md5, sha1sum, 20 ) ) != 0 )
00558             goto exit;
00559         if( ( ret = mbedtls_md5_finish_ret( &md5, dstbuf + i * 16 ) ) != 0 )
00560             goto exit;
00561     }
00562 
00563 exit:
00564     mbedtls_md5_free(  &md5  );
00565     mbedtls_sha1_free( &sha1 );
00566 
00567     mbedtls_platform_zeroize( padding, sizeof( padding ) );
00568     mbedtls_platform_zeroize( sha1sum, sizeof( sha1sum ) );
00569 
00570     return( ret );
00571 }
00572 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
00573 
00574 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
00575 static int tls1_prf( const unsigned char *secret, size_t slen,
00576                      const char *label,
00577                      const unsigned char *random, size_t rlen,
00578                      unsigned char *dstbuf, size_t dlen )
00579 {
00580     size_t nb, hs;
00581     size_t i, j, k;
00582     const unsigned char *S1, *S2;
00583     unsigned char *tmp;
00584     size_t tmp_len = 0;
00585     unsigned char h_i[20];
00586     const mbedtls_md_info_t *md_info;
00587     mbedtls_md_context_t md_ctx;
00588     int ret;
00589 
00590     mbedtls_md_init( &md_ctx );
00591 
00592     tmp_len = 20 + strlen( label ) + rlen;
00593     tmp = mbedtls_calloc( 1, tmp_len );
00594     if( tmp == NULL )
00595     {
00596         ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
00597         goto exit;
00598     }
00599 
00600     hs = ( slen + 1 ) / 2;
00601     S1 = secret;
00602     S2 = secret + slen - hs;
00603 
00604     nb = strlen( label );
00605     memcpy( tmp + 20, label, nb );
00606     memcpy( tmp + 20 + nb, random, rlen );
00607     nb += rlen;
00608 
00609     /*
00610      * First compute P_md5(secret,label+random)[0..dlen]
00611      */
00612     if( ( md_info = mbedtls_md_info_from_type( MBEDTLS_MD_MD5 ) ) == NULL )
00613     {
00614         ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
00615         goto exit;
00616     }
00617 
00618     if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )
00619     {
00620         goto exit;
00621     }
00622 
00623     mbedtls_md_hmac_starts( &md_ctx, S1, hs );
00624     mbedtls_md_hmac_update( &md_ctx, tmp + 20, nb );
00625     mbedtls_md_hmac_finish( &md_ctx, 4 + tmp );
00626 
00627     for( i = 0; i < dlen; i += 16 )
00628     {
00629         mbedtls_md_hmac_reset ( &md_ctx );
00630         mbedtls_md_hmac_update( &md_ctx, 4 + tmp, 16 + nb );
00631         mbedtls_md_hmac_finish( &md_ctx, h_i );
00632 
00633         mbedtls_md_hmac_reset ( &md_ctx );
00634         mbedtls_md_hmac_update( &md_ctx, 4 + tmp, 16 );
00635         mbedtls_md_hmac_finish( &md_ctx, 4 + tmp );
00636 
00637         k = ( i + 16 > dlen ) ? dlen % 16 : 16;
00638 
00639         for( j = 0; j < k; j++ )
00640             dstbuf[i + j]  = h_i[j];
00641     }
00642 
00643     mbedtls_md_free( &md_ctx );
00644 
00645     /*
00646      * XOR out with P_sha1(secret,label+random)[0..dlen]
00647      */
00648     if( ( md_info = mbedtls_md_info_from_type( MBEDTLS_MD_SHA1 ) ) == NULL )
00649     {
00650         ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
00651         goto exit;
00652     }
00653 
00654     if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )
00655     {
00656         goto exit;
00657     }
00658 
00659     mbedtls_md_hmac_starts( &md_ctx, S2, hs );
00660     mbedtls_md_hmac_update( &md_ctx, tmp + 20, nb );
00661     mbedtls_md_hmac_finish( &md_ctx, tmp );
00662 
00663     for( i = 0; i < dlen; i += 20 )
00664     {
00665         mbedtls_md_hmac_reset ( &md_ctx );
00666         mbedtls_md_hmac_update( &md_ctx, tmp, 20 + nb );
00667         mbedtls_md_hmac_finish( &md_ctx, h_i );
00668 
00669         mbedtls_md_hmac_reset ( &md_ctx );
00670         mbedtls_md_hmac_update( &md_ctx, tmp, 20 );
00671         mbedtls_md_hmac_finish( &md_ctx, tmp );
00672 
00673         k = ( i + 20 > dlen ) ? dlen % 20 : 20;
00674 
00675         for( j = 0; j < k; j++ )
00676             dstbuf[i + j] = (unsigned char)( dstbuf[i + j] ^ h_i[j] );
00677     }
00678 
00679 exit:
00680     mbedtls_md_free( &md_ctx );
00681 
00682     mbedtls_platform_zeroize( tmp, tmp_len );
00683     mbedtls_platform_zeroize( h_i, sizeof( h_i ) );
00684 
00685     mbedtls_free( tmp );
00686     return( ret );
00687 }
00688 #endif /* MBEDTLS_SSL_PROTO_TLS1) || MBEDTLS_SSL_PROTO_TLS1_1 */
00689 
00690 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
00691 #if defined(MBEDTLS_USE_PSA_CRYPTO)
00692 
00693 static psa_status_t setup_psa_key_derivation( psa_key_derivation_operation_t* derivation,
00694                                               psa_key_handle_t slot,
00695                                               psa_algorithm_t alg,
00696                                               const unsigned char* seed, size_t seed_length,
00697                                               const unsigned char* label, size_t label_length,
00698                                               size_t capacity )
00699 {
00700     psa_status_t status;
00701 
00702     status = psa_key_derivation_setup( derivation, alg );
00703     if( status != PSA_SUCCESS )
00704         return( status );
00705 
00706     if( PSA_ALG_IS_TLS12_PRF( alg ) || PSA_ALG_IS_TLS12_PSK_TO_MS( alg ) )
00707     {
00708         status = psa_key_derivation_input_bytes( derivation,
00709                                                  PSA_KEY_DERIVATION_INPUT_SEED,
00710                                                  seed, seed_length );
00711         if( status != PSA_SUCCESS )
00712             return( status );
00713 
00714         if( slot == 0 )
00715         {
00716             status = psa_key_derivation_input_bytes(
00717                 derivation, PSA_KEY_DERIVATION_INPUT_SECRET,
00718                 NULL, 0 );
00719         }
00720         else
00721         {
00722             status = psa_key_derivation_input_key(
00723                 derivation, PSA_KEY_DERIVATION_INPUT_SECRET,
00724                 slot );
00725         }
00726         if( status != PSA_SUCCESS )
00727             return( status );
00728 
00729         status = psa_key_derivation_input_bytes( derivation,
00730                                                  PSA_KEY_DERIVATION_INPUT_LABEL,
00731                                                  label, label_length );
00732         if( status != PSA_SUCCESS )
00733             return( status );
00734     }
00735     else
00736     {
00737         return( PSA_ERROR_NOT_SUPPORTED );
00738     }
00739 
00740     status = psa_key_derivation_set_capacity( derivation, capacity );
00741     if( status != PSA_SUCCESS )
00742         return( status );
00743 
00744     return( PSA_SUCCESS );
00745 }
00746 
00747 static int tls_prf_generic( mbedtls_md_type_t md_type,
00748                             const unsigned char *secret, size_t slen,
00749                             const char *label,
00750                             const unsigned char *random, size_t rlen,
00751                             unsigned char *dstbuf, size_t dlen )
00752 {
00753     psa_status_t status;
00754     psa_algorithm_t alg;
00755     psa_key_handle_t master_slot = 0;
00756     psa_key_derivation_operation_t derivation =
00757         PSA_KEY_DERIVATION_OPERATION_INIT;
00758 
00759     if( md_type == MBEDTLS_MD_SHA384 )
00760         alg = PSA_ALG_TLS12_PRF(PSA_ALG_SHA_384);
00761     else
00762         alg = PSA_ALG_TLS12_PRF(PSA_ALG_SHA_256);
00763 
00764     /* Normally a "secret" should be long enough to be impossible to
00765      * find by brute force, and in particular should not be empty. But
00766      * this PRF is also used to derive an IV, in particular in EAP-TLS,
00767      * and for this use case it makes sense to have a 0-length "secret".
00768      * Since the key API doesn't allow importing a key of length 0,
00769      * keep master_slot=0, which setup_psa_key_derivation() understands
00770      * to mean a 0-length "secret" input. */
00771     if( slen != 0 )
00772     {
00773         psa_key_attributes_t key_attributes = psa_key_attributes_init();
00774         psa_set_key_usage_flags( &key_attributes, PSA_KEY_USAGE_DERIVE );
00775         psa_set_key_algorithm( &key_attributes, alg );
00776         psa_set_key_type( &key_attributes, PSA_KEY_TYPE_DERIVE );
00777 
00778         status = psa_import_key( &key_attributes, secret, slen, &master_slot );
00779         if( status != PSA_SUCCESS )
00780             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
00781     }
00782 
00783     status = setup_psa_key_derivation( &derivation,
00784                                        master_slot, alg,
00785                                        random, rlen,
00786                                        (unsigned char const *) label,
00787                                        (size_t) strlen( label ),
00788                                        dlen );
00789     if( status != PSA_SUCCESS )
00790     {
00791         psa_key_derivation_abort( &derivation );
00792         psa_destroy_key( master_slot );
00793         return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
00794     }
00795 
00796     status = psa_key_derivation_output_bytes( &derivation, dstbuf, dlen );
00797     if( status != PSA_SUCCESS )
00798     {
00799         psa_key_derivation_abort( &derivation );
00800         psa_destroy_key( master_slot );
00801         return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
00802     }
00803 
00804     status = psa_key_derivation_abort( &derivation );
00805     if( status != PSA_SUCCESS )
00806     {
00807         psa_destroy_key( master_slot );
00808         return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
00809     }
00810 
00811     if( master_slot != 0 )
00812         status = psa_destroy_key( master_slot );
00813     if( status != PSA_SUCCESS )
00814         return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
00815 
00816     return( 0 );
00817 }
00818 
00819 #else /* MBEDTLS_USE_PSA_CRYPTO */
00820 
00821 static int tls_prf_generic( mbedtls_md_type_t md_type,
00822                             const unsigned char *secret, size_t slen,
00823                             const char *label,
00824                             const unsigned char *random, size_t rlen,
00825                             unsigned char *dstbuf, size_t dlen )
00826 {
00827     size_t nb;
00828     size_t i, j, k, md_len;
00829     unsigned char *tmp;
00830     size_t tmp_len = 0;
00831     unsigned char h_i[MBEDTLS_MD_MAX_SIZE];
00832     const mbedtls_md_info_t *md_info;
00833     mbedtls_md_context_t md_ctx;
00834     int ret;
00835 
00836     mbedtls_md_init( &md_ctx );
00837 
00838     if( ( md_info = mbedtls_md_info_from_type( md_type ) ) == NULL )
00839         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
00840 
00841     md_len = mbedtls_md_get_size( md_info );
00842 
00843     tmp_len = md_len + strlen( label ) + rlen;
00844     tmp = mbedtls_calloc( 1, tmp_len );
00845     if( tmp == NULL )
00846     {
00847         ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
00848         goto exit;
00849     }
00850 
00851     nb = strlen( label );
00852     memcpy( tmp + md_len, label, nb );
00853     memcpy( tmp + md_len + nb, random, rlen );
00854     nb += rlen;
00855 
00856     /*
00857      * Compute P_<hash>(secret, label + random)[0..dlen]
00858      */
00859     if ( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 )
00860         goto exit;
00861 
00862     mbedtls_md_hmac_starts( &md_ctx, secret, slen );
00863     mbedtls_md_hmac_update( &md_ctx, tmp + md_len, nb );
00864     mbedtls_md_hmac_finish( &md_ctx, tmp );
00865 
00866     for( i = 0; i < dlen; i += md_len )
00867     {
00868         mbedtls_md_hmac_reset ( &md_ctx );
00869         mbedtls_md_hmac_update( &md_ctx, tmp, md_len + nb );
00870         mbedtls_md_hmac_finish( &md_ctx, h_i );
00871 
00872         mbedtls_md_hmac_reset ( &md_ctx );
00873         mbedtls_md_hmac_update( &md_ctx, tmp, md_len );
00874         mbedtls_md_hmac_finish( &md_ctx, tmp );
00875 
00876         k = ( i + md_len > dlen ) ? dlen % md_len : md_len;
00877 
00878         for( j = 0; j < k; j++ )
00879             dstbuf[i + j]  = h_i[j];
00880     }
00881 
00882 exit:
00883     mbedtls_md_free( &md_ctx );
00884 
00885     mbedtls_platform_zeroize( tmp, tmp_len );
00886     mbedtls_platform_zeroize( h_i, sizeof( h_i ) );
00887 
00888     mbedtls_free( tmp );
00889 
00890     return( ret );
00891 }
00892 #endif /* MBEDTLS_USE_PSA_CRYPTO */
00893 #if defined(MBEDTLS_SHA256_C)
00894 static int tls_prf_sha256( const unsigned char *secret, size_t slen,
00895                            const char *label,
00896                            const unsigned char *random, size_t rlen,
00897                            unsigned char *dstbuf, size_t dlen )
00898 {
00899     return( tls_prf_generic( MBEDTLS_MD_SHA256, secret, slen,
00900                              label, random, rlen, dstbuf, dlen ) );
00901 }
00902 #endif /* MBEDTLS_SHA256_C */
00903 
00904 #if defined(MBEDTLS_SHA512_C)
00905 static int tls_prf_sha384( const unsigned char *secret, size_t slen,
00906                            const char *label,
00907                            const unsigned char *random, size_t rlen,
00908                            unsigned char *dstbuf, size_t dlen )
00909 {
00910     return( tls_prf_generic( MBEDTLS_MD_SHA384, secret, slen,
00911                              label, random, rlen, dstbuf, dlen ) );
00912 }
00913 #endif /* MBEDTLS_SHA512_C */
00914 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
00915 
00916 static void ssl_update_checksum_start( mbedtls_ssl_context *, const unsigned char *, size_t );
00917 
00918 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
00919     defined(MBEDTLS_SSL_PROTO_TLS1_1)
00920 static void ssl_update_checksum_md5sha1( mbedtls_ssl_context *, const unsigned char *, size_t );
00921 #endif
00922 
00923 #if defined(MBEDTLS_SSL_PROTO_SSL3)
00924 static void ssl_calc_verify_ssl( const mbedtls_ssl_context *, unsigned char *, size_t * );
00925 static void ssl_calc_finished_ssl( mbedtls_ssl_context *, unsigned char *, int );
00926 #endif
00927 
00928 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
00929 static void ssl_calc_verify_tls( const mbedtls_ssl_context *, unsigned char *, size_t * );
00930 static void ssl_calc_finished_tls( mbedtls_ssl_context *, unsigned char *, int );
00931 #endif
00932 
00933 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
00934 #if defined(MBEDTLS_SHA256_C)
00935 static void ssl_update_checksum_sha256( mbedtls_ssl_context *, const unsigned char *, size_t );
00936 static void ssl_calc_verify_tls_sha256( const mbedtls_ssl_context *,unsigned char *, size_t * );
00937 static void ssl_calc_finished_tls_sha256( mbedtls_ssl_context *,unsigned char *, int );
00938 #endif
00939 
00940 #if defined(MBEDTLS_SHA512_C)
00941 static void ssl_update_checksum_sha384( mbedtls_ssl_context *, const unsigned char *, size_t );
00942 static void ssl_calc_verify_tls_sha384( const mbedtls_ssl_context *, unsigned char *, size_t * );
00943 static void ssl_calc_finished_tls_sha384( mbedtls_ssl_context *, unsigned char *, int );
00944 #endif
00945 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
00946 
00947 #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) && \
00948     defined(MBEDTLS_USE_PSA_CRYPTO)
00949 static int ssl_use_opaque_psk( mbedtls_ssl_context const *ssl )
00950 {
00951     if( ssl->conf->f_psk != NULL )
00952     {
00953         /* If we've used a callback to select the PSK,
00954          * the static configuration is irrelevant. */
00955         if( ssl->handshake->psk_opaque != 0 )
00956             return( 1 );
00957 
00958         return( 0 );
00959     }
00960 
00961     if( ssl->conf->psk_opaque != 0 )
00962         return( 1 );
00963 
00964     return( 0 );
00965 }
00966 #endif /* MBEDTLS_USE_PSA_CRYPTO &&
00967           MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */
00968 
00969 #if defined(MBEDTLS_SSL_EXPORT_KEYS)
00970 static mbedtls_tls_prf_types tls_prf_get_type( mbedtls_ssl_tls_prf_cb *tls_prf )
00971 {
00972 #if defined(MBEDTLS_SSL_PROTO_SSL3)
00973     if( tls_prf == ssl3_prf )
00974     {
00975         return( MBEDTLS_SSL_TLS_PRF_SSL3 );
00976     }
00977     else
00978 #endif
00979 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
00980     if( tls_prf == tls1_prf )
00981     {
00982         return( MBEDTLS_SSL_TLS_PRF_TLS1 );
00983     }
00984     else
00985 #endif
00986 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
00987 #if defined(MBEDTLS_SHA512_C)
00988     if( tls_prf == tls_prf_sha384 )
00989     {
00990         return( MBEDTLS_SSL_TLS_PRF_SHA384 );
00991     }
00992     else
00993 #endif
00994 #if defined(MBEDTLS_SHA256_C)
00995     if( tls_prf == tls_prf_sha256 )
00996     {
00997         return( MBEDTLS_SSL_TLS_PRF_SHA256 );
00998     }
00999     else
01000 #endif
01001 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
01002     return( MBEDTLS_SSL_TLS_PRF_NONE );
01003 }
01004 #endif /* MBEDTLS_SSL_EXPORT_KEYS */
01005 
01006 int  mbedtls_ssl_tls_prf( const mbedtls_tls_prf_types prf,
01007                           const unsigned char *secret, size_t slen,
01008                           const char *label,
01009                           const unsigned char *random, size_t rlen,
01010                           unsigned char *dstbuf, size_t dlen )
01011 {
01012     mbedtls_ssl_tls_prf_cb *tls_prf = NULL;
01013 
01014     switch( prf )
01015     {
01016 #if defined(MBEDTLS_SSL_PROTO_SSL3)
01017         case MBEDTLS_SSL_TLS_PRF_SSL3:
01018             tls_prf = ssl3_prf;
01019         break;
01020 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
01021 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
01022         case MBEDTLS_SSL_TLS_PRF_TLS1:
01023             tls_prf = tls1_prf;
01024         break;
01025 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
01026 
01027 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
01028 #if defined(MBEDTLS_SHA512_C)
01029         case MBEDTLS_SSL_TLS_PRF_SHA384:
01030             tls_prf = tls_prf_sha384;
01031         break;
01032 #endif /* MBEDTLS_SHA512_C */
01033 #if defined(MBEDTLS_SHA256_C)
01034         case MBEDTLS_SSL_TLS_PRF_SHA256:
01035             tls_prf = tls_prf_sha256;
01036         break;
01037 #endif /* MBEDTLS_SHA256_C */
01038 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
01039     default:
01040         return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
01041     }
01042 
01043     return( tls_prf( secret, slen, label, random, rlen, dstbuf, dlen ) );
01044 }
01045 
01046 /* Type for the TLS PRF */
01047 typedef int ssl_tls_prf_t(const unsigned char *, size_t, const char *,
01048                           const unsigned char *, size_t,
01049                           unsigned char *, size_t);
01050 
01051 /*
01052  * Populate a transform structure with session keys and all the other
01053  * necessary information.
01054  *
01055  * Parameters:
01056  * - [in/out]: transform: structure to populate
01057  *      [in] must be just initialised with mbedtls_ssl_transform_init()
01058  *      [out] fully populated, ready for use by mbedtls_ssl_{en,de}crypt_buf()
01059  * - [in] ciphersuite
01060  * - [in] master
01061  * - [in] encrypt_then_mac
01062  * - [in] trunc_hmac
01063  * - [in] compression
01064  * - [in] tls_prf: pointer to PRF to use for key derivation
01065  * - [in] randbytes: buffer holding ServerHello.random + ClientHello.random
01066  * - [in] minor_ver: SSL/TLS minor version
01067  * - [in] endpoint: client or server
01068  * - [in] ssl: optionally used for:
01069  *        - MBEDTLS_SSL_HW_RECORD_ACCEL: whole context
01070  *        - MBEDTLS_SSL_EXPORT_KEYS: ssl->conf->{f,p}_export_keys
01071  *        - MBEDTLS_DEBUG_C: ssl->conf->{f,p}_dbg
01072  */
01073 static int ssl_populate_transform( mbedtls_ssl_transform *transform,
01074                                    int ciphersuite,
01075                                    const unsigned char master[48],
01076 #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
01077 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
01078                                    int encrypt_then_mac,
01079 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
01080 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
01081                                    int trunc_hmac,
01082 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
01083 #endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */
01084 #if defined(MBEDTLS_ZLIB_SUPPORT)
01085                                    int compression,
01086 #endif
01087                                    ssl_tls_prf_t tls_prf,
01088                                    const unsigned char randbytes[64],
01089                                    int minor_ver,
01090                                    unsigned endpoint,
01091                                    const mbedtls_ssl_context *ssl )
01092 {
01093     int ret = 0;
01094 #if defined(MBEDTLS_USE_PSA_CRYPTO)
01095     int psa_fallthrough;
01096 #endif /* MBEDTLS_USE_PSA_CRYPTO */
01097     unsigned char keyblk[256];
01098     unsigned char *key1;
01099     unsigned char *key2;
01100     unsigned char *mac_enc;
01101     unsigned char *mac_dec;
01102     size_t mac_key_len;
01103     size_t iv_copy_len;
01104     unsigned keylen;
01105     const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
01106     const mbedtls_cipher_info_t *cipher_info;
01107     const mbedtls_md_info_t *md_info;
01108 
01109 #if !defined(MBEDTLS_SSL_HW_RECORD_ACCEL) && \
01110     !defined(MBEDTLS_SSL_EXPORT_KEYS) && \
01111     !defined(MBEDTLS_DEBUG_C)
01112     ssl = NULL; /* make sure we don't use it except for those cases */
01113     (void) ssl;
01114 #endif
01115 
01116     /*
01117      * Some data just needs copying into the structure
01118      */
01119 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) && \
01120     defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
01121     transform->encrypt_then_mac = encrypt_then_mac;
01122 #endif
01123     transform->minor_ver = minor_ver;
01124 
01125 #if defined(MBEDTLS_SSL_CONTEXT_SERIALIZATION)
01126     memcpy( transform->randbytes, randbytes, sizeof( transform->randbytes ) );
01127 #endif
01128 
01129     /*
01130      * Get various info structures
01131      */
01132     ciphersuite_info = mbedtls_ssl_ciphersuite_from_id( ciphersuite );
01133     if( ciphersuite_info == NULL )
01134     {
01135         MBEDTLS_SSL_DEBUG_MSG( 1, ( "ciphersuite info for %d not found",
01136                                     ciphersuite ) );
01137         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
01138     }
01139 
01140     cipher_info = mbedtls_cipher_info_from_type( ciphersuite_info->cipher );
01141     if( cipher_info == NULL )
01142     {
01143         MBEDTLS_SSL_DEBUG_MSG( 1, ( "cipher info for %d not found",
01144                                     ciphersuite_info->cipher ) );
01145         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
01146     }
01147 
01148     md_info = mbedtls_md_info_from_type( ciphersuite_info->mac );
01149     if( md_info == NULL )
01150     {
01151         MBEDTLS_SSL_DEBUG_MSG( 1, ( "mbedtls_md info for %d not found",
01152                             ciphersuite_info->mac ) );
01153         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
01154     }
01155 
01156 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
01157     /* Copy own and peer's CID if the use of the CID
01158      * extension has been negotiated. */
01159     if( ssl->handshake->cid_in_use == MBEDTLS_SSL_CID_ENABLED )
01160     {
01161         MBEDTLS_SSL_DEBUG_MSG( 3, ( "Copy CIDs into SSL transform" ) );
01162 
01163         transform->in_cid_len = ssl->own_cid_len;
01164         memcpy( transform->in_cid, ssl->own_cid, ssl->own_cid_len );
01165         MBEDTLS_SSL_DEBUG_BUF( 3, "Incoming CID", transform->in_cid,
01166                                transform->in_cid_len );
01167 
01168         transform->out_cid_len = ssl->handshake->peer_cid_len;
01169         memcpy( transform->out_cid, ssl->handshake->peer_cid,
01170                 ssl->handshake->peer_cid_len );
01171         MBEDTLS_SSL_DEBUG_BUF( 3, "Outgoing CID", transform->out_cid,
01172                                transform->out_cid_len );
01173     }
01174 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
01175 
01176     /*
01177      * Compute key block using the PRF
01178      */
01179     ret = tls_prf( master, 48, "key expansion", randbytes, 64, keyblk, 256 );
01180     if( ret != 0 )
01181     {
01182         MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret );
01183         return( ret );
01184     }
01185 
01186     MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite = %s",
01187                            mbedtls_ssl_get_ciphersuite_name( ciphersuite ) ) );
01188     MBEDTLS_SSL_DEBUG_BUF( 3, "master secret", master, 48 );
01189     MBEDTLS_SSL_DEBUG_BUF( 4, "random bytes", randbytes, 64 );
01190     MBEDTLS_SSL_DEBUG_BUF( 4, "key block", keyblk, 256 );
01191 
01192     /*
01193      * Determine the appropriate key, IV and MAC length.
01194      */
01195 
01196     keylen = cipher_info->key_bitlen / 8;
01197 
01198 #if defined(MBEDTLS_GCM_C) ||                           \
01199     defined(MBEDTLS_CCM_C) ||                           \
01200     defined(MBEDTLS_CHACHAPOLY_C)
01201     if( cipher_info->mode == MBEDTLS_MODE_GCM ||
01202         cipher_info->mode == MBEDTLS_MODE_CCM ||
01203         cipher_info->mode == MBEDTLS_MODE_CHACHAPOLY )
01204     {
01205         size_t explicit_ivlen;
01206 
01207         transform->maclen = 0;
01208         mac_key_len = 0;
01209         transform->taglen =
01210             ciphersuite_info->flags & MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16;
01211 
01212         /* All modes haves 96-bit IVs;
01213          * GCM and CCM has 4 implicit and 8 explicit bytes
01214          * ChachaPoly has all 12 bytes implicit
01215          */
01216         transform->ivlen = 12;
01217         if( cipher_info->mode == MBEDTLS_MODE_CHACHAPOLY )
01218             transform->fixed_ivlen = 12;
01219         else
01220             transform->fixed_ivlen = 4;
01221 
01222         /* Minimum length of encrypted record */
01223         explicit_ivlen = transform->ivlen - transform->fixed_ivlen;
01224         transform->minlen = explicit_ivlen + transform->taglen;
01225     }
01226     else
01227 #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C || MBEDTLS_CHACHAPOLY_C */
01228 #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
01229     if( cipher_info->mode == MBEDTLS_MODE_STREAM ||
01230         cipher_info->mode == MBEDTLS_MODE_CBC )
01231     {
01232         /* Initialize HMAC contexts */
01233         if( ( ret = mbedtls_md_setup( &transform->md_ctx_enc, md_info, 1 ) ) != 0 ||
01234             ( ret = mbedtls_md_setup( &transform->md_ctx_dec, md_info, 1 ) ) != 0 )
01235         {
01236             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_setup", ret );
01237             goto end;
01238         }
01239 
01240         /* Get MAC length */
01241         mac_key_len = mbedtls_md_get_size( md_info );
01242         transform->maclen = mac_key_len;
01243 
01244 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
01245         /*
01246          * If HMAC is to be truncated, we shall keep the leftmost bytes,
01247          * (rfc 6066 page 13 or rfc 2104 section 4),
01248          * so we only need to adjust the length here.
01249          */
01250         if( trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_ENABLED )
01251         {
01252             transform->maclen = MBEDTLS_SSL_TRUNCATED_HMAC_LEN;
01253 
01254 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT)
01255             /* Fall back to old, non-compliant version of the truncated
01256              * HMAC implementation which also truncates the key
01257              * (Mbed TLS versions from 1.3 to 2.6.0) */
01258             mac_key_len = transform->maclen;
01259 #endif
01260         }
01261 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
01262 
01263         /* IV length */
01264         transform->ivlen = cipher_info->iv_size;
01265 
01266         /* Minimum length */
01267         if( cipher_info->mode == MBEDTLS_MODE_STREAM )
01268             transform->minlen = transform->maclen;
01269         else
01270         {
01271             /*
01272              * GenericBlockCipher:
01273              * 1. if EtM is in use: one block plus MAC
01274              *    otherwise: * first multiple of blocklen greater than maclen
01275              * 2. IV except for SSL3 and TLS 1.0
01276              */
01277 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
01278             if( encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED )
01279             {
01280                 transform->minlen = transform->maclen
01281                                   + cipher_info->block_size;
01282             }
01283             else
01284 #endif
01285             {
01286                 transform->minlen = transform->maclen
01287                                   + cipher_info->block_size
01288                                   - transform->maclen % cipher_info->block_size;
01289             }
01290 
01291 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1)
01292             if( minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ||
01293                 minor_ver == MBEDTLS_SSL_MINOR_VERSION_1 )
01294                 ; /* No need to adjust minlen */
01295             else
01296 #endif
01297 #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
01298             if( minor_ver == MBEDTLS_SSL_MINOR_VERSION_2 ||
01299                 minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
01300             {
01301                 transform->minlen += transform->ivlen;
01302             }
01303             else
01304 #endif
01305             {
01306                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
01307                 ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
01308                 goto end;
01309             }
01310         }
01311     }
01312     else
01313 #endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */
01314     {
01315         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
01316         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
01317     }
01318 
01319     MBEDTLS_SSL_DEBUG_MSG( 3, ( "keylen: %u, minlen: %u, ivlen: %u, maclen: %u",
01320                                 (unsigned) keylen,
01321                                 (unsigned) transform->minlen,
01322                                 (unsigned) transform->ivlen,
01323                                 (unsigned) transform->maclen ) );
01324 
01325     /*
01326      * Finally setup the cipher contexts, IVs and MAC secrets.
01327      */
01328 #if defined(MBEDTLS_SSL_CLI_C)
01329     if( endpoint == MBEDTLS_SSL_IS_CLIENT )
01330     {
01331         key1 = keyblk + mac_key_len * 2;
01332         key2 = keyblk + mac_key_len * 2 + keylen;
01333 
01334         mac_enc = keyblk;
01335         mac_dec = keyblk + mac_key_len;
01336 
01337         /*
01338          * This is not used in TLS v1.1.
01339          */
01340         iv_copy_len = ( transform->fixed_ivlen ) ?
01341                             transform->fixed_ivlen : transform->ivlen;
01342         memcpy( transform->iv_enc, key2 + keylen,  iv_copy_len );
01343         memcpy( transform->iv_dec, key2 + keylen + iv_copy_len,
01344                 iv_copy_len );
01345     }
01346     else
01347 #endif /* MBEDTLS_SSL_CLI_C */
01348 #if defined(MBEDTLS_SSL_SRV_C)
01349     if( endpoint == MBEDTLS_SSL_IS_SERVER )
01350     {
01351         key1 = keyblk + mac_key_len * 2 + keylen;
01352         key2 = keyblk + mac_key_len * 2;
01353 
01354         mac_enc = keyblk + mac_key_len;
01355         mac_dec = keyblk;
01356 
01357         /*
01358          * This is not used in TLS v1.1.
01359          */
01360         iv_copy_len = ( transform->fixed_ivlen ) ?
01361                             transform->fixed_ivlen : transform->ivlen;
01362         memcpy( transform->iv_dec, key1 + keylen,  iv_copy_len );
01363         memcpy( transform->iv_enc, key1 + keylen + iv_copy_len,
01364                 iv_copy_len );
01365     }
01366     else
01367 #endif /* MBEDTLS_SSL_SRV_C */
01368     {
01369         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
01370         ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
01371         goto end;
01372     }
01373 
01374 #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
01375 #if defined(MBEDTLS_SSL_PROTO_SSL3)
01376     if( minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
01377     {
01378         if( mac_key_len > sizeof( transform->mac_enc ) )
01379         {
01380             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
01381             ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
01382             goto end;
01383         }
01384 
01385         memcpy( transform->mac_enc, mac_enc, mac_key_len );
01386         memcpy( transform->mac_dec, mac_dec, mac_key_len );
01387     }
01388     else
01389 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
01390 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
01391     defined(MBEDTLS_SSL_PROTO_TLS1_2)
01392     if( minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 )
01393     {
01394         /* For HMAC-based ciphersuites, initialize the HMAC transforms.
01395            For AEAD-based ciphersuites, there is nothing to do here. */
01396         if( mac_key_len != 0 )
01397         {
01398             mbedtls_md_hmac_starts( &transform->md_ctx_enc, mac_enc, mac_key_len );
01399             mbedtls_md_hmac_starts( &transform->md_ctx_dec, mac_dec, mac_key_len );
01400         }
01401     }
01402     else
01403 #endif
01404     {
01405         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
01406         ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
01407         goto end;
01408     }
01409 #endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */
01410 
01411 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
01412     if( mbedtls_ssl_hw_record_init != NULL )
01413     {
01414         int ret = 0;
01415 
01416         MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_init()" ) );
01417 
01418         if( ( ret = mbedtls_ssl_hw_record_init( ssl, key1, key2, keylen,
01419                                         transform->iv_enc, transform->iv_dec,
01420                                         iv_copy_len,
01421                                         mac_enc, mac_dec,
01422                                         mac_key_len ) ) != 0 )
01423         {
01424             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_init", ret );
01425             ret = MBEDTLS_ERR_SSL_HW_ACCEL_FAILED;
01426             goto end;
01427         }
01428     }
01429 #else
01430     ((void) mac_dec);
01431     ((void) mac_enc);
01432 #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
01433 
01434 #if defined(MBEDTLS_SSL_EXPORT_KEYS)
01435     if( ssl->conf->f_export_keys != NULL )
01436     {
01437         ssl->conf->f_export_keys( ssl->conf->p_export_keys,
01438                                   master, keyblk,
01439                                   mac_key_len, keylen,
01440                                   iv_copy_len );
01441     }
01442 
01443     if( ssl->conf->f_export_keys_ext != NULL )
01444     {
01445         ssl->conf->f_export_keys_ext( ssl->conf->p_export_keys,
01446                                       master, keyblk,
01447                                       mac_key_len, keylen,
01448                                       iv_copy_len,
01449                                       randbytes + 32,
01450                                       randbytes,
01451                                       tls_prf_get_type( tls_prf ) );
01452     }
01453 #endif
01454 
01455 #if defined(MBEDTLS_USE_PSA_CRYPTO)
01456 
01457     /* Only use PSA-based ciphers for TLS-1.2.
01458      * That's relevant at least for TLS-1.0, where
01459      * we assume that mbedtls_cipher_crypt() updates
01460      * the structure field for the IV, which the PSA-based
01461      * implementation currently doesn't. */
01462 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
01463     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
01464     {
01465         ret = mbedtls_cipher_setup_psa( &transform->cipher_ctx_enc,
01466                                         cipher_info, transform->taglen );
01467         if( ret != 0 && ret != MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE )
01468         {
01469             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup_psa", ret );
01470             goto end;
01471         }
01472 
01473         if( ret == 0 )
01474         {
01475             MBEDTLS_SSL_DEBUG_MSG( 3, ( "Successfully setup PSA-based encryption cipher context" ) );
01476             psa_fallthrough = 0;
01477         }
01478         else
01479         {
01480             MBEDTLS_SSL_DEBUG_MSG( 1, ( "Failed to setup PSA-based cipher context for record encryption - fall through to default setup." ) );
01481             psa_fallthrough = 1;
01482         }
01483     }
01484     else
01485         psa_fallthrough = 1;
01486 #else
01487     psa_fallthrough = 1;
01488 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
01489 
01490     if( psa_fallthrough == 1 )
01491 #endif /* MBEDTLS_USE_PSA_CRYPTO */
01492     if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_enc,
01493                                  cipher_info ) ) != 0 )
01494     {
01495         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup", ret );
01496         goto end;
01497     }
01498 
01499 #if defined(MBEDTLS_USE_PSA_CRYPTO)
01500     /* Only use PSA-based ciphers for TLS-1.2.
01501      * That's relevant at least for TLS-1.0, where
01502      * we assume that mbedtls_cipher_crypt() updates
01503      * the structure field for the IV, which the PSA-based
01504      * implementation currently doesn't. */
01505 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
01506     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
01507     {
01508         ret = mbedtls_cipher_setup_psa( &transform->cipher_ctx_dec,
01509                                         cipher_info, transform->taglen );
01510         if( ret != 0 && ret != MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE )
01511         {
01512             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup_psa", ret );
01513             goto end;
01514         }
01515 
01516         if( ret == 0 )
01517         {
01518             MBEDTLS_SSL_DEBUG_MSG( 3, ( "Successfully setup PSA-based decryption cipher context" ) );
01519             psa_fallthrough = 0;
01520         }
01521         else
01522         {
01523             MBEDTLS_SSL_DEBUG_MSG( 1, ( "Failed to setup PSA-based cipher context for record decryption - fall through to default setup." ) );
01524             psa_fallthrough = 1;
01525         }
01526     }
01527     else
01528         psa_fallthrough = 1;
01529 #else
01530     psa_fallthrough = 1;
01531 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
01532 
01533     if( psa_fallthrough == 1 )
01534 #endif /* MBEDTLS_USE_PSA_CRYPTO */
01535     if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_dec,
01536                                  cipher_info ) ) != 0 )
01537     {
01538         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup", ret );
01539         goto end;
01540     }
01541 
01542     if( ( ret = mbedtls_cipher_setkey( &transform->cipher_ctx_enc, key1,
01543                                cipher_info->key_bitlen,
01544                                MBEDTLS_ENCRYPT ) ) != 0 )
01545     {
01546         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setkey", ret );
01547         goto end;
01548     }
01549 
01550     if( ( ret = mbedtls_cipher_setkey( &transform->cipher_ctx_dec, key2,
01551                                cipher_info->key_bitlen,
01552                                MBEDTLS_DECRYPT ) ) != 0 )
01553     {
01554         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setkey", ret );
01555         goto end;
01556     }
01557 
01558 #if defined(MBEDTLS_CIPHER_MODE_CBC)
01559     if( cipher_info->mode == MBEDTLS_MODE_CBC )
01560     {
01561         if( ( ret = mbedtls_cipher_set_padding_mode( &transform->cipher_ctx_enc,
01562                                              MBEDTLS_PADDING_NONE ) ) != 0 )
01563         {
01564             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_set_padding_mode", ret );
01565             goto end;
01566         }
01567 
01568         if( ( ret = mbedtls_cipher_set_padding_mode( &transform->cipher_ctx_dec,
01569                                              MBEDTLS_PADDING_NONE ) ) != 0 )
01570         {
01571             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_set_padding_mode", ret );
01572             goto end;
01573         }
01574     }
01575 #endif /* MBEDTLS_CIPHER_MODE_CBC */
01576 
01577 
01578     /* Initialize Zlib contexts */
01579 #if defined(MBEDTLS_ZLIB_SUPPORT)
01580     if( compression == MBEDTLS_SSL_COMPRESS_DEFLATE )
01581     {
01582         MBEDTLS_SSL_DEBUG_MSG( 3, ( "Initializing zlib states" ) );
01583 
01584         memset( &transform->ctx_deflate, 0, sizeof( transform->ctx_deflate ) );
01585         memset( &transform->ctx_inflate, 0, sizeof( transform->ctx_inflate ) );
01586 
01587         if( deflateInit( &transform->ctx_deflate,
01588                          Z_DEFAULT_COMPRESSION )   != Z_OK ||
01589             inflateInit( &transform->ctx_inflate ) != Z_OK )
01590         {
01591             MBEDTLS_SSL_DEBUG_MSG( 1, ( "Failed to initialize compression" ) );
01592             ret = MBEDTLS_ERR_SSL_COMPRESSION_FAILED;
01593             goto end;
01594         }
01595     }
01596 #endif /* MBEDTLS_ZLIB_SUPPORT */
01597 
01598 end:
01599     mbedtls_platform_zeroize( keyblk, sizeof( keyblk ) );
01600     return( ret );
01601 }
01602 
01603 /*
01604  * Set appropriate PRF function and other SSL / TLS 1.0/1.1 / TLS1.2 functions
01605  *
01606  * Inputs:
01607  * - SSL/TLS minor version
01608  * - hash associated with the ciphersuite (only used by TLS 1.2)
01609  *
01610  * Outputs:
01611  * - the tls_prf, calc_verify and calc_finished members of handshake structure
01612  */
01613 static int ssl_set_handshake_prfs( mbedtls_ssl_handshake_params *handshake,
01614                                    int minor_ver,
01615                                    mbedtls_md_type_t hash )
01616 {
01617 #if !defined(MBEDTLS_SSL_PROTO_TLS1_2) || !defined(MBEDTLS_SHA512_C)
01618     (void) hash;
01619 #endif
01620 
01621 #if defined(MBEDTLS_SSL_PROTO_SSL3)
01622     if( minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
01623     {
01624         handshake->tls_prf = ssl3_prf;
01625         handshake->calc_verify = ssl_calc_verify_ssl;
01626         handshake->calc_finished = ssl_calc_finished_ssl;
01627     }
01628     else
01629 #endif
01630 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
01631     if( minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 )
01632     {
01633         handshake->tls_prf = tls1_prf;
01634         handshake->calc_verify = ssl_calc_verify_tls;
01635         handshake->calc_finished = ssl_calc_finished_tls;
01636     }
01637     else
01638 #endif
01639 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
01640 #if defined(MBEDTLS_SHA512_C)
01641     if( minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 &&
01642         hash == MBEDTLS_MD_SHA384 )
01643     {
01644         handshake->tls_prf = tls_prf_sha384;
01645         handshake->calc_verify = ssl_calc_verify_tls_sha384;
01646         handshake->calc_finished = ssl_calc_finished_tls_sha384;
01647     }
01648     else
01649 #endif
01650 #if defined(MBEDTLS_SHA256_C)
01651     if( minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
01652     {
01653         handshake->tls_prf = tls_prf_sha256;
01654         handshake->calc_verify = ssl_calc_verify_tls_sha256;
01655         handshake->calc_finished = ssl_calc_finished_tls_sha256;
01656     }
01657     else
01658 #endif
01659 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
01660     {
01661         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
01662     }
01663 
01664     return( 0 );
01665 }
01666 
01667 /*
01668  * Compute master secret if needed
01669  *
01670  * Parameters:
01671  * [in/out] handshake
01672  *          [in] resume, premaster, extended_ms, calc_verify, tls_prf
01673  *               (PSA-PSK) ciphersuite_info, psk_opaque
01674  *          [out] premaster (cleared)
01675  * [out] master
01676  * [in] ssl: optionally used for debugging, EMS and PSA-PSK
01677  *      debug: conf->f_dbg, conf->p_dbg
01678  *      EMS: passed to calc_verify (debug + (SSL3) session_negotiate)
01679  *      PSA-PSA: minor_ver, conf
01680  */
01681 static int ssl_compute_master( mbedtls_ssl_handshake_params *handshake,
01682                                unsigned char *master,
01683                                const mbedtls_ssl_context *ssl )
01684 {
01685     int ret;
01686 
01687     /* cf. RFC 5246, Section 8.1:
01688      * "The master secret is always exactly 48 bytes in length." */
01689     size_t const master_secret_len = 48;
01690 
01691 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
01692     unsigned char session_hash[48];
01693 #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
01694 
01695     /* The label for the KDF used for key expansion.
01696      * This is either "master secret" or "extended master secret"
01697      * depending on whether the Extended Master Secret extension
01698      * is used. */
01699     char const *lbl = "master secret";
01700 
01701     /* The salt for the KDF used for key expansion.
01702      * - If the Extended Master Secret extension is not used,
01703      *   this is ClientHello.Random + ServerHello.Random
01704      *   (see Sect. 8.1 in RFC 5246).
01705      * - If the Extended Master Secret extension is used,
01706      *   this is the transcript of the handshake so far.
01707      *   (see Sect. 4 in RFC 7627). */
01708     unsigned char const *salt = handshake->randbytes;
01709     size_t salt_len = 64;
01710 
01711 #if !defined(MBEDTLS_DEBUG_C) &&                    \
01712     !defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) && \
01713     !(defined(MBEDTLS_USE_PSA_CRYPTO) &&            \
01714       defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED))
01715     ssl = NULL; /* make sure we don't use it except for those cases */
01716     (void) ssl;
01717 #endif
01718 
01719     if( handshake->resume != 0 )
01720     {
01721         MBEDTLS_SSL_DEBUG_MSG( 3, ( "no premaster (session resumed)" ) );
01722         return( 0 );
01723     }
01724 
01725 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
01726     if( handshake->extended_ms == MBEDTLS_SSL_EXTENDED_MS_ENABLED )
01727     {
01728         lbl  = "extended master secret";
01729         salt = session_hash;
01730         handshake->calc_verify( ssl, session_hash, &salt_len );
01731 
01732         MBEDTLS_SSL_DEBUG_BUF( 3, "session hash for extended master secret",
01733                                   session_hash, salt_len );
01734     }
01735 #endif /* MBEDTLS_SSL_EXTENDED_MS_ENABLED */
01736 
01737 #if defined(MBEDTLS_USE_PSA_CRYPTO) &&          \
01738     defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
01739     if( handshake->ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK &&
01740         ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 &&
01741         ssl_use_opaque_psk( ssl ) == 1 )
01742     {
01743         /* Perform PSK-to-MS expansion in a single step. */
01744         psa_status_t status;
01745         psa_algorithm_t alg;
01746         psa_key_handle_t psk;
01747         psa_key_derivation_operation_t derivation =
01748             PSA_KEY_DERIVATION_OPERATION_INIT;
01749         mbedtls_md_type_t hash_alg = handshake->ciphersuite_info->mac;
01750 
01751         MBEDTLS_SSL_DEBUG_MSG( 2, ( "perform PSA-based PSK-to-MS expansion" ) );
01752 
01753         psk = ssl->conf->psk_opaque;
01754         if( handshake->psk_opaque != 0 )
01755             psk = handshake->psk_opaque;
01756 
01757         if( hash_alg == MBEDTLS_MD_SHA384 )
01758             alg = PSA_ALG_TLS12_PSK_TO_MS(PSA_ALG_SHA_384);
01759         else
01760             alg = PSA_ALG_TLS12_PSK_TO_MS(PSA_ALG_SHA_256);
01761 
01762         status = setup_psa_key_derivation( &derivation, psk, alg,
01763                                            salt, salt_len,
01764                                            (unsigned char const *) lbl,
01765                                            (size_t) strlen( lbl ),
01766                                            master_secret_len );
01767         if( status != PSA_SUCCESS )
01768         {
01769             psa_key_derivation_abort( &derivation );
01770             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
01771         }
01772 
01773         status = psa_key_derivation_output_bytes( &derivation,
01774                                                   master,
01775                                                   master_secret_len );
01776         if( status != PSA_SUCCESS )
01777         {
01778             psa_key_derivation_abort( &derivation );
01779             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
01780         }
01781 
01782         status = psa_key_derivation_abort( &derivation );
01783         if( status != PSA_SUCCESS )
01784             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
01785     }
01786     else
01787 #endif
01788     {
01789         ret = handshake->tls_prf( handshake->premaster, handshake->pmslen,
01790                                   lbl, salt, salt_len,
01791                                   master,
01792                                   master_secret_len );
01793         if( ret != 0 )
01794         {
01795             MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret );
01796             return( ret );
01797         }
01798 
01799         MBEDTLS_SSL_DEBUG_BUF( 3, "premaster secret",
01800                                handshake->premaster,
01801                                handshake->pmslen );
01802 
01803         mbedtls_platform_zeroize( handshake->premaster,
01804                                   sizeof(handshake->premaster) );
01805     }
01806 
01807     return( 0 );
01808 }
01809 
01810 int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl )
01811 {
01812     int ret;
01813     const mbedtls_ssl_ciphersuite_t * const ciphersuite_info =
01814         ssl->handshake->ciphersuite_info;
01815 
01816     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> derive keys" ) );
01817 
01818     /* Set PRF, calc_verify and calc_finished function pointers */
01819     ret = ssl_set_handshake_prfs( ssl->handshake,
01820                                   ssl->minor_ver,
01821                                   ciphersuite_info->mac );
01822     if( ret != 0 )
01823     {
01824         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_set_handshake_prfs", ret );
01825         return( ret );
01826     }
01827 
01828     /* Compute master secret if needed */
01829     ret = ssl_compute_master( ssl->handshake,
01830                               ssl->session_negotiate->master,
01831                               ssl );
01832     if( ret != 0 )
01833     {
01834         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_compute_master", ret );
01835         return( ret );
01836     }
01837 
01838     /* Swap the client and server random values:
01839      * - MS derivation wanted client+server (RFC 5246 8.1)
01840      * - key derivation wants server+client (RFC 5246 6.3) */
01841     {
01842         unsigned char tmp[64];
01843         memcpy( tmp, ssl->handshake->randbytes, 64 );
01844         memcpy( ssl->handshake->randbytes, tmp + 32, 32 );
01845         memcpy( ssl->handshake->randbytes + 32, tmp, 32 );
01846         mbedtls_platform_zeroize( tmp, sizeof( tmp ) );
01847     }
01848 
01849     /* Populate transform structure */
01850     ret = ssl_populate_transform( ssl->transform_negotiate,
01851                                   ssl->session_negotiate->ciphersuite,
01852                                   ssl->session_negotiate->master,
01853 #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
01854 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
01855                                   ssl->session_negotiate->encrypt_then_mac,
01856 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
01857 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
01858                                   ssl->session_negotiate->trunc_hmac,
01859 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
01860 #endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */
01861 #if defined(MBEDTLS_ZLIB_SUPPORT)
01862                                   ssl->session_negotiate->compression,
01863 #endif
01864                                   ssl->handshake->tls_prf,
01865                                   ssl->handshake->randbytes,
01866                                   ssl->minor_ver,
01867                                   ssl->conf->endpoint,
01868                                   ssl );
01869     if( ret != 0 )
01870     {
01871         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_populate_transform", ret );
01872         return( ret );
01873     }
01874 
01875     /* We no longer need Server/ClientHello.random values */
01876     mbedtls_platform_zeroize( ssl->handshake->randbytes,
01877                       sizeof( ssl->handshake->randbytes ) );
01878 
01879     /* Allocate compression buffer */
01880 #if defined(MBEDTLS_ZLIB_SUPPORT)
01881     if( session->compression == MBEDTLS_SSL_COMPRESS_DEFLATE &&
01882         ssl->compress_buf == NULL )
01883     {
01884         MBEDTLS_SSL_DEBUG_MSG( 3, ( "Allocating compression buffer" ) );
01885         ssl->compress_buf = mbedtls_calloc( 1, MBEDTLS_SSL_COMPRESS_BUFFER_LEN );
01886         if( ssl->compress_buf == NULL )
01887         {
01888             MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed",
01889                                         MBEDTLS_SSL_COMPRESS_BUFFER_LEN ) );
01890             return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
01891         }
01892     }
01893 #endif
01894 
01895     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= derive keys" ) );
01896 
01897     return( 0 );
01898 }
01899 
01900 #if defined(MBEDTLS_SSL_PROTO_SSL3)
01901 void ssl_calc_verify_ssl( const mbedtls_ssl_context *ssl,
01902                           unsigned char hash[36],
01903                           size_t *hlen )
01904 {
01905     mbedtls_md5_context md5;
01906     mbedtls_sha1_context sha1;
01907     unsigned char pad_1[48];
01908     unsigned char pad_2[48];
01909 
01910     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify ssl" ) );
01911 
01912     mbedtls_md5_init( &md5 );
01913     mbedtls_sha1_init( &sha1 );
01914 
01915     mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
01916     mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
01917 
01918     memset( pad_1, 0x36, 48 );
01919     memset( pad_2, 0x5C, 48 );
01920 
01921     mbedtls_md5_update_ret( &md5, ssl->session_negotiate->master, 48 );
01922     mbedtls_md5_update_ret( &md5, pad_1, 48 );
01923     mbedtls_md5_finish_ret( &md5, hash );
01924 
01925     mbedtls_md5_starts_ret( &md5 );
01926     mbedtls_md5_update_ret( &md5, ssl->session_negotiate->master, 48 );
01927     mbedtls_md5_update_ret( &md5, pad_2, 48 );
01928     mbedtls_md5_update_ret( &md5, hash,  16 );
01929     mbedtls_md5_finish_ret( &md5, hash );
01930 
01931     mbedtls_sha1_update_ret( &sha1, ssl->session_negotiate->master, 48 );
01932     mbedtls_sha1_update_ret( &sha1, pad_1, 40 );
01933     mbedtls_sha1_finish_ret( &sha1, hash + 16 );
01934 
01935     mbedtls_sha1_starts_ret( &sha1 );
01936     mbedtls_sha1_update_ret( &sha1, ssl->session_negotiate->master, 48 );
01937     mbedtls_sha1_update_ret( &sha1, pad_2, 40 );
01938     mbedtls_sha1_update_ret( &sha1, hash + 16, 20 );
01939     mbedtls_sha1_finish_ret( &sha1, hash + 16 );
01940 
01941     *hlen = 36;
01942 
01943     MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, *hlen );
01944     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
01945 
01946     mbedtls_md5_free(  &md5  );
01947     mbedtls_sha1_free( &sha1 );
01948 
01949     return;
01950 }
01951 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
01952 
01953 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
01954 void ssl_calc_verify_tls( const mbedtls_ssl_context *ssl,
01955                           unsigned char hash[36],
01956                           size_t *hlen )
01957 {
01958     mbedtls_md5_context md5;
01959     mbedtls_sha1_context sha1;
01960 
01961     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify tls" ) );
01962 
01963     mbedtls_md5_init( &md5 );
01964     mbedtls_sha1_init( &sha1 );
01965 
01966     mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
01967     mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
01968 
01969     mbedtls_md5_finish_ret( &md5,  hash );
01970     mbedtls_sha1_finish_ret( &sha1, hash + 16 );
01971 
01972     *hlen = 36;
01973 
01974     MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, *hlen );
01975     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
01976 
01977     mbedtls_md5_free(  &md5  );
01978     mbedtls_sha1_free( &sha1 );
01979 
01980     return;
01981 }
01982 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
01983 
01984 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
01985 #if defined(MBEDTLS_SHA256_C)
01986 void ssl_calc_verify_tls_sha256( const mbedtls_ssl_context *ssl,
01987                                  unsigned char hash[32],
01988                                  size_t *hlen )
01989 {
01990 #if defined(MBEDTLS_USE_PSA_CRYPTO)
01991     size_t hash_size;
01992     psa_status_t status;
01993     psa_hash_operation_t sha256_psa = psa_hash_operation_init();
01994 
01995     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> PSA calc verify sha256" ) );
01996     status = psa_hash_clone( &ssl->handshake->fin_sha256_psa, &sha256_psa );
01997     if( status != PSA_SUCCESS )
01998     {
01999         MBEDTLS_SSL_DEBUG_MSG( 2, ( "PSA hash clone failed" ) );
02000         return;
02001     }
02002 
02003     status = psa_hash_finish( &sha256_psa, hash, 32, &hash_size );
02004     if( status != PSA_SUCCESS )
02005     {
02006         MBEDTLS_SSL_DEBUG_MSG( 2, ( "PSA hash finish failed" ) );
02007         return;
02008     }
02009 
02010     *hlen = 32;
02011     MBEDTLS_SSL_DEBUG_BUF( 3, "PSA calculated verify result", hash, *hlen );
02012     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= PSA calc verify" ) );
02013 #else
02014     mbedtls_sha256_context sha256;
02015 
02016     mbedtls_sha256_init( &sha256 );
02017 
02018     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify sha256" ) );
02019 
02020     mbedtls_sha256_clone( &sha256, &ssl->handshake->fin_sha256 );
02021     mbedtls_sha256_finish_ret( &sha256, hash );
02022 
02023     *hlen = 32;
02024 
02025     MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, *hlen );
02026     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
02027 
02028     mbedtls_sha256_free( &sha256 );
02029 #endif /* MBEDTLS_USE_PSA_CRYPTO */
02030     return;
02031 }
02032 #endif /* MBEDTLS_SHA256_C */
02033 
02034 #if defined(MBEDTLS_SHA512_C)
02035 void ssl_calc_verify_tls_sha384( const mbedtls_ssl_context *ssl,
02036                                  unsigned char hash[48],
02037                                  size_t *hlen )
02038 {
02039 #if defined(MBEDTLS_USE_PSA_CRYPTO)
02040     size_t hash_size;
02041     psa_status_t status;
02042     psa_hash_operation_t sha384_psa = psa_hash_operation_init();
02043 
02044     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> PSA calc verify sha384" ) );
02045     status = psa_hash_clone( &ssl->handshake->fin_sha384_psa, &sha384_psa );
02046     if( status != PSA_SUCCESS )
02047     {
02048         MBEDTLS_SSL_DEBUG_MSG( 2, ( "PSA hash clone failed" ) );
02049         return;
02050     }
02051 
02052     status = psa_hash_finish( &sha384_psa, hash, 48, &hash_size );
02053     if( status != PSA_SUCCESS )
02054     {
02055         MBEDTLS_SSL_DEBUG_MSG( 2, ( "PSA hash finish failed" ) );
02056         return;
02057     }
02058 
02059     *hlen = 48;
02060     MBEDTLS_SSL_DEBUG_BUF( 3, "PSA calculated verify result", hash, *hlen );
02061     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= PSA calc verify" ) );
02062 #else
02063     mbedtls_sha512_context sha512;
02064 
02065     mbedtls_sha512_init( &sha512 );
02066 
02067     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify sha384" ) );
02068 
02069     mbedtls_sha512_clone( &sha512, &ssl->handshake->fin_sha512 );
02070     mbedtls_sha512_finish_ret( &sha512, hash );
02071 
02072     *hlen = 48;
02073 
02074     MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, *hlen );
02075     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) );
02076 
02077     mbedtls_sha512_free( &sha512 );
02078 #endif /* MBEDTLS_USE_PSA_CRYPTO */
02079     return;
02080 }
02081 #endif /* MBEDTLS_SHA512_C */
02082 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
02083 
02084 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
02085 int mbedtls_ssl_psk_derive_premaster( mbedtls_ssl_context *ssl, mbedtls_key_exchange_type_t key_ex )
02086 {
02087     unsigned char *p = ssl->handshake->premaster;
02088     unsigned char *end = p + sizeof( ssl->handshake->premaster );
02089     const unsigned char *psk = ssl->conf->psk;
02090     size_t psk_len = ssl->conf->psk_len;
02091 
02092     /* If the psk callback was called, use its result */
02093     if( ssl->handshake->psk != NULL )
02094     {
02095         psk = ssl->handshake->psk;
02096         psk_len = ssl->handshake->psk_len;
02097     }
02098 
02099     /*
02100      * PMS = struct {
02101      *     opaque other_secret<0..2^16-1>;
02102      *     opaque psk<0..2^16-1>;
02103      * };
02104      * with "other_secret" depending on the particular key exchange
02105      */
02106 #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
02107     if( key_ex == MBEDTLS_KEY_EXCHANGE_PSK )
02108     {
02109         if( end - p < 2 )
02110             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
02111 
02112         *(p++) = (unsigned char)( psk_len >> 8 );
02113         *(p++) = (unsigned char)( psk_len      );
02114 
02115         if( end < p || (size_t)( end - p ) < psk_len )
02116             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
02117 
02118         memset( p, 0, psk_len );
02119         p += psk_len;
02120     }
02121     else
02122 #endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */
02123 #if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
02124     if( key_ex == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
02125     {
02126         /*
02127          * other_secret already set by the ClientKeyExchange message,
02128          * and is 48 bytes long
02129          */
02130         if( end - p < 2 )
02131             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
02132 
02133         *p++ = 0;
02134         *p++ = 48;
02135         p += 48;
02136     }
02137     else
02138 #endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
02139 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
02140     if( key_ex == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
02141     {
02142         int ret;
02143         size_t len;
02144 
02145         /* Write length only when we know the actual value */
02146         if( ( ret = mbedtls_dhm_calc_secret( &ssl->handshake->dhm_ctx,
02147                                       p + 2, end - ( p + 2 ), &len,
02148                                       ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
02149         {
02150             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_calc_secret", ret );
02151             return( ret );
02152         }
02153         *(p++) = (unsigned char)( len >> 8 );
02154         *(p++) = (unsigned char)( len );
02155         p += len;
02156 
02157         MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: K ", &ssl->handshake->dhm_ctx.K  );
02158     }
02159     else
02160 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
02161 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
02162     if( key_ex == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
02163     {
02164         int ret;
02165         size_t zlen;
02166 
02167         if( ( ret = mbedtls_ecdh_calc_secret( &ssl->handshake->ecdh_ctx, &zlen,
02168                                        p + 2, end - ( p + 2 ),
02169                                        ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
02170         {
02171             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_calc_secret", ret );
02172             return( ret );
02173         }
02174 
02175         *(p++) = (unsigned char)( zlen >> 8 );
02176         *(p++) = (unsigned char)( zlen      );
02177         p += zlen;
02178 
02179         MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx,
02180                                 MBEDTLS_DEBUG_ECDH_Z );
02181     }
02182     else
02183 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
02184     {
02185         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
02186         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
02187     }
02188 
02189     /* opaque psk<0..2^16-1>; */
02190     if( end - p < 2 )
02191         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
02192 
02193     *(p++) = (unsigned char)( psk_len >> 8 );
02194     *(p++) = (unsigned char)( psk_len      );
02195 
02196     if( end < p || (size_t)( end - p ) < psk_len )
02197         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
02198 
02199     memcpy( p, psk, psk_len );
02200     p += psk_len;
02201 
02202     ssl->handshake->pmslen = p - ssl->handshake->premaster;
02203 
02204     return( 0 );
02205 }
02206 #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
02207 
02208 #if defined(MBEDTLS_SSL_PROTO_SSL3)
02209 /*
02210  * SSLv3.0 MAC functions
02211  */
02212 #define SSL_MAC_MAX_BYTES   20  /* MD-5 or SHA-1 */
02213 static void ssl_mac( mbedtls_md_context_t *md_ctx,
02214                      const unsigned char *secret,
02215                      const unsigned char *buf, size_t len,
02216                      const unsigned char *ctr, int type,
02217                      unsigned char out[SSL_MAC_MAX_BYTES] )
02218 {
02219     unsigned char header[11];
02220     unsigned char padding[48];
02221     int padlen;
02222     int md_size = mbedtls_md_get_size( md_ctx->md_info );
02223     int md_type = mbedtls_md_get_type( md_ctx->md_info );
02224 
02225     /* Only MD5 and SHA-1 supported */
02226     if( md_type == MBEDTLS_MD_MD5 )
02227         padlen = 48;
02228     else
02229         padlen = 40;
02230 
02231     memcpy( header, ctr, 8 );
02232     header[ 8] = (unsigned char)  type;
02233     header[ 9] = (unsigned char)( len >> 8 );
02234     header[10] = (unsigned char)( len      );
02235 
02236     memset( padding, 0x36, padlen );
02237     mbedtls_md_starts( md_ctx );
02238     mbedtls_md_update( md_ctx, secret,  md_size );
02239     mbedtls_md_update( md_ctx, padding, padlen  );
02240     mbedtls_md_update( md_ctx, header,  11      );
02241     mbedtls_md_update( md_ctx, buf,     len     );
02242     mbedtls_md_finish( md_ctx, out              );
02243 
02244     memset( padding, 0x5C, padlen );
02245     mbedtls_md_starts( md_ctx );
02246     mbedtls_md_update( md_ctx, secret,    md_size );
02247     mbedtls_md_update( md_ctx, padding,   padlen  );
02248     mbedtls_md_update( md_ctx, out,       md_size );
02249     mbedtls_md_finish( md_ctx, out                );
02250 }
02251 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
02252 
02253 /* The function below is only used in the Lucky 13 counter-measure in
02254  * mbedtls_ssl_decrypt_buf(). These are the defines that guard the call site. */
02255 #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC) && \
02256     ( defined(MBEDTLS_SSL_PROTO_TLS1) || \
02257       defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
02258       defined(MBEDTLS_SSL_PROTO_TLS1_2) )
02259 /* This function makes sure every byte in the memory region is accessed
02260  * (in ascending addresses order) */
02261 static void ssl_read_memory( unsigned char *p, size_t len )
02262 {
02263     unsigned char acc = 0;
02264     volatile unsigned char force;
02265 
02266     for( ; len != 0; p++, len-- )
02267         acc ^= *p;
02268 
02269     force = acc;
02270     (void) force;
02271 }
02272 #endif /* SSL_SOME_MODES_USE_MAC && ( TLS1 || TLS1_1 || TLS1_2 ) */
02273 
02274 /*
02275  * Encryption/decryption functions
02276  */
02277 
02278 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
02279 /* This functions transforms a DTLS plaintext fragment and a record content
02280  * type into an instance of the DTLSInnerPlaintext structure:
02281  *
02282  *        struct {
02283  *            opaque content[DTLSPlaintext.length];
02284  *            ContentType real_type;
02285  *            uint8 zeros[length_of_padding];
02286  *        } DTLSInnerPlaintext;
02287  *
02288  *  Input:
02289  *  - `content`: The beginning of the buffer holding the
02290  *               plaintext to be wrapped.
02291  *  - `*content_size`: The length of the plaintext in Bytes.
02292  *  - `max_len`: The number of Bytes available starting from
02293  *               `content`. This must be `>= *content_size`.
02294  *  - `rec_type`: The desired record content type.
02295  *
02296  *  Output:
02297  *  - `content`: The beginning of the resulting DTLSInnerPlaintext structure.
02298  *  - `*content_size`: The length of the resulting DTLSInnerPlaintext structure.
02299  *
02300  *  Returns:
02301  *  - `0` on success.
02302  *  - A negative error code if `max_len` didn't offer enough space
02303  *    for the expansion.
02304  */
02305 static int ssl_cid_build_inner_plaintext( unsigned char *content,
02306                                           size_t *content_size,
02307                                           size_t remaining,
02308                                           uint8_t rec_type )
02309 {
02310     size_t len = *content_size;
02311     size_t pad = ( MBEDTLS_SSL_CID_PADDING_GRANULARITY -
02312                    ( len + 1 ) % MBEDTLS_SSL_CID_PADDING_GRANULARITY ) %
02313         MBEDTLS_SSL_CID_PADDING_GRANULARITY;
02314 
02315     /* Write real content type */
02316     if( remaining == 0 )
02317         return( -1 );
02318     content[ len ] = rec_type;
02319     len++;
02320     remaining--;
02321 
02322     if( remaining < pad )
02323         return( -1 );
02324     memset( content + len, 0, pad );
02325     len += pad;
02326     remaining -= pad;
02327 
02328     *content_size = len;
02329     return( 0 );
02330 }
02331 
02332 /* This function parses a DTLSInnerPlaintext structure.
02333  * See ssl_cid_build_inner_plaintext() for details. */
02334 static int ssl_cid_parse_inner_plaintext( unsigned char const *content,
02335                                           size_t *content_size,
02336                                           uint8_t *rec_type )
02337 {
02338     size_t remaining = *content_size;
02339 
02340     /* Determine length of padding by skipping zeroes from the back. */
02341     do
02342     {
02343         if( remaining == 0 )
02344             return( -1 );
02345         remaining--;
02346     } while( content[ remaining ] == 0 );
02347 
02348     *content_size = remaining;
02349     *rec_type = content[ remaining ];
02350 
02351     return( 0 );
02352 }
02353 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
02354 
02355 /* `add_data` must have size 13 Bytes if the CID extension is disabled,
02356  * and 13 + 1 + CID-length Bytes if the CID extension is enabled. */
02357 static void ssl_extract_add_data_from_record( unsigned char* add_data,
02358                                               size_t *add_data_len,
02359                                               mbedtls_record *rec )
02360 {
02361     /* Quoting RFC 5246 (TLS 1.2):
02362      *
02363      *    additional_data = seq_num + TLSCompressed.type +
02364      *                      TLSCompressed.version + TLSCompressed.length;
02365      *
02366      * For the CID extension, this is extended as follows
02367      * (quoting draft-ietf-tls-dtls-connection-id-05,
02368      *  https://tools.ietf.org/html/draft-ietf-tls-dtls-connection-id-05):
02369      *
02370      *       additional_data = seq_num + DTLSPlaintext.type +
02371      *                         DTLSPlaintext.version +
02372      *                         cid +
02373      *                         cid_length +
02374      *                         length_of_DTLSInnerPlaintext;
02375      */
02376 
02377     memcpy( add_data, rec->ctr, sizeof( rec->ctr ) );
02378     add_data[8] = rec->type;
02379     memcpy( add_data + 9, rec->ver, sizeof( rec->ver ) );
02380 
02381 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
02382     if( rec->cid_len != 0 )
02383     {
02384         memcpy( add_data + 11, rec->cid, rec->cid_len );
02385         add_data[11 + rec->cid_len + 0] = rec->cid_len;
02386         add_data[11 + rec->cid_len + 1] = ( rec->data_len >> 8 ) & 0xFF;
02387         add_data[11 + rec->cid_len + 2] = ( rec->data_len >> 0 ) & 0xFF;
02388         *add_data_len = 13 + 1 + rec->cid_len;
02389     }
02390     else
02391 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
02392     {
02393         add_data[11 + 0] = ( rec->data_len >> 8 ) & 0xFF;
02394         add_data[11 + 1] = ( rec->data_len >> 0 ) & 0xFF;
02395         *add_data_len = 13;
02396     }
02397 }
02398 
02399 int mbedtls_ssl_encrypt_buf( mbedtls_ssl_context *ssl,
02400                              mbedtls_ssl_transform *transform,
02401                              mbedtls_record *rec,
02402                              int (*f_rng)(void *, unsigned char *, size_t),
02403                              void *p_rng )
02404 {
02405     mbedtls_cipher_mode_t mode;
02406     int auth_done = 0;
02407     unsigned char * data;
02408     unsigned char add_data[13 + 1 + MBEDTLS_SSL_CID_OUT_LEN_MAX ];
02409     size_t add_data_len;
02410     size_t post_avail;
02411 
02412     /* The SSL context is only used for debugging purposes! */
02413 #if !defined(MBEDTLS_DEBUG_C)
02414     ssl = NULL; /* make sure we don't use it except for debug */
02415     ((void) ssl);
02416 #endif
02417 
02418     /* The PRNG is used for dynamic IV generation that's used
02419      * for CBC transformations in TLS 1.1 and TLS 1.2. */
02420 #if !( defined(MBEDTLS_CIPHER_MODE_CBC) &&                              \
02421        ( defined(MBEDTLS_AES_C)  ||                                     \
02422          defined(MBEDTLS_ARIA_C) ||                                     \
02423          defined(MBEDTLS_CAMELLIA_C) ) &&                               \
02424        ( defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2) ) )
02425     ((void) f_rng);
02426     ((void) p_rng);
02427 #endif
02428 
02429     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> encrypt buf" ) );
02430 
02431     if( transform == NULL )
02432     {
02433         MBEDTLS_SSL_DEBUG_MSG( 1, ( "no transform provided to encrypt_buf" ) );
02434         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
02435     }
02436     if( rec == NULL
02437         || rec->buf == NULL
02438         || rec->buf_len < rec->data_offset
02439         || rec->buf_len - rec->data_offset < rec->data_len
02440 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
02441         || rec->cid_len != 0
02442 #endif
02443         )
02444     {
02445         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad record structure provided to encrypt_buf" ) );
02446         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
02447     }
02448 
02449     data = rec->buf + rec->data_offset;
02450     post_avail = rec->buf_len - ( rec->data_len + rec->data_offset );
02451     MBEDTLS_SSL_DEBUG_BUF( 4, "before encrypt: output payload",
02452                            data, rec->data_len );
02453 
02454     mode = mbedtls_cipher_get_cipher_mode( &transform->cipher_ctx_enc );
02455 
02456     if( rec->data_len > MBEDTLS_SSL_OUT_CONTENT_LEN )
02457     {
02458         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Record content %u too large, maximum %d",
02459                                     (unsigned) rec->data_len,
02460                                     MBEDTLS_SSL_OUT_CONTENT_LEN ) );
02461         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
02462     }
02463 
02464 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
02465     /*
02466      * Add CID information
02467      */
02468     rec->cid_len = transform->out_cid_len;
02469     memcpy( rec->cid, transform->out_cid, transform->out_cid_len );
02470     MBEDTLS_SSL_DEBUG_BUF( 3, "CID", rec->cid, rec->cid_len );
02471 
02472     if( rec->cid_len != 0 )
02473     {
02474         /*
02475          * Wrap plaintext into DTLSInnerPlaintext structure.
02476          * See ssl_cid_build_inner_plaintext() for more information.
02477          *
02478          * Note that this changes `rec->data_len`, and hence
02479          * `post_avail` needs to be recalculated afterwards.
02480          */
02481         if( ssl_cid_build_inner_plaintext( data,
02482                         &rec->data_len,
02483                         post_avail,
02484                         rec->type ) != 0 )
02485         {
02486             return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
02487         }
02488 
02489         rec->type = MBEDTLS_SSL_MSG_CID;
02490     }
02491 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
02492 
02493     post_avail = rec->buf_len - ( rec->data_len + rec->data_offset );
02494 
02495     /*
02496      * Add MAC before if needed
02497      */
02498 #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
02499     if( mode == MBEDTLS_MODE_STREAM ||
02500         ( mode == MBEDTLS_MODE_CBC
02501 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
02502           && transform->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED
02503 #endif
02504         ) )
02505     {
02506         if( post_avail < transform->maclen )
02507         {
02508             MBEDTLS_SSL_DEBUG_MSG( 1, ( "Buffer provided for encrypted record not large enough" ) );
02509             return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
02510         }
02511 
02512 #if defined(MBEDTLS_SSL_PROTO_SSL3)
02513         if( transform->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
02514         {
02515             unsigned char mac[SSL_MAC_MAX_BYTES];
02516             ssl_mac( &transform->md_ctx_enc, transform->mac_enc,
02517                      data, rec->data_len, rec->ctr, rec->type, mac );
02518             memcpy( data + rec->data_len, mac, transform->maclen );
02519         }
02520         else
02521 #endif
02522 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
02523         defined(MBEDTLS_SSL_PROTO_TLS1_2)
02524         if( transform->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 )
02525         {
02526             unsigned char mac[MBEDTLS_SSL_MAC_ADD];
02527 
02528             ssl_extract_add_data_from_record( add_data, &add_data_len, rec );
02529 
02530             mbedtls_md_hmac_update( &transform->md_ctx_enc, add_data,
02531                                     add_data_len );
02532             mbedtls_md_hmac_update( &transform->md_ctx_enc,
02533                                     data, rec->data_len );
02534             mbedtls_md_hmac_finish( &transform->md_ctx_enc, mac );
02535             mbedtls_md_hmac_reset( &transform->md_ctx_enc );
02536 
02537             memcpy( data + rec->data_len, mac, transform->maclen );
02538         }
02539         else
02540 #endif
02541         {
02542             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
02543             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
02544         }
02545 
02546         MBEDTLS_SSL_DEBUG_BUF( 4, "computed mac", data + rec->data_len,
02547                                transform->maclen );
02548 
02549         rec->data_len += transform->maclen;
02550         post_avail -= transform->maclen;
02551         auth_done++;
02552     }
02553 #endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */
02554 
02555     /*
02556      * Encrypt
02557      */
02558 #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER)
02559     if( mode == MBEDTLS_MODE_STREAM )
02560     {
02561         int ret;
02562         size_t olen;
02563         MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
02564                                     "including %d bytes of padding",
02565                                     rec->data_len, 0 ) );
02566 
02567         if( ( ret = mbedtls_cipher_crypt( &transform->cipher_ctx_enc,
02568                                    transform->iv_enc, transform->ivlen,
02569                                    data, rec->data_len,
02570                                    data, &olen ) ) != 0 )
02571         {
02572             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
02573             return( ret );
02574         }
02575 
02576         if( rec->data_len != olen )
02577         {
02578             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
02579             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
02580         }
02581     }
02582     else
02583 #endif /* MBEDTLS_ARC4_C || MBEDTLS_CIPHER_NULL_CIPHER */
02584 
02585 #if defined(MBEDTLS_GCM_C) || \
02586     defined(MBEDTLS_CCM_C) || \
02587     defined(MBEDTLS_CHACHAPOLY_C)
02588     if( mode == MBEDTLS_MODE_GCM ||
02589         mode == MBEDTLS_MODE_CCM ||
02590         mode == MBEDTLS_MODE_CHACHAPOLY )
02591     {
02592         int ret;
02593         unsigned char iv[12];
02594         size_t explicit_iv_len = transform->ivlen - transform->fixed_ivlen;
02595 
02596         /* Check that there's space for both the authentication tag
02597          * and the explicit IV before and after the record content. */
02598         if( post_avail < transform->taglen ||
02599             rec->data_offset < explicit_iv_len )
02600         {
02601             MBEDTLS_SSL_DEBUG_MSG( 1, ( "Buffer provided for encrypted record not large enough" ) );
02602             return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
02603         }
02604 
02605         /*
02606          * Generate IV
02607          */
02608         if( transform->ivlen == 12 && transform->fixed_ivlen == 4 )
02609         {
02610             /* GCM and CCM: fixed || explicit (=seqnum) */
02611             memcpy( iv, transform->iv_enc, transform->fixed_ivlen );
02612             memcpy( iv + transform->fixed_ivlen, rec->ctr,
02613                     explicit_iv_len );
02614             /* Prefix record content with explicit IV. */
02615             memcpy( data - explicit_iv_len, rec->ctr, explicit_iv_len );
02616         }
02617         else if( transform->ivlen == 12 && transform->fixed_ivlen == 12 )
02618         {
02619             /* ChachaPoly: fixed XOR sequence number */
02620             unsigned char i;
02621 
02622             memcpy( iv, transform->iv_enc, transform->fixed_ivlen );
02623 
02624             for( i = 0; i < 8; i++ )
02625                 iv[i+4] ^= rec->ctr[i];
02626         }
02627         else
02628         {
02629             /* Reminder if we ever add an AEAD mode with a different size */
02630             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
02631             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
02632         }
02633 
02634         ssl_extract_add_data_from_record( add_data, &add_data_len, rec );
02635 
02636         MBEDTLS_SSL_DEBUG_BUF( 4, "IV used (internal)",
02637                                   iv, transform->ivlen );
02638         MBEDTLS_SSL_DEBUG_BUF( 4, "IV used (transmitted)",
02639                                   data - explicit_iv_len, explicit_iv_len );
02640         MBEDTLS_SSL_DEBUG_BUF( 4, "additional data used for AEAD",
02641                                add_data, add_data_len );
02642         MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
02643                                     "including 0 bytes of padding",
02644                                     rec->data_len ) );
02645 
02646         /*
02647          * Encrypt and authenticate
02648          */
02649 
02650         if( ( ret = mbedtls_cipher_auth_encrypt( &transform->cipher_ctx_enc,
02651                    iv, transform->ivlen,
02652                    add_data, add_data_len,       /* add data     */
02653                    data, rec->data_len,          /* source       */
02654                    data, &rec->data_len,         /* destination  */
02655                    data + rec->data_len, transform->taglen ) ) != 0 )
02656         {
02657             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_auth_encrypt", ret );
02658             return( ret );
02659         }
02660 
02661         MBEDTLS_SSL_DEBUG_BUF( 4, "after encrypt: tag",
02662                                data + rec->data_len, transform->taglen );
02663 
02664         rec->data_len    += transform->taglen + explicit_iv_len;
02665         rec->data_offset -= explicit_iv_len;
02666         post_avail -= transform->taglen;
02667         auth_done++;
02668     }
02669     else
02670 #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C */
02671 #if defined(MBEDTLS_CIPHER_MODE_CBC) &&                                    \
02672     ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_CAMELLIA_C) || defined(MBEDTLS_ARIA_C) )
02673     if( mode == MBEDTLS_MODE_CBC )
02674     {
02675         int ret;
02676         size_t padlen, i;
02677         size_t olen;
02678 
02679         /* Currently we're always using minimal padding
02680          * (up to 255 bytes would be allowed). */
02681         padlen = transform->ivlen - ( rec->data_len + 1 ) % transform->ivlen;
02682         if( padlen == transform->ivlen )
02683             padlen = 0;
02684 
02685         /* Check there's enough space in the buffer for the padding. */
02686         if( post_avail < padlen + 1 )
02687         {
02688             MBEDTLS_SSL_DEBUG_MSG( 1, ( "Buffer provided for encrypted record not large enough" ) );
02689             return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
02690         }
02691 
02692         for( i = 0; i <= padlen; i++ )
02693             data[rec->data_len + i] = (unsigned char) padlen;
02694 
02695         rec->data_len += padlen + 1;
02696         post_avail -= padlen + 1;
02697 
02698 #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
02699         /*
02700          * Prepend per-record IV for block cipher in TLS v1.1 and up as per
02701          * Method 1 (6.2.3.2. in RFC4346 and RFC5246)
02702          */
02703         if( transform->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
02704         {
02705             if( f_rng == NULL )
02706             {
02707                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "No PRNG provided to encrypt_record routine" ) );
02708                 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
02709             }
02710 
02711             if( rec->data_offset < transform->ivlen )
02712             {
02713                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Buffer provided for encrypted record not large enough" ) );
02714                 return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
02715             }
02716 
02717             /*
02718              * Generate IV
02719              */
02720             ret = f_rng( p_rng, transform->iv_enc, transform->ivlen );
02721             if( ret != 0 )
02722                 return( ret );
02723 
02724             memcpy( data - transform->ivlen, transform->iv_enc,
02725                     transform->ivlen );
02726 
02727         }
02728 #endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */
02729 
02730         MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
02731                             "including %d bytes of IV and %d bytes of padding",
02732                             rec->data_len, transform->ivlen,
02733                             padlen + 1 ) );
02734 
02735         if( ( ret = mbedtls_cipher_crypt( &transform->cipher_ctx_enc,
02736                                    transform->iv_enc,
02737                                    transform->ivlen,
02738                                    data, rec->data_len,
02739                                    data, &olen ) ) != 0 )
02740         {
02741             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
02742             return( ret );
02743         }
02744 
02745         if( rec->data_len != olen )
02746         {
02747             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
02748             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
02749         }
02750 
02751 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1)
02752         if( transform->minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 )
02753         {
02754             /*
02755              * Save IV in SSL3 and TLS1
02756              */
02757             memcpy( transform->iv_enc, transform->cipher_ctx_enc.iv,
02758                     transform->ivlen );
02759         }
02760         else
02761 #endif
02762         {
02763             data             -= transform->ivlen;
02764             rec->data_offset -= transform->ivlen;
02765             rec->data_len    += transform->ivlen;
02766         }
02767 
02768 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
02769         if( auth_done == 0 )
02770         {
02771             unsigned char mac[MBEDTLS_SSL_MAC_ADD];
02772 
02773             /*
02774              * MAC(MAC_write_key, seq_num +
02775              *     TLSCipherText.type +
02776              *     TLSCipherText.version +
02777              *     length_of( (IV +) ENC(...) ) +
02778              *     IV + // except for TLS 1.0
02779              *     ENC(content + padding + padding_length));
02780              */
02781 
02782             if( post_avail < transform->maclen)
02783             {
02784                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "Buffer provided for encrypted record not large enough" ) );
02785                 return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
02786             }
02787 
02788             ssl_extract_add_data_from_record( add_data, &add_data_len, rec );
02789 
02790             MBEDTLS_SSL_DEBUG_MSG( 3, ( "using encrypt then mac" ) );
02791             MBEDTLS_SSL_DEBUG_BUF( 4, "MAC'd meta-data", add_data,
02792                                    add_data_len );
02793 
02794             mbedtls_md_hmac_update( &transform->md_ctx_enc, add_data,
02795                                     add_data_len );
02796             mbedtls_md_hmac_update( &transform->md_ctx_enc,
02797                                     data, rec->data_len );
02798             mbedtls_md_hmac_finish( &transform->md_ctx_enc, mac );
02799             mbedtls_md_hmac_reset( &transform->md_ctx_enc );
02800 
02801             memcpy( data + rec->data_len, mac, transform->maclen );
02802 
02803             rec->data_len += transform->maclen;
02804             post_avail -= transform->maclen;
02805             auth_done++;
02806         }
02807 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
02808     }
02809     else
02810 #endif /* MBEDTLS_CIPHER_MODE_CBC &&
02811           ( MBEDTLS_AES_C || MBEDTLS_CAMELLIA_C || MBEDTLS_ARIA_C ) */
02812     {
02813         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
02814         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
02815     }
02816 
02817     /* Make extra sure authentication was performed, exactly once */
02818     if( auth_done != 1 )
02819     {
02820         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
02821         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
02822     }
02823 
02824     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= encrypt buf" ) );
02825 
02826     return( 0 );
02827 }
02828 
02829 int mbedtls_ssl_decrypt_buf( mbedtls_ssl_context const *ssl,
02830                              mbedtls_ssl_transform *transform,
02831                              mbedtls_record *rec )
02832 {
02833     size_t olen;
02834     mbedtls_cipher_mode_t mode;
02835     int ret, auth_done = 0;
02836 #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
02837     size_t padlen = 0, correct = 1;
02838 #endif
02839     unsigned char* data;
02840     unsigned char add_data[13 + 1 + MBEDTLS_SSL_CID_IN_LEN_MAX ];
02841     size_t add_data_len;
02842 
02843 #if !defined(MBEDTLS_DEBUG_C)
02844     ssl = NULL; /* make sure we don't use it except for debug */
02845     ((void) ssl);
02846 #endif
02847 
02848     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> decrypt buf" ) );
02849     if( rec == NULL                     ||
02850         rec->buf == NULL                ||
02851         rec->buf_len < rec->data_offset ||
02852         rec->buf_len - rec->data_offset < rec->data_len )
02853     {
02854         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad record structure provided to decrypt_buf" ) );
02855         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
02856     }
02857 
02858     data = rec->buf + rec->data_offset;
02859     mode = mbedtls_cipher_get_cipher_mode( &transform->cipher_ctx_dec );
02860 
02861 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
02862     /*
02863      * Match record's CID with incoming CID.
02864      */
02865     if( rec->cid_len != transform->in_cid_len ||
02866         memcmp( rec->cid, transform->in_cid, rec->cid_len ) != 0 )
02867     {
02868         return( MBEDTLS_ERR_SSL_UNEXPECTED_CID );
02869     }
02870 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
02871 
02872 #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER)
02873     if( mode == MBEDTLS_MODE_STREAM )
02874     {
02875         padlen = 0;
02876         if( ( ret = mbedtls_cipher_crypt( &transform->cipher_ctx_dec,
02877                                    transform->iv_dec,
02878                                    transform->ivlen,
02879                                    data, rec->data_len,
02880                                    data, &olen ) ) != 0 )
02881         {
02882             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
02883             return( ret );
02884         }
02885 
02886         if( rec->data_len != olen )
02887         {
02888             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
02889             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
02890         }
02891     }
02892     else
02893 #endif /* MBEDTLS_ARC4_C || MBEDTLS_CIPHER_NULL_CIPHER */
02894 #if defined(MBEDTLS_GCM_C) || \
02895     defined(MBEDTLS_CCM_C) || \
02896     defined(MBEDTLS_CHACHAPOLY_C)
02897     if( mode == MBEDTLS_MODE_GCM ||
02898         mode == MBEDTLS_MODE_CCM ||
02899         mode == MBEDTLS_MODE_CHACHAPOLY )
02900     {
02901         unsigned char iv[12];
02902         size_t explicit_iv_len = transform->ivlen - transform->fixed_ivlen;
02903 
02904         /*
02905          * Prepare IV from explicit and implicit data.
02906          */
02907 
02908         /* Check that there's enough space for the explicit IV
02909          * (at the beginning of the record) and the MAC (at the
02910          * end of the record). */
02911         if( rec->data_len < explicit_iv_len + transform->taglen )
02912         {
02913             MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < explicit_iv_len (%d) "
02914                                         "+ taglen (%d)", rec->data_len,
02915                                         explicit_iv_len, transform->taglen ) );
02916             return( MBEDTLS_ERR_SSL_INVALID_MAC );
02917         }
02918 
02919 #if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CCM_C)
02920         if( transform->ivlen == 12 && transform->fixed_ivlen == 4 )
02921         {
02922             /* GCM and CCM: fixed || explicit */
02923 
02924             /* Fixed */
02925             memcpy( iv, transform->iv_dec, transform->fixed_ivlen );
02926             /* Explicit */
02927             memcpy( iv + transform->fixed_ivlen, data, 8 );
02928         }
02929         else
02930 #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C */
02931 #if defined(MBEDTLS_CHACHAPOLY_C)
02932         if( transform->ivlen == 12 && transform->fixed_ivlen == 12 )
02933         {
02934             /* ChachaPoly: fixed XOR sequence number */
02935             unsigned char i;
02936 
02937             memcpy( iv, transform->iv_dec, transform->fixed_ivlen );
02938 
02939             for( i = 0; i < 8; i++ )
02940                 iv[i+4] ^= rec->ctr[i];
02941         }
02942         else
02943 #endif /* MBEDTLS_CHACHAPOLY_C */
02944         {
02945             /* Reminder if we ever add an AEAD mode with a different size */
02946             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
02947             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
02948         }
02949 
02950         /* Group changes to data, data_len, and add_data, because
02951          * add_data depends on data_len. */
02952         data += explicit_iv_len;
02953         rec->data_offset += explicit_iv_len;
02954         rec->data_len -= explicit_iv_len + transform->taglen;
02955 
02956         ssl_extract_add_data_from_record( add_data, &add_data_len, rec );
02957         MBEDTLS_SSL_DEBUG_BUF( 4, "additional data used for AEAD",
02958                                add_data, add_data_len );
02959 
02960         /* Because of the check above, we know that there are
02961          * explicit_iv_len Bytes preceeding data, and taglen
02962          * bytes following data + data_len. This justifies
02963          * the debug message and the invocation of
02964          * mbedtls_cipher_auth_decrypt() below. */
02965 
02966         MBEDTLS_SSL_DEBUG_BUF( 4, "IV used", iv, transform->ivlen );
02967         MBEDTLS_SSL_DEBUG_BUF( 4, "TAG used", data + rec->data_len,
02968                                transform->taglen );
02969 
02970         /*
02971          * Decrypt and authenticate
02972          */
02973         if( ( ret = mbedtls_cipher_auth_decrypt( &transform->cipher_ctx_dec,
02974                   iv, transform->ivlen,
02975                   add_data, add_data_len,
02976                   data, rec->data_len,
02977                   data, &olen,
02978                   data + rec->data_len,
02979                   transform->taglen ) ) != 0 )
02980         {
02981             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_auth_decrypt", ret );
02982 
02983             if( ret == MBEDTLS_ERR_CIPHER_AUTH_FAILED )
02984                 return( MBEDTLS_ERR_SSL_INVALID_MAC );
02985 
02986             return( ret );
02987         }
02988         auth_done++;
02989 
02990         /* Double-check that AEAD decryption doesn't change content length. */
02991         if( olen != rec->data_len )
02992         {
02993             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
02994             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
02995         }
02996     }
02997     else
02998 #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C */
02999 #if defined(MBEDTLS_CIPHER_MODE_CBC) &&                                    \
03000     ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_CAMELLIA_C) || defined(MBEDTLS_ARIA_C) )
03001     if( mode == MBEDTLS_MODE_CBC )
03002     {
03003         size_t minlen = 0;
03004 
03005         /*
03006          * Check immediate ciphertext sanity
03007          */
03008 #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
03009         if( transform->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
03010         {
03011             /* The ciphertext is prefixed with the CBC IV. */
03012             minlen += transform->ivlen;
03013         }
03014 #endif
03015 
03016         /* Size considerations:
03017          *
03018          * - The CBC cipher text must not be empty and hence
03019          *   at least of size transform->ivlen.
03020          *
03021          * Together with the potential IV-prefix, this explains
03022          * the first of the two checks below.
03023          *
03024          * - The record must contain a MAC, either in plain or
03025          *   encrypted, depending on whether Encrypt-then-MAC
03026          *   is used or not.
03027          *   - If it is, the message contains the IV-prefix,
03028          *     the CBC ciphertext, and the MAC.
03029          *   - If it is not, the padded plaintext, and hence
03030          *     the CBC ciphertext, has at least length maclen + 1
03031          *     because there is at least the padding length byte.
03032          *
03033          * As the CBC ciphertext is not empty, both cases give the
03034          * lower bound minlen + maclen + 1 on the record size, which
03035          * we test for in the second check below.
03036          */
03037         if( rec->data_len < minlen + transform->ivlen ||
03038             rec->data_len < minlen + transform->maclen + 1 )
03039         {
03040             MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < max( ivlen(%d), maclen (%d) "
03041                                 "+ 1 ) ( + expl IV )", rec->data_len,
03042                                 transform->ivlen,
03043                                 transform->maclen ) );
03044             return( MBEDTLS_ERR_SSL_INVALID_MAC );
03045         }
03046 
03047         /*
03048          * Authenticate before decrypt if enabled
03049          */
03050 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
03051         if( transform->encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED )
03052         {
03053             unsigned char mac_expect[MBEDTLS_SSL_MAC_ADD];
03054 
03055             MBEDTLS_SSL_DEBUG_MSG( 3, ( "using encrypt then mac" ) );
03056 
03057             /* Update data_len in tandem with add_data.
03058              *
03059              * The subtraction is safe because of the previous check
03060              * data_len >= minlen + maclen + 1.
03061              *
03062              * Afterwards, we know that data + data_len is followed by at
03063              * least maclen Bytes, which justifies the call to
03064              * mbedtls_ssl_safer_memcmp() below.
03065              *
03066              * Further, we still know that data_len > minlen */
03067             rec->data_len -= transform->maclen;
03068             ssl_extract_add_data_from_record( add_data, &add_data_len, rec );
03069 
03070             /* Calculate expected MAC. */
03071             MBEDTLS_SSL_DEBUG_BUF( 4, "MAC'd meta-data", add_data,
03072                                    add_data_len );
03073             mbedtls_md_hmac_update( &transform->md_ctx_dec, add_data,
03074                                     add_data_len );
03075             mbedtls_md_hmac_update( &transform->md_ctx_dec,
03076                                     data, rec->data_len );
03077             mbedtls_md_hmac_finish( &transform->md_ctx_dec, mac_expect );
03078             mbedtls_md_hmac_reset( &transform->md_ctx_dec );
03079 
03080             MBEDTLS_SSL_DEBUG_BUF( 4, "message  mac", data + rec->data_len,
03081                                    transform->maclen );
03082             MBEDTLS_SSL_DEBUG_BUF( 4, "expected mac", mac_expect,
03083                                    transform->maclen );
03084 
03085             /* Compare expected MAC with MAC at the end of the record. */
03086             if( mbedtls_ssl_safer_memcmp( data + rec->data_len, mac_expect,
03087                                           transform->maclen ) != 0 )
03088             {
03089                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "message mac does not match" ) );
03090                 return( MBEDTLS_ERR_SSL_INVALID_MAC );
03091             }
03092             auth_done++;
03093         }
03094 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
03095 
03096         /*
03097          * Check length sanity
03098          */
03099 
03100         /* We know from above that data_len > minlen >= 0,
03101          * so the following check in particular implies that
03102          * data_len >= minlen + ivlen ( = minlen or 2 * minlen ). */
03103         if( rec->data_len % transform->ivlen != 0 )
03104         {
03105             MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) %% ivlen (%d) != 0",
03106                                         rec->data_len, transform->ivlen ) );
03107             return( MBEDTLS_ERR_SSL_INVALID_MAC );
03108         }
03109 
03110 #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
03111         /*
03112          * Initialize for prepended IV for block cipher in TLS v1.1 and up
03113          */
03114         if( transform->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
03115         {
03116             /* Safe because data_len >= minlen + ivlen = 2 * ivlen. */
03117             memcpy( transform->iv_dec, data, transform->ivlen );
03118 
03119             data += transform->ivlen;
03120             rec->data_offset += transform->ivlen;
03121             rec->data_len -= transform->ivlen;
03122         }
03123 #endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */
03124 
03125         /* We still have data_len % ivlen == 0 and data_len >= ivlen here. */
03126 
03127         if( ( ret = mbedtls_cipher_crypt( &transform->cipher_ctx_dec,
03128                                    transform->iv_dec, transform->ivlen,
03129                                    data, rec->data_len, data, &olen ) ) != 0 )
03130         {
03131             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
03132             return( ret );
03133         }
03134 
03135         /* Double-check that length hasn't changed during decryption. */
03136         if( rec->data_len != olen )
03137         {
03138             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
03139             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
03140         }
03141 
03142 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1)
03143         if( transform->minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 )
03144         {
03145             /*
03146              * Save IV in SSL3 and TLS1, where CBC decryption of consecutive
03147              * records is equivalent to CBC decryption of the concatenation
03148              * of the records; in other words, IVs are maintained across
03149              * record decryptions.
03150              */
03151             memcpy( transform->iv_dec, transform->cipher_ctx_dec.iv,
03152                     transform->ivlen );
03153         }
03154 #endif
03155 
03156         /* Safe since data_len >= minlen + maclen + 1, so after having
03157          * subtracted at most minlen and maclen up to this point,
03158          * data_len > 0 (because of data_len % ivlen == 0, it's actually
03159          * >= ivlen ). */
03160         padlen = data[rec->data_len - 1];
03161 
03162         if( auth_done == 1 )
03163         {
03164             correct *= ( rec->data_len >= padlen + 1 );
03165             padlen  *= ( rec->data_len >= padlen + 1 );
03166         }
03167         else
03168         {
03169 #if defined(MBEDTLS_SSL_DEBUG_ALL)
03170             if( rec->data_len < transform->maclen + padlen + 1 )
03171             {
03172                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < maclen (%d) + padlen (%d)",
03173                                             rec->data_len,
03174                                             transform->maclen,
03175                                             padlen + 1 ) );
03176             }
03177 #endif
03178 
03179             correct *= ( rec->data_len >= transform->maclen + padlen + 1 );
03180             padlen  *= ( rec->data_len >= transform->maclen + padlen + 1 );
03181         }
03182 
03183         padlen++;
03184 
03185         /* Regardless of the validity of the padding,
03186          * we have data_len >= padlen here. */
03187 
03188 #if defined(MBEDTLS_SSL_PROTO_SSL3)
03189         if( transform->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
03190         {
03191             if( padlen > transform->ivlen )
03192             {
03193 #if defined(MBEDTLS_SSL_DEBUG_ALL)
03194                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad padding length: is %d, "
03195                                             "should be no more than %d",
03196                                             padlen, transform->ivlen ) );
03197 #endif
03198                 correct = 0;
03199             }
03200         }
03201         else
03202 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
03203 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
03204     defined(MBEDTLS_SSL_PROTO_TLS1_2)
03205         if( transform->minor_ver > MBEDTLS_SSL_MINOR_VERSION_0 )
03206         {
03207             /* The padding check involves a series of up to 256
03208              * consecutive memory reads at the end of the record
03209              * plaintext buffer. In order to hide the length and
03210              * validity of the padding, always perform exactly
03211              * `min(256,plaintext_len)` reads (but take into account
03212              * only the last `padlen` bytes for the padding check). */
03213             size_t pad_count = 0;
03214             size_t real_count = 0;
03215             volatile unsigned char* const check = data;
03216 
03217             /* Index of first padding byte; it has been ensured above
03218              * that the subtraction is safe. */
03219             size_t const padding_idx = rec->data_len - padlen;
03220             size_t const num_checks = rec->data_len <= 256 ? rec->data_len : 256;
03221             size_t const start_idx = rec->data_len - num_checks;
03222             size_t idx;
03223 
03224             for( idx = start_idx; idx < rec->data_len; idx++ )
03225             {
03226                 real_count |= ( idx >= padding_idx );
03227                 pad_count += real_count * ( check[idx] == padlen - 1 );
03228             }
03229             correct &= ( pad_count == padlen );
03230 
03231 #if defined(MBEDTLS_SSL_DEBUG_ALL)
03232             if( padlen > 0 && correct == 0 )
03233                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad padding byte detected" ) );
03234 #endif
03235             padlen &= correct * 0x1FF;
03236         }
03237         else
03238 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
03239           MBEDTLS_SSL_PROTO_TLS1_2 */
03240         {
03241             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
03242             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
03243         }
03244 
03245         /* If the padding was found to be invalid, padlen == 0
03246          * and the subtraction is safe. If the padding was found valid,
03247          * padlen hasn't been changed and the previous assertion
03248          * data_len >= padlen still holds. */
03249         rec->data_len -= padlen;
03250     }
03251     else
03252 #endif /* MBEDTLS_CIPHER_MODE_CBC &&
03253           ( MBEDTLS_AES_C || MBEDTLS_CAMELLIA_C || MBEDTLS_ARIA_C ) */
03254     {
03255         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
03256         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
03257     }
03258 
03259 #if defined(MBEDTLS_SSL_DEBUG_ALL)
03260     MBEDTLS_SSL_DEBUG_BUF( 4, "raw buffer after decryption",
03261                            data, rec->data_len );
03262 #endif
03263 
03264     /*
03265      * Authenticate if not done yet.
03266      * Compute the MAC regardless of the padding result (RFC4346, CBCTIME).
03267      */
03268 #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
03269     if( auth_done == 0 )
03270     {
03271         unsigned char mac_expect[MBEDTLS_SSL_MAC_ADD];
03272 
03273         /* If the initial value of padlen was such that
03274          * data_len < maclen + padlen + 1, then padlen
03275          * got reset to 1, and the initial check
03276          * data_len >= minlen + maclen + 1
03277          * guarantees that at this point we still
03278          * have at least data_len >= maclen.
03279          *
03280          * If the initial value of padlen was such that
03281          * data_len >= maclen + padlen + 1, then we have
03282          * subtracted either padlen + 1 (if the padding was correct)
03283          * or 0 (if the padding was incorrect) since then,
03284          * hence data_len >= maclen in any case.
03285          */
03286         rec->data_len -= transform->maclen;
03287         ssl_extract_add_data_from_record( add_data, &add_data_len, rec );
03288 
03289 #if defined(MBEDTLS_SSL_PROTO_SSL3)
03290         if( transform->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
03291         {
03292             ssl_mac( &transform->md_ctx_dec,
03293                      transform->mac_dec,
03294                      data, rec->data_len,
03295                      rec->ctr, rec->type,
03296                      mac_expect );
03297         }
03298         else
03299 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
03300 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
03301         defined(MBEDTLS_SSL_PROTO_TLS1_2)
03302         if( transform->minor_ver > MBEDTLS_SSL_MINOR_VERSION_0 )
03303         {
03304             /*
03305              * Process MAC and always update for padlen afterwards to make
03306              * total time independent of padlen.
03307              *
03308              * Known timing attacks:
03309              *  - Lucky Thirteen (http://www.isg.rhul.ac.uk/tls/TLStiming.pdf)
03310              *
03311              * To compensate for different timings for the MAC calculation
03312              * depending on how much padding was removed (which is determined
03313              * by padlen), process extra_run more blocks through the hash
03314              * function.
03315              *
03316              * The formula in the paper is
03317              *   extra_run = ceil( (L1-55) / 64 ) - ceil( (L2-55) / 64 )
03318              * where L1 is the size of the header plus the decrypted message
03319              * plus CBC padding and L2 is the size of the header plus the
03320              * decrypted message. This is for an underlying hash function
03321              * with 64-byte blocks.
03322              * We use ( (Lx+8) / 64 ) to handle 'negative Lx' values
03323              * correctly. We round down instead of up, so -56 is the correct
03324              * value for our calculations instead of -55.
03325              *
03326              * Repeat the formula rather than defining a block_size variable.
03327              * This avoids requiring division by a variable at runtime
03328              * (which would be marginally less efficient and would require
03329              * linking an extra division function in some builds).
03330              */
03331             size_t j, extra_run = 0;
03332             unsigned char tmp[MBEDTLS_MD_MAX_BLOCK_SIZE];
03333 
03334             /*
03335              * The next two sizes are the minimum and maximum values of
03336              * in_msglen over all padlen values.
03337              *
03338              * They're independent of padlen, since we previously did
03339              * data_len -= padlen.
03340              *
03341              * Note that max_len + maclen is never more than the buffer
03342              * length, as we previously did in_msglen -= maclen too.
03343              */
03344             const size_t max_len = rec->data_len + padlen;
03345             const size_t min_len = ( max_len > 256 ) ? max_len - 256 : 0;
03346 
03347             memset( tmp, 0, sizeof( tmp ) );
03348 
03349             switch( mbedtls_md_get_type( transform->md_ctx_dec.md_info ) )
03350             {
03351 #if defined(MBEDTLS_MD5_C) || defined(MBEDTLS_SHA1_C) || \
03352     defined(MBEDTLS_SHA256_C)
03353                 case MBEDTLS_MD_MD5:
03354                 case MBEDTLS_MD_SHA1:
03355                 case MBEDTLS_MD_SHA256:
03356                     /* 8 bytes of message size, 64-byte compression blocks */
03357                     extra_run =
03358                         ( add_data_len + rec->data_len + padlen + 8 ) / 64 -
03359                         ( add_data_len + rec->data_len          + 8 ) / 64;
03360                     break;
03361 #endif
03362 #if defined(MBEDTLS_SHA512_C)
03363                 case MBEDTLS_MD_SHA384:
03364                     /* 16 bytes of message size, 128-byte compression blocks */
03365                     extra_run =
03366                         ( add_data_len + rec->data_len + padlen + 16 ) / 128 -
03367                         ( add_data_len + rec->data_len          + 16 ) / 128;
03368                     break;
03369 #endif
03370                 default:
03371                     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
03372                     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
03373             }
03374 
03375             extra_run &= correct * 0xFF;
03376 
03377             mbedtls_md_hmac_update( &transform->md_ctx_dec, add_data,
03378                                     add_data_len );
03379             mbedtls_md_hmac_update( &transform->md_ctx_dec, data,
03380                                     rec->data_len );
03381             /* Make sure we access everything even when padlen > 0. This
03382              * makes the synchronisation requirements for just-in-time
03383              * Prime+Probe attacks much tighter and hopefully impractical. */
03384             ssl_read_memory( data + rec->data_len, padlen );
03385             mbedtls_md_hmac_finish( &transform->md_ctx_dec, mac_expect );
03386 
03387             /* Call mbedtls_md_process at least once due to cache attacks
03388              * that observe whether md_process() was called of not */
03389             for( j = 0; j < extra_run + 1; j++ )
03390                 mbedtls_md_process( &transform->md_ctx_dec, tmp );
03391 
03392             mbedtls_md_hmac_reset( &transform->md_ctx_dec );
03393 
03394             /* Make sure we access all the memory that could contain the MAC,
03395              * before we check it in the next code block. This makes the
03396              * synchronisation requirements for just-in-time Prime+Probe
03397              * attacks much tighter and hopefully impractical. */
03398             ssl_read_memory( data + min_len,
03399                              max_len - min_len + transform->maclen );
03400         }
03401         else
03402 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
03403               MBEDTLS_SSL_PROTO_TLS1_2 */
03404         {
03405             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
03406             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
03407         }
03408 
03409 #if defined(MBEDTLS_SSL_DEBUG_ALL)
03410         MBEDTLS_SSL_DEBUG_BUF( 4, "expected mac", mac_expect, transform->maclen );
03411         MBEDTLS_SSL_DEBUG_BUF( 4, "message  mac", data + rec->data_len, transform->maclen );
03412 #endif
03413 
03414         if( mbedtls_ssl_safer_memcmp( data + rec->data_len, mac_expect,
03415                                       transform->maclen ) != 0 )
03416         {
03417 #if defined(MBEDTLS_SSL_DEBUG_ALL)
03418             MBEDTLS_SSL_DEBUG_MSG( 1, ( "message mac does not match" ) );
03419 #endif
03420             correct = 0;
03421         }
03422         auth_done++;
03423     }
03424 
03425     /*
03426      * Finally check the correct flag
03427      */
03428     if( correct == 0 )
03429         return( MBEDTLS_ERR_SSL_INVALID_MAC );
03430 #endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */
03431 
03432     /* Make extra sure authentication was performed, exactly once */
03433     if( auth_done != 1 )
03434     {
03435         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
03436         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
03437     }
03438 
03439 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
03440     if( rec->cid_len != 0 )
03441     {
03442         ret = ssl_cid_parse_inner_plaintext( data, &rec->data_len,
03443                                              &rec->type );
03444         if( ret != 0 )
03445             return( MBEDTLS_ERR_SSL_INVALID_RECORD );
03446     }
03447 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
03448 
03449     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= decrypt buf" ) );
03450 
03451     return( 0 );
03452 }
03453 
03454 #undef MAC_NONE
03455 #undef MAC_PLAINTEXT
03456 #undef MAC_CIPHERTEXT
03457 
03458 #if defined(MBEDTLS_ZLIB_SUPPORT)
03459 /*
03460  * Compression/decompression functions
03461  */
03462 static int ssl_compress_buf( mbedtls_ssl_context *ssl )
03463 {
03464     int ret;
03465     unsigned char *msg_post = ssl->out_msg;
03466     ptrdiff_t bytes_written = ssl->out_msg - ssl->out_buf;
03467     size_t len_pre = ssl->out_msglen;
03468     unsigned char *msg_pre = ssl->compress_buf;
03469 
03470     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> compress buf" ) );
03471 
03472     if( len_pre == 0 )
03473         return( 0 );
03474 
03475     memcpy( msg_pre, ssl->out_msg, len_pre );
03476 
03477     MBEDTLS_SSL_DEBUG_MSG( 3, ( "before compression: msglen = %d, ",
03478                    ssl->out_msglen ) );
03479 
03480     MBEDTLS_SSL_DEBUG_BUF( 4, "before compression: output payload",
03481                    ssl->out_msg, ssl->out_msglen );
03482 
03483     ssl->transform_out->ctx_deflate.next_in = msg_pre;
03484     ssl->transform_out->ctx_deflate.avail_in = len_pre;
03485     ssl->transform_out->ctx_deflate.next_out = msg_post;
03486     ssl->transform_out->ctx_deflate.avail_out = MBEDTLS_SSL_OUT_BUFFER_LEN - bytes_written;
03487 
03488     ret = deflate( &ssl->transform_out->ctx_deflate, Z_SYNC_FLUSH );
03489     if( ret != Z_OK )
03490     {
03491         MBEDTLS_SSL_DEBUG_MSG( 1, ( "failed to perform compression (%d)", ret ) );
03492         return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED );
03493     }
03494 
03495     ssl->out_msglen = MBEDTLS_SSL_OUT_BUFFER_LEN -
03496                       ssl->transform_out->ctx_deflate.avail_out - bytes_written;
03497 
03498     MBEDTLS_SSL_DEBUG_MSG( 3, ( "after compression: msglen = %d, ",
03499                    ssl->out_msglen ) );
03500 
03501     MBEDTLS_SSL_DEBUG_BUF( 4, "after compression: output payload",
03502                    ssl->out_msg, ssl->out_msglen );
03503 
03504     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= compress buf" ) );
03505 
03506     return( 0 );
03507 }
03508 
03509 static int ssl_decompress_buf( mbedtls_ssl_context *ssl )
03510 {
03511     int ret;
03512     unsigned char *msg_post = ssl->in_msg;
03513     ptrdiff_t header_bytes = ssl->in_msg - ssl->in_buf;
03514     size_t len_pre = ssl->in_msglen;
03515     unsigned char *msg_pre = ssl->compress_buf;
03516 
03517     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> decompress buf" ) );
03518 
03519     if( len_pre == 0 )
03520         return( 0 );
03521 
03522     memcpy( msg_pre, ssl->in_msg, len_pre );
03523 
03524     MBEDTLS_SSL_DEBUG_MSG( 3, ( "before decompression: msglen = %d, ",
03525                    ssl->in_msglen ) );
03526 
03527     MBEDTLS_SSL_DEBUG_BUF( 4, "before decompression: input payload",
03528                    ssl->in_msg, ssl->in_msglen );
03529 
03530     ssl->transform_in->ctx_inflate.next_in = msg_pre;
03531     ssl->transform_in->ctx_inflate.avail_in = len_pre;
03532     ssl->transform_in->ctx_inflate.next_out = msg_post;
03533     ssl->transform_in->ctx_inflate.avail_out = MBEDTLS_SSL_IN_BUFFER_LEN -
03534                                                header_bytes;
03535 
03536     ret = inflate( &ssl->transform_in->ctx_inflate, Z_SYNC_FLUSH );
03537     if( ret != Z_OK )
03538     {
03539         MBEDTLS_SSL_DEBUG_MSG( 1, ( "failed to perform decompression (%d)", ret ) );
03540         return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED );
03541     }
03542 
03543     ssl->in_msglen = MBEDTLS_SSL_IN_BUFFER_LEN -
03544                      ssl->transform_in->ctx_inflate.avail_out - header_bytes;
03545 
03546     MBEDTLS_SSL_DEBUG_MSG( 3, ( "after decompression: msglen = %d, ",
03547                    ssl->in_msglen ) );
03548 
03549     MBEDTLS_SSL_DEBUG_BUF( 4, "after decompression: input payload",
03550                    ssl->in_msg, ssl->in_msglen );
03551 
03552     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= decompress buf" ) );
03553 
03554     return( 0 );
03555 }
03556 #endif /* MBEDTLS_ZLIB_SUPPORT */
03557 
03558 #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
03559 static int ssl_write_hello_request( mbedtls_ssl_context *ssl );
03560 
03561 #if defined(MBEDTLS_SSL_PROTO_DTLS)
03562 static int ssl_resend_hello_request( mbedtls_ssl_context *ssl )
03563 {
03564     /* If renegotiation is not enforced, retransmit until we would reach max
03565      * timeout if we were using the usual handshake doubling scheme */
03566     if( ssl->conf->renego_max_records < 0 )
03567     {
03568         uint32_t ratio = ssl->conf->hs_timeout_max / ssl->conf->hs_timeout_min + 1;
03569         unsigned char doublings = 1;
03570 
03571         while( ratio != 0 )
03572         {
03573             ++doublings;
03574             ratio >>= 1;
03575         }
03576 
03577         if( ++ssl->renego_records_seen > doublings )
03578         {
03579             MBEDTLS_SSL_DEBUG_MSG( 2, ( "no longer retransmitting hello request" ) );
03580             return( 0 );
03581         }
03582     }
03583 
03584     return( ssl_write_hello_request( ssl ) );
03585 }
03586 #endif
03587 #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
03588 
03589 /*
03590  * Fill the input message buffer by appending data to it.
03591  * The amount of data already fetched is in ssl->in_left.
03592  *
03593  * If we return 0, is it guaranteed that (at least) nb_want bytes are
03594  * available (from this read and/or a previous one). Otherwise, an error code
03595  * is returned (possibly EOF or WANT_READ).
03596  *
03597  * With stream transport (TLS) on success ssl->in_left == nb_want, but
03598  * with datagram transport (DTLS) on success ssl->in_left >= nb_want,
03599  * since we always read a whole datagram at once.
03600  *
03601  * For DTLS, it is up to the caller to set ssl->next_record_offset when
03602  * they're done reading a record.
03603  */
03604 int mbedtls_ssl_fetch_input( mbedtls_ssl_context *ssl, size_t nb_want )
03605 {
03606     int ret;
03607     size_t len;
03608 
03609     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> fetch input" ) );
03610 
03611     if( ssl->f_recv == NULL && ssl->f_recv_timeout == NULL )
03612     {
03613         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Bad usage of mbedtls_ssl_set_bio() "
03614                             "or mbedtls_ssl_set_bio()" ) );
03615         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
03616     }
03617 
03618     if( nb_want > MBEDTLS_SSL_IN_BUFFER_LEN - (size_t)( ssl->in_hdr - ssl->in_buf ) )
03619     {
03620         MBEDTLS_SSL_DEBUG_MSG( 1, ( "requesting more data than fits" ) );
03621         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
03622     }
03623 
03624 #if defined(MBEDTLS_SSL_PROTO_DTLS)
03625     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
03626     {
03627         uint32_t timeout;
03628 
03629         /* Just to be sure */
03630         if( ssl->f_set_timer == NULL || ssl->f_get_timer == NULL )
03631         {
03632             MBEDTLS_SSL_DEBUG_MSG( 1, ( "You must use "
03633                         "mbedtls_ssl_set_timer_cb() for DTLS" ) );
03634             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
03635         }
03636 
03637         /*
03638          * The point is, we need to always read a full datagram at once, so we
03639          * sometimes read more then requested, and handle the additional data.
03640          * It could be the rest of the current record (while fetching the
03641          * header) and/or some other records in the same datagram.
03642          */
03643 
03644         /*
03645          * Move to the next record in the already read datagram if applicable
03646          */
03647         if( ssl->next_record_offset != 0 )
03648         {
03649             if( ssl->in_left < ssl->next_record_offset )
03650             {
03651                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
03652                 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
03653             }
03654 
03655             ssl->in_left -= ssl->next_record_offset;
03656 
03657             if( ssl->in_left != 0 )
03658             {
03659                 MBEDTLS_SSL_DEBUG_MSG( 2, ( "next record in same datagram, offset: %d",
03660                                     ssl->next_record_offset ) );
03661                 memmove( ssl->in_hdr,
03662                          ssl->in_hdr + ssl->next_record_offset,
03663                          ssl->in_left );
03664             }
03665 
03666             ssl->next_record_offset = 0;
03667         }
03668 
03669         MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d",
03670                        ssl->in_left, nb_want ) );
03671 
03672         /*
03673          * Done if we already have enough data.
03674          */
03675         if( nb_want <= ssl->in_left)
03676         {
03677             MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= fetch input" ) );
03678             return( 0 );
03679         }
03680 
03681         /*
03682          * A record can't be split across datagrams. If we need to read but
03683          * are not at the beginning of a new record, the caller did something
03684          * wrong.
03685          */
03686         if( ssl->in_left != 0 )
03687         {
03688             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
03689             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
03690         }
03691 
03692         /*
03693          * Don't even try to read if time's out already.
03694          * This avoids by-passing the timer when repeatedly receiving messages
03695          * that will end up being dropped.
03696          */
03697         if( ssl_check_timer( ssl ) != 0 )
03698         {
03699             MBEDTLS_SSL_DEBUG_MSG( 2, ( "timer has expired" ) );
03700             ret = MBEDTLS_ERR_SSL_TIMEOUT;
03701         }
03702         else
03703         {
03704             len = MBEDTLS_SSL_IN_BUFFER_LEN - ( ssl->in_hdr - ssl->in_buf );
03705 
03706             if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
03707                 timeout = ssl->handshake->retransmit_timeout;
03708             else
03709                 timeout = ssl->conf->read_timeout;
03710 
03711             MBEDTLS_SSL_DEBUG_MSG( 3, ( "f_recv_timeout: %u ms", timeout ) );
03712 
03713             if( ssl->f_recv_timeout != NULL )
03714                 ret = ssl->f_recv_timeout( ssl->p_bio, ssl->in_hdr, len,
03715                                                                     timeout );
03716             else
03717                 ret = ssl->f_recv( ssl->p_bio, ssl->in_hdr, len );
03718 
03719             MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_recv(_timeout)", ret );
03720 
03721             if( ret == 0 )
03722                 return( MBEDTLS_ERR_SSL_CONN_EOF );
03723         }
03724 
03725         if( ret == MBEDTLS_ERR_SSL_TIMEOUT )
03726         {
03727             MBEDTLS_SSL_DEBUG_MSG( 2, ( "timeout" ) );
03728             ssl_set_timer( ssl, 0 );
03729 
03730             if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
03731             {
03732                 if( ssl_double_retransmit_timeout( ssl ) != 0 )
03733                 {
03734                     MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake timeout" ) );
03735                     return( MBEDTLS_ERR_SSL_TIMEOUT );
03736                 }
03737 
03738                 if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )
03739                 {
03740                     MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend", ret );
03741                     return( ret );
03742                 }
03743 
03744                 return( MBEDTLS_ERR_SSL_WANT_READ );
03745             }
03746 #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
03747             else if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
03748                      ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
03749             {
03750                 if( ( ret = ssl_resend_hello_request( ssl ) ) != 0 )
03751                 {
03752                     MBEDTLS_SSL_DEBUG_RET( 1, "ssl_resend_hello_request", ret );
03753                     return( ret );
03754                 }
03755 
03756                 return( MBEDTLS_ERR_SSL_WANT_READ );
03757             }
03758 #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
03759         }
03760 
03761         if( ret < 0 )
03762             return( ret );
03763 
03764         ssl->in_left = ret;
03765     }
03766     else
03767 #endif
03768     {
03769         MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d",
03770                        ssl->in_left, nb_want ) );
03771 
03772         while( ssl->in_left < nb_want )
03773         {
03774             len = nb_want - ssl->in_left;
03775 
03776             if( ssl_check_timer( ssl ) != 0 )
03777                 ret = MBEDTLS_ERR_SSL_TIMEOUT;
03778             else
03779             {
03780                 if( ssl->f_recv_timeout != NULL )
03781                 {
03782                     ret = ssl->f_recv_timeout( ssl->p_bio,
03783                                                ssl->in_hdr + ssl->in_left, len,
03784                                                ssl->conf->read_timeout );
03785                 }
03786                 else
03787                 {
03788                     ret = ssl->f_recv( ssl->p_bio,
03789                                        ssl->in_hdr + ssl->in_left, len );
03790                 }
03791             }
03792 
03793             MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d",
03794                                         ssl->in_left, nb_want ) );
03795             MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_recv(_timeout)", ret );
03796 
03797             if( ret == 0 )
03798                 return( MBEDTLS_ERR_SSL_CONN_EOF );
03799 
03800             if( ret < 0 )
03801                 return( ret );
03802 
03803             if ( (size_t)ret > len || ( INT_MAX > SIZE_MAX && ret > SIZE_MAX ) )
03804             {
03805                 MBEDTLS_SSL_DEBUG_MSG( 1,
03806                     ( "f_recv returned %d bytes but only %lu were requested",
03807                     ret, (unsigned long)len ) );
03808                 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
03809             }
03810 
03811             ssl->in_left += ret;
03812         }
03813     }
03814 
03815     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= fetch input" ) );
03816 
03817     return( 0 );
03818 }
03819 
03820 /*
03821  * Flush any data not yet written
03822  */
03823 int mbedtls_ssl_flush_output( mbedtls_ssl_context *ssl )
03824 {
03825     int ret;
03826     unsigned char *buf;
03827 
03828     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> flush output" ) );
03829 
03830     if( ssl->f_send == NULL )
03831     {
03832         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Bad usage of mbedtls_ssl_set_bio() "
03833                             "or mbedtls_ssl_set_bio()" ) );
03834         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
03835     }
03836 
03837     /* Avoid incrementing counter if data is flushed */
03838     if( ssl->out_left == 0 )
03839     {
03840         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= flush output" ) );
03841         return( 0 );
03842     }
03843 
03844     while( ssl->out_left > 0 )
03845     {
03846         MBEDTLS_SSL_DEBUG_MSG( 2, ( "message length: %d, out_left: %d",
03847                        mbedtls_ssl_out_hdr_len( ssl ) + ssl->out_msglen, ssl->out_left ) );
03848 
03849         buf = ssl->out_hdr - ssl->out_left;
03850         ret = ssl->f_send( ssl->p_bio, buf, ssl->out_left );
03851 
03852         MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_send", ret );
03853 
03854         if( ret <= 0 )
03855             return( ret );
03856 
03857         if( (size_t)ret > ssl->out_left || ( INT_MAX > SIZE_MAX && ret > SIZE_MAX ) )
03858         {
03859             MBEDTLS_SSL_DEBUG_MSG( 1,
03860                 ( "f_send returned %d bytes but only %lu bytes were sent",
03861                 ret, (unsigned long)ssl->out_left ) );
03862             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
03863         }
03864 
03865         ssl->out_left -= ret;
03866     }
03867 
03868 #if defined(MBEDTLS_SSL_PROTO_DTLS)
03869     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
03870     {
03871         ssl->out_hdr = ssl->out_buf;
03872     }
03873     else
03874 #endif
03875     {
03876         ssl->out_hdr = ssl->out_buf + 8;
03877     }
03878     ssl_update_out_pointers( ssl, ssl->transform_out );
03879 
03880     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= flush output" ) );
03881 
03882     return( 0 );
03883 }
03884 
03885 /*
03886  * Functions to handle the DTLS retransmission state machine
03887  */
03888 #if defined(MBEDTLS_SSL_PROTO_DTLS)
03889 /*
03890  * Append current handshake message to current outgoing flight
03891  */
03892 static int ssl_flight_append( mbedtls_ssl_context *ssl )
03893 {
03894     mbedtls_ssl_flight_item *msg;
03895     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> ssl_flight_append" ) );
03896     MBEDTLS_SSL_DEBUG_BUF( 4, "message appended to flight",
03897                            ssl->out_msg, ssl->out_msglen );
03898 
03899     /* Allocate space for current message */
03900     if( ( msg = mbedtls_calloc( 1, sizeof(  mbedtls_ssl_flight_item ) ) ) == NULL )
03901     {
03902         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc %d bytes failed",
03903                             sizeof( mbedtls_ssl_flight_item ) ) );
03904         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
03905     }
03906 
03907     if( ( msg->p = mbedtls_calloc( 1, ssl->out_msglen ) ) == NULL )
03908     {
03909         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc %d bytes failed", ssl->out_msglen ) );
03910         mbedtls_free( msg );
03911         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
03912     }
03913 
03914     /* Copy current handshake message with headers */
03915     memcpy( msg->p, ssl->out_msg, ssl->out_msglen );
03916     msg->len = ssl->out_msglen;
03917     msg->type = ssl->out_msgtype;
03918     msg->next = NULL;
03919 
03920     /* Append to the current flight */
03921     if( ssl->handshake->flight == NULL )
03922         ssl->handshake->flight = msg;
03923     else
03924     {
03925         mbedtls_ssl_flight_item *cur = ssl->handshake->flight;
03926         while( cur->next != NULL )
03927             cur = cur->next;
03928         cur->next = msg;
03929     }
03930 
03931     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= ssl_flight_append" ) );
03932     return( 0 );
03933 }
03934 
03935 /*
03936  * Free the current flight of handshake messages
03937  */
03938 static void ssl_flight_free( mbedtls_ssl_flight_item *flight )
03939 {
03940     mbedtls_ssl_flight_item *cur = flight;
03941     mbedtls_ssl_flight_item *next;
03942 
03943     while( cur != NULL )
03944     {
03945         next = cur->next;
03946 
03947         mbedtls_free( cur->p );
03948         mbedtls_free( cur );
03949 
03950         cur = next;
03951     }
03952 }
03953 
03954 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
03955 static void ssl_dtls_replay_reset( mbedtls_ssl_context *ssl );
03956 #endif
03957 
03958 /*
03959  * Swap transform_out and out_ctr with the alternative ones
03960  */
03961 static void ssl_swap_epochs( mbedtls_ssl_context *ssl )
03962 {
03963     mbedtls_ssl_transform *tmp_transform;
03964     unsigned char tmp_out_ctr[8];
03965 
03966     if( ssl->transform_out == ssl->handshake->alt_transform_out )
03967     {
03968         MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip swap epochs" ) );
03969         return;
03970     }
03971 
03972     MBEDTLS_SSL_DEBUG_MSG( 3, ( "swap epochs" ) );
03973 
03974     /* Swap transforms */
03975     tmp_transform                     = ssl->transform_out;
03976     ssl->transform_out                = ssl->handshake->alt_transform_out;
03977     ssl->handshake->alt_transform_out = tmp_transform;
03978 
03979     /* Swap epoch + sequence_number */
03980     memcpy( tmp_out_ctr,                 ssl->cur_out_ctr,            8 );
03981     memcpy( ssl->cur_out_ctr,            ssl->handshake->alt_out_ctr, 8 );
03982     memcpy( ssl->handshake->alt_out_ctr, tmp_out_ctr,                 8 );
03983 
03984     /* Adjust to the newly activated transform */
03985     ssl_update_out_pointers( ssl, ssl->transform_out );
03986 
03987 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
03988     if( mbedtls_ssl_hw_record_activate != NULL )
03989     {
03990         if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_OUTBOUND ) ) != 0 )
03991         {
03992             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret );
03993             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
03994         }
03995     }
03996 #endif
03997 }
03998 
03999 /*
04000  * Retransmit the current flight of messages.
04001  */
04002 int mbedtls_ssl_resend( mbedtls_ssl_context *ssl )
04003 {
04004     int ret = 0;
04005 
04006     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> mbedtls_ssl_resend" ) );
04007 
04008     ret = mbedtls_ssl_flight_transmit( ssl );
04009 
04010     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= mbedtls_ssl_resend" ) );
04011 
04012     return( ret );
04013 }
04014 
04015 /*
04016  * Transmit or retransmit the current flight of messages.
04017  *
04018  * Need to remember the current message in case flush_output returns
04019  * WANT_WRITE, causing us to exit this function and come back later.
04020  * This function must be called until state is no longer SENDING.
04021  */
04022 int mbedtls_ssl_flight_transmit( mbedtls_ssl_context *ssl )
04023 {
04024     int ret;
04025     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> mbedtls_ssl_flight_transmit" ) );
04026 
04027     if( ssl->handshake->retransmit_state != MBEDTLS_SSL_RETRANS_SENDING )
04028     {
04029         MBEDTLS_SSL_DEBUG_MSG( 2, ( "initialise flight transmission" ) );
04030 
04031         ssl->handshake->cur_msg = ssl->handshake->flight;
04032         ssl->handshake->cur_msg_p = ssl->handshake->flight->p + 12;
04033         ssl_swap_epochs( ssl );
04034 
04035         ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_SENDING;
04036     }
04037 
04038     while( ssl->handshake->cur_msg != NULL )
04039     {
04040         size_t max_frag_len;
04041         const mbedtls_ssl_flight_item * const cur = ssl->handshake->cur_msg;
04042 
04043         int const is_finished =
04044             ( cur->type == MBEDTLS_SSL_MSG_HANDSHAKE &&
04045               cur->p[0] == MBEDTLS_SSL_HS_FINISHED );
04046 
04047         uint8_t const force_flush = ssl->disable_datagram_packing == 1 ?
04048             SSL_FORCE_FLUSH : SSL_DONT_FORCE_FLUSH;
04049 
04050         /* Swap epochs before sending Finished: we can't do it after
04051          * sending ChangeCipherSpec, in case write returns WANT_READ.
04052          * Must be done before copying, may change out_msg pointer */
04053         if( is_finished && ssl->handshake->cur_msg_p == ( cur->p + 12 ) )
04054         {
04055             MBEDTLS_SSL_DEBUG_MSG( 2, ( "swap epochs to send finished message" ) );
04056             ssl_swap_epochs( ssl );
04057         }
04058 
04059         ret = ssl_get_remaining_payload_in_datagram( ssl );
04060         if( ret < 0 )
04061             return( ret );
04062         max_frag_len = (size_t) ret;
04063 
04064         /* CCS is copied as is, while HS messages may need fragmentation */
04065         if( cur->type == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC )
04066         {
04067             if( max_frag_len == 0 )
04068             {
04069                 if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
04070                     return( ret );
04071 
04072                 continue;
04073             }
04074 
04075             memcpy( ssl->out_msg, cur->p, cur->len );
04076             ssl->out_msglen  = cur->len;
04077             ssl->out_msgtype = cur->type;
04078 
04079             /* Update position inside current message */
04080             ssl->handshake->cur_msg_p += cur->len;
04081         }
04082         else
04083         {
04084             const unsigned char * const p = ssl->handshake->cur_msg_p;
04085             const size_t hs_len = cur->len - 12;
04086             const size_t frag_off = p - ( cur->p + 12 );
04087             const size_t rem_len = hs_len - frag_off;
04088             size_t cur_hs_frag_len, max_hs_frag_len;
04089 
04090             if( ( max_frag_len < 12 ) || ( max_frag_len == 12 && hs_len != 0 ) )
04091             {
04092                 if( is_finished )
04093                     ssl_swap_epochs( ssl );
04094 
04095                 if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
04096                     return( ret );
04097 
04098                 continue;
04099             }
04100             max_hs_frag_len = max_frag_len - 12;
04101 
04102             cur_hs_frag_len = rem_len > max_hs_frag_len ?
04103                 max_hs_frag_len : rem_len;
04104 
04105             if( frag_off == 0 && cur_hs_frag_len != hs_len )
04106             {
04107                 MBEDTLS_SSL_DEBUG_MSG( 2, ( "fragmenting handshake message (%u > %u)",
04108                                             (unsigned) cur_hs_frag_len,
04109                                             (unsigned) max_hs_frag_len ) );
04110             }
04111 
04112             /* Messages are stored with handshake headers as if not fragmented,
04113              * copy beginning of headers then fill fragmentation fields.
04114              * Handshake headers: type(1) len(3) seq(2) f_off(3) f_len(3) */
04115             memcpy( ssl->out_msg, cur->p, 6 );
04116 
04117             ssl->out_msg[6] = ( ( frag_off >> 16 ) & 0xff );
04118             ssl->out_msg[7] = ( ( frag_off >>  8 ) & 0xff );
04119             ssl->out_msg[8] = ( ( frag_off       ) & 0xff );
04120 
04121             ssl->out_msg[ 9] = ( ( cur_hs_frag_len >> 16 ) & 0xff );
04122             ssl->out_msg[10] = ( ( cur_hs_frag_len >>  8 ) & 0xff );
04123             ssl->out_msg[11] = ( ( cur_hs_frag_len       ) & 0xff );
04124 
04125             MBEDTLS_SSL_DEBUG_BUF( 3, "handshake header", ssl->out_msg, 12 );
04126 
04127             /* Copy the handshake message content and set records fields */
04128             memcpy( ssl->out_msg + 12, p, cur_hs_frag_len );
04129             ssl->out_msglen = cur_hs_frag_len + 12;
04130             ssl->out_msgtype = cur->type;
04131 
04132             /* Update position inside current message */
04133             ssl->handshake->cur_msg_p += cur_hs_frag_len;
04134         }
04135 
04136         /* If done with the current message move to the next one if any */
04137         if( ssl->handshake->cur_msg_p >= cur->p + cur->len )
04138         {
04139             if( cur->next != NULL )
04140             {
04141                 ssl->handshake->cur_msg = cur->next;
04142                 ssl->handshake->cur_msg_p = cur->next->p + 12;
04143             }
04144             else
04145             {
04146                 ssl->handshake->cur_msg = NULL;
04147                 ssl->handshake->cur_msg_p = NULL;
04148             }
04149         }
04150 
04151         /* Actually send the message out */
04152         if( ( ret = mbedtls_ssl_write_record( ssl, force_flush ) ) != 0 )
04153         {
04154             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
04155             return( ret );
04156         }
04157     }
04158 
04159     if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
04160         return( ret );
04161 
04162     /* Update state and set timer */
04163     if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )
04164         ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
04165     else
04166     {
04167         ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
04168         ssl_set_timer( ssl, ssl->handshake->retransmit_timeout );
04169     }
04170 
04171     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= mbedtls_ssl_flight_transmit" ) );
04172 
04173     return( 0 );
04174 }
04175 
04176 /*
04177  * To be called when the last message of an incoming flight is received.
04178  */
04179 void mbedtls_ssl_recv_flight_completed( mbedtls_ssl_context *ssl )
04180 {
04181     /* We won't need to resend that one any more */
04182     ssl_flight_free( ssl->handshake->flight );
04183     ssl->handshake->flight = NULL;
04184     ssl->handshake->cur_msg = NULL;
04185 
04186     /* The next incoming flight will start with this msg_seq */
04187     ssl->handshake->in_flight_start_seq = ssl->handshake->in_msg_seq;
04188 
04189     /* We don't want to remember CCS's across flight boundaries. */
04190     ssl->handshake->buffering.seen_ccs = 0;
04191 
04192     /* Clear future message buffering structure. */
04193     ssl_buffering_free( ssl );
04194 
04195     /* Cancel timer */
04196     ssl_set_timer( ssl, 0 );
04197 
04198     if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
04199         ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED )
04200     {
04201         ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
04202     }
04203     else
04204         ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_PREPARING;
04205 }
04206 
04207 /*
04208  * To be called when the last message of an outgoing flight is send.
04209  */
04210 void mbedtls_ssl_send_flight_completed( mbedtls_ssl_context *ssl )
04211 {
04212     ssl_reset_retransmit_timeout( ssl );
04213     ssl_set_timer( ssl, ssl->handshake->retransmit_timeout );
04214 
04215     if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
04216         ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED )
04217     {
04218         ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED;
04219     }
04220     else
04221         ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
04222 }
04223 #endif /* MBEDTLS_SSL_PROTO_DTLS */
04224 
04225 /*
04226  * Handshake layer functions
04227  */
04228 
04229 /*
04230  * Write (DTLS: or queue) current handshake (including CCS) message.
04231  *
04232  *  - fill in handshake headers
04233  *  - update handshake checksum
04234  *  - DTLS: save message for resending
04235  *  - then pass to the record layer
04236  *
04237  * DTLS: except for HelloRequest, messages are only queued, and will only be
04238  * actually sent when calling flight_transmit() or resend().
04239  *
04240  * Inputs:
04241  *  - ssl->out_msglen: 4 + actual handshake message len
04242  *      (4 is the size of handshake headers for TLS)
04243  *  - ssl->out_msg[0]: the handshake type (ClientHello, ServerHello, etc)
04244  *  - ssl->out_msg + 4: the handshake message body
04245  *
04246  * Outputs, ie state before passing to flight_append() or write_record():
04247  *   - ssl->out_msglen: the length of the record contents
04248  *      (including handshake headers but excluding record headers)
04249  *   - ssl->out_msg: the record contents (handshake headers + content)
04250  */
04251 int mbedtls_ssl_write_handshake_msg( mbedtls_ssl_context *ssl )
04252 {
04253     int ret;
04254     const size_t hs_len = ssl->out_msglen - 4;
04255     const unsigned char hs_type = ssl->out_msg[0];
04256 
04257     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write handshake message" ) );
04258 
04259     /*
04260      * Sanity checks
04261      */
04262     if( ssl->out_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE          &&
04263         ssl->out_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC )
04264     {
04265         /* In SSLv3, the client might send a NoCertificate alert. */
04266 #if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_CLI_C)
04267         if( ! ( ssl->minor_ver      == MBEDTLS_SSL_MINOR_VERSION_0 &&
04268                 ssl->out_msgtype    == MBEDTLS_SSL_MSG_ALERT       &&
04269                 ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ) )
04270 #endif /* MBEDTLS_SSL_PROTO_SSL3 && MBEDTLS_SSL_SRV_C */
04271         {
04272             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
04273             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
04274         }
04275     }
04276 
04277     /* Whenever we send anything different from a
04278      * HelloRequest we should be in a handshake - double check. */
04279     if( ! ( ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
04280             hs_type          == MBEDTLS_SSL_HS_HELLO_REQUEST ) &&
04281         ssl->handshake == NULL )
04282     {
04283         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
04284         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
04285     }
04286 
04287 #if defined(MBEDTLS_SSL_PROTO_DTLS)
04288     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
04289         ssl->handshake != NULL &&
04290         ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING )
04291     {
04292         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
04293         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
04294     }
04295 #endif
04296 
04297     /* Double-check that we did not exceed the bounds
04298      * of the outgoing record buffer.
04299      * This should never fail as the various message
04300      * writing functions must obey the bounds of the
04301      * outgoing record buffer, but better be safe.
04302      *
04303      * Note: We deliberately do not check for the MTU or MFL here.
04304      */
04305     if( ssl->out_msglen > MBEDTLS_SSL_OUT_CONTENT_LEN )
04306     {
04307         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Record too large: "
04308                                     "size %u, maximum %u",
04309                                     (unsigned) ssl->out_msglen,
04310                                     (unsigned) MBEDTLS_SSL_OUT_CONTENT_LEN ) );
04311         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
04312     }
04313 
04314     /*
04315      * Fill handshake headers
04316      */
04317     if( ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE )
04318     {
04319         ssl->out_msg[1] = (unsigned char)( hs_len >> 16 );
04320         ssl->out_msg[2] = (unsigned char)( hs_len >>  8 );
04321         ssl->out_msg[3] = (unsigned char)( hs_len       );
04322 
04323         /*
04324          * DTLS has additional fields in the Handshake layer,
04325          * between the length field and the actual payload:
04326          *      uint16 message_seq;
04327          *      uint24 fragment_offset;
04328          *      uint24 fragment_length;
04329          */
04330 #if defined(MBEDTLS_SSL_PROTO_DTLS)
04331         if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
04332         {
04333             /* Make room for the additional DTLS fields */
04334             if( MBEDTLS_SSL_OUT_CONTENT_LEN - ssl->out_msglen < 8 )
04335             {
04336                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS handshake message too large: "
04337                               "size %u, maximum %u",
04338                                (unsigned) ( hs_len ),
04339                                (unsigned) ( MBEDTLS_SSL_OUT_CONTENT_LEN - 12 ) ) );
04340                 return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
04341             }
04342 
04343             memmove( ssl->out_msg + 12, ssl->out_msg + 4, hs_len );
04344             ssl->out_msglen += 8;
04345 
04346             /* Write message_seq and update it, except for HelloRequest */
04347             if( hs_type != MBEDTLS_SSL_HS_HELLO_REQUEST )
04348             {
04349                 ssl->out_msg[4] = ( ssl->handshake->out_msg_seq >> 8 ) & 0xFF;
04350                 ssl->out_msg[5] = ( ssl->handshake->out_msg_seq      ) & 0xFF;
04351                 ++( ssl->handshake->out_msg_seq );
04352             }
04353             else
04354             {
04355                 ssl->out_msg[4] = 0;
04356                 ssl->out_msg[5] = 0;
04357             }
04358 
04359             /* Handshake hashes are computed without fragmentation,
04360              * so set frag_offset = 0 and frag_len = hs_len for now */
04361             memset( ssl->out_msg + 6, 0x00, 3 );
04362             memcpy( ssl->out_msg + 9, ssl->out_msg + 1, 3 );
04363         }
04364 #endif /* MBEDTLS_SSL_PROTO_DTLS */
04365 
04366         /* Update running hashes of handshake messages seen */
04367         if( hs_type != MBEDTLS_SSL_HS_HELLO_REQUEST )
04368             ssl->handshake->update_checksum( ssl, ssl->out_msg, ssl->out_msglen );
04369     }
04370 
04371     /* Either send now, or just save to be sent (and resent) later */
04372 #if defined(MBEDTLS_SSL_PROTO_DTLS)
04373     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
04374         ! ( ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
04375             hs_type          == MBEDTLS_SSL_HS_HELLO_REQUEST ) )
04376     {
04377         if( ( ret = ssl_flight_append( ssl ) ) != 0 )
04378         {
04379             MBEDTLS_SSL_DEBUG_RET( 1, "ssl_flight_append", ret );
04380             return( ret );
04381         }
04382     }
04383     else
04384 #endif
04385     {
04386         if( ( ret = mbedtls_ssl_write_record( ssl, SSL_FORCE_FLUSH ) ) != 0 )
04387         {
04388             MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_record", ret );
04389             return( ret );
04390         }
04391     }
04392 
04393     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write handshake message" ) );
04394 
04395     return( 0 );
04396 }
04397 
04398 /*
04399  * Record layer functions
04400  */
04401 
04402 /*
04403  * Write current record.
04404  *
04405  * Uses:
04406  *  - ssl->out_msgtype: type of the message (AppData, Handshake, Alert, CCS)
04407  *  - ssl->out_msglen: length of the record content (excl headers)
04408  *  - ssl->out_msg: record content
04409  */
04410 int mbedtls_ssl_write_record( mbedtls_ssl_context *ssl, uint8_t force_flush )
04411 {
04412     int ret, done = 0;
04413     size_t len = ssl->out_msglen;
04414     uint8_t flush = force_flush;
04415 
04416     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write record" ) );
04417 
04418 #if defined(MBEDTLS_ZLIB_SUPPORT)
04419     if( ssl->transform_out != NULL &&
04420         ssl->session_out->compression == MBEDTLS_SSL_COMPRESS_DEFLATE )
04421     {
04422         if( ( ret = ssl_compress_buf( ssl ) ) != 0 )
04423         {
04424             MBEDTLS_SSL_DEBUG_RET( 1, "ssl_compress_buf", ret );
04425             return( ret );
04426         }
04427 
04428         len = ssl->out_msglen;
04429     }
04430 #endif /*MBEDTLS_ZLIB_SUPPORT */
04431 
04432 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
04433     if( mbedtls_ssl_hw_record_write != NULL )
04434     {
04435         MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_write()" ) );
04436 
04437         ret = mbedtls_ssl_hw_record_write( ssl );
04438         if( ret != 0 && ret != MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH )
04439         {
04440             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_write", ret );
04441             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
04442         }
04443 
04444         if( ret == 0 )
04445             done = 1;
04446     }
04447 #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
04448     if( !done )
04449     {
04450         unsigned i;
04451         size_t protected_record_size;
04452 
04453         /* Skip writing the record content type to after the encryption,
04454          * as it may change when using the CID extension. */
04455 
04456         mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,
04457                            ssl->conf->transport, ssl->out_hdr + 1 );
04458 
04459         memcpy( ssl->out_ctr, ssl->cur_out_ctr, 8 );
04460         ssl->out_len[0] = (unsigned char)( len >> 8 );
04461         ssl->out_len[1] = (unsigned char)( len      );
04462 
04463         if( ssl->transform_out != NULL )
04464         {
04465             mbedtls_record rec;
04466 
04467             rec.buf         = ssl->out_iv;
04468             rec.buf_len     = MBEDTLS_SSL_OUT_BUFFER_LEN -
04469                 ( ssl->out_iv - ssl->out_buf );
04470             rec.data_len    = ssl->out_msglen;
04471             rec.data_offset = ssl->out_msg - rec.buf;
04472 
04473             memcpy( &rec.ctr[0], ssl->out_ctr, 8 );
04474             mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,
04475                                        ssl->conf->transport, rec.ver );
04476             rec.type = ssl->out_msgtype;
04477 
04478 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
04479             /* The CID is set by mbedtls_ssl_encrypt_buf(). */
04480             rec.cid_len = 0;
04481 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
04482 
04483             if( ( ret = mbedtls_ssl_encrypt_buf( ssl, ssl->transform_out, &rec,
04484                                          ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
04485             {
04486                 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_encrypt_buf", ret );
04487                 return( ret );
04488             }
04489 
04490             if( rec.data_offset != 0 )
04491             {
04492                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
04493                 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
04494             }
04495 
04496             /* Update the record content type and CID. */
04497             ssl->out_msgtype = rec.type;
04498 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID )
04499             memcpy( ssl->out_cid, rec.cid, rec.cid_len );
04500 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
04501             ssl->out_msglen = len = rec.data_len;
04502             ssl->out_len[0] = (unsigned char)( rec.data_len >> 8 );
04503             ssl->out_len[1] = (unsigned char)( rec.data_len      );
04504         }
04505 
04506         protected_record_size = len + mbedtls_ssl_out_hdr_len( ssl );
04507 
04508 #if defined(MBEDTLS_SSL_PROTO_DTLS)
04509         /* In case of DTLS, double-check that we don't exceed
04510          * the remaining space in the datagram. */
04511         if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
04512         {
04513             ret = ssl_get_remaining_space_in_datagram( ssl );
04514             if( ret < 0 )
04515                 return( ret );
04516 
04517             if( protected_record_size > (size_t) ret )
04518             {
04519                 /* Should never happen */
04520                 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
04521             }
04522         }
04523 #endif /* MBEDTLS_SSL_PROTO_DTLS */
04524 
04525         /* Now write the potentially updated record content type. */
04526         ssl->out_hdr[0] = (unsigned char) ssl->out_msgtype;
04527 
04528         MBEDTLS_SSL_DEBUG_MSG( 3, ( "output record: msgtype = %d, "
04529                                     "version = [%d:%d], msglen = %d",
04530                                     ssl->out_hdr[0], ssl->out_hdr[1],
04531                                     ssl->out_hdr[2], len ) );
04532 
04533         MBEDTLS_SSL_DEBUG_BUF( 4, "output record sent to network",
04534                                ssl->out_hdr, protected_record_size );
04535 
04536         ssl->out_left += protected_record_size;
04537         ssl->out_hdr  += protected_record_size;
04538         ssl_update_out_pointers( ssl, ssl->transform_out );
04539 
04540         for( i = 8; i > ssl_ep_len( ssl ); i-- )
04541             if( ++ssl->cur_out_ctr[i - 1] != 0 )
04542                 break;
04543 
04544         /* The loop goes to its end iff the counter is wrapping */
04545         if( i == ssl_ep_len( ssl ) )
04546         {
04547             MBEDTLS_SSL_DEBUG_MSG( 1, ( "outgoing message counter would wrap" ) );
04548             return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
04549         }
04550     }
04551 
04552 #if defined(MBEDTLS_SSL_PROTO_DTLS)
04553     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
04554         flush == SSL_DONT_FORCE_FLUSH )
04555     {
04556         size_t remaining;
04557         ret = ssl_get_remaining_payload_in_datagram( ssl );
04558         if( ret < 0 )
04559         {
04560             MBEDTLS_SSL_DEBUG_RET( 1, "ssl_get_remaining_payload_in_datagram",
04561                                    ret );
04562             return( ret );
04563         }
04564 
04565         remaining = (size_t) ret;
04566         if( remaining == 0 )
04567         {
04568             flush = SSL_FORCE_FLUSH;
04569         }
04570         else
04571         {
04572             MBEDTLS_SSL_DEBUG_MSG( 2, ( "Still %u bytes available in current datagram", (unsigned) remaining ) );
04573         }
04574     }
04575 #endif /* MBEDTLS_SSL_PROTO_DTLS */
04576 
04577     if( ( flush == SSL_FORCE_FLUSH ) &&
04578         ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
04579     {
04580         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flush_output", ret );
04581         return( ret );
04582     }
04583 
04584     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write record" ) );
04585 
04586     return( 0 );
04587 }
04588 
04589 #if defined(MBEDTLS_SSL_PROTO_DTLS)
04590 
04591 static int ssl_hs_is_proper_fragment( mbedtls_ssl_context *ssl )
04592 {
04593     if( ssl->in_msglen < ssl->in_hslen ||
04594         memcmp( ssl->in_msg + 6, "\0\0\0",        3 ) != 0 ||
04595         memcmp( ssl->in_msg + 9, ssl->in_msg + 1, 3 ) != 0 )
04596     {
04597         return( 1 );
04598     }
04599     return( 0 );
04600 }
04601 
04602 static uint32_t ssl_get_hs_frag_len( mbedtls_ssl_context const *ssl )
04603 {
04604     return( ( ssl->in_msg[9] << 16  ) |
04605             ( ssl->in_msg[10] << 8  ) |
04606               ssl->in_msg[11] );
04607 }
04608 
04609 static uint32_t ssl_get_hs_frag_off( mbedtls_ssl_context const *ssl )
04610 {
04611     return( ( ssl->in_msg[6] << 16 ) |
04612             ( ssl->in_msg[7] << 8  ) |
04613               ssl->in_msg[8] );
04614 }
04615 
04616 static int ssl_check_hs_header( mbedtls_ssl_context const *ssl )
04617 {
04618     uint32_t msg_len, frag_off, frag_len;
04619 
04620     msg_len  = ssl_get_hs_total_len( ssl );
04621     frag_off = ssl_get_hs_frag_off( ssl );
04622     frag_len = ssl_get_hs_frag_len( ssl );
04623 
04624     if( frag_off > msg_len )
04625         return( -1 );
04626 
04627     if( frag_len > msg_len - frag_off )
04628         return( -1 );
04629 
04630     if( frag_len + 12 > ssl->in_msglen )
04631         return( -1 );
04632 
04633     return( 0 );
04634 }
04635 
04636 /*
04637  * Mark bits in bitmask (used for DTLS HS reassembly)
04638  */
04639 static void ssl_bitmask_set( unsigned char *mask, size_t offset, size_t len )
04640 {
04641     unsigned int start_bits, end_bits;
04642 
04643     start_bits = 8 - ( offset % 8 );
04644     if( start_bits != 8 )
04645     {
04646         size_t first_byte_idx = offset / 8;
04647 
04648         /* Special case */
04649         if( len <= start_bits )
04650         {
04651             for( ; len != 0; len-- )
04652                 mask[first_byte_idx] |= 1 << ( start_bits - len );
04653 
04654             /* Avoid potential issues with offset or len becoming invalid */
04655             return;
04656         }
04657 
04658         offset += start_bits; /* Now offset % 8 == 0 */
04659         len -= start_bits;
04660 
04661         for( ; start_bits != 0; start_bits-- )
04662             mask[first_byte_idx] |= 1 << ( start_bits - 1 );
04663     }
04664 
04665     end_bits = len % 8;
04666     if( end_bits != 0 )
04667     {
04668         size_t last_byte_idx = ( offset + len ) / 8;
04669 
04670         len -= end_bits; /* Now len % 8 == 0 */
04671 
04672         for( ; end_bits != 0; end_bits-- )
04673             mask[last_byte_idx] |= 1 << ( 8 - end_bits );
04674     }
04675 
04676     memset( mask + offset / 8, 0xFF, len / 8 );
04677 }
04678 
04679 /*
04680  * Check that bitmask is full
04681  */
04682 static int ssl_bitmask_check( unsigned char *mask, size_t len )
04683 {
04684     size_t i;
04685 
04686     for( i = 0; i < len / 8; i++ )
04687         if( mask[i] != 0xFF )
04688             return( -1 );
04689 
04690     for( i = 0; i < len % 8; i++ )
04691         if( ( mask[len / 8] & ( 1 << ( 7 - i ) ) ) == 0 )
04692             return( -1 );
04693 
04694     return( 0 );
04695 }
04696 
04697 /* msg_len does not include the handshake header */
04698 static size_t ssl_get_reassembly_buffer_size( size_t msg_len,
04699                                               unsigned add_bitmap )
04700 {
04701     size_t alloc_len;
04702 
04703     alloc_len  = 12;                                 /* Handshake header */
04704     alloc_len += msg_len;                            /* Content buffer   */
04705 
04706     if( add_bitmap )
04707         alloc_len += msg_len / 8 + ( msg_len % 8 != 0 ); /* Bitmap       */
04708 
04709     return( alloc_len );
04710 }
04711 
04712 #endif /* MBEDTLS_SSL_PROTO_DTLS */
04713 
04714 static uint32_t ssl_get_hs_total_len( mbedtls_ssl_context const *ssl )
04715 {
04716     return( ( ssl->in_msg[1] << 16 ) |
04717             ( ssl->in_msg[2] << 8  ) |
04718               ssl->in_msg[3] );
04719 }
04720 
04721 int mbedtls_ssl_prepare_handshake_record( mbedtls_ssl_context *ssl )
04722 {
04723     if( ssl->in_msglen < mbedtls_ssl_hs_hdr_len( ssl ) )
04724     {
04725         MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake message too short: %d",
04726                             ssl->in_msglen ) );
04727         return( MBEDTLS_ERR_SSL_INVALID_RECORD );
04728     }
04729 
04730     ssl->in_hslen = mbedtls_ssl_hs_hdr_len( ssl ) + ssl_get_hs_total_len( ssl );
04731 
04732     MBEDTLS_SSL_DEBUG_MSG( 3, ( "handshake message: msglen ="
04733                         " %d, type = %d, hslen = %d",
04734                         ssl->in_msglen, ssl->in_msg[0], ssl->in_hslen ) );
04735 
04736 #if defined(MBEDTLS_SSL_PROTO_DTLS)
04737     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
04738     {
04739         int ret;
04740         unsigned int recv_msg_seq = ( ssl->in_msg[4] << 8 ) | ssl->in_msg[5];
04741 
04742         if( ssl_check_hs_header( ssl ) != 0 )
04743         {
04744             MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid handshake header" ) );
04745             return( MBEDTLS_ERR_SSL_INVALID_RECORD );
04746         }
04747 
04748         if( ssl->handshake != NULL &&
04749             ( ( ssl->state   != MBEDTLS_SSL_HANDSHAKE_OVER &&
04750                 recv_msg_seq != ssl->handshake->in_msg_seq ) ||
04751               ( ssl->state  == MBEDTLS_SSL_HANDSHAKE_OVER &&
04752                 ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_HELLO ) ) )
04753         {
04754             if( recv_msg_seq > ssl->handshake->in_msg_seq )
04755             {
04756                 MBEDTLS_SSL_DEBUG_MSG( 2, ( "received future handshake message of sequence number %u (next %u)",
04757                                             recv_msg_seq,
04758                                             ssl->handshake->in_msg_seq ) );
04759                 return( MBEDTLS_ERR_SSL_EARLY_MESSAGE );
04760             }
04761 
04762             /* Retransmit only on last message from previous flight, to avoid
04763              * too many retransmissions.
04764              * Besides, No sane server ever retransmits HelloVerifyRequest */
04765             if( recv_msg_seq == ssl->handshake->in_flight_start_seq - 1 &&
04766                 ssl->in_msg[0] != MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST )
04767             {
04768                 MBEDTLS_SSL_DEBUG_MSG( 2, ( "received message from last flight, "
04769                                     "message_seq = %d, start_of_flight = %d",
04770                                     recv_msg_seq,
04771                                     ssl->handshake->in_flight_start_seq ) );
04772 
04773                 if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )
04774                 {
04775                     MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend", ret );
04776                     return( ret );
04777                 }
04778             }
04779             else
04780             {
04781                 MBEDTLS_SSL_DEBUG_MSG( 2, ( "dropping out-of-sequence message: "
04782                                     "message_seq = %d, expected = %d",
04783                                     recv_msg_seq,
04784                                     ssl->handshake->in_msg_seq ) );
04785             }
04786 
04787             return( MBEDTLS_ERR_SSL_CONTINUE_PROCESSING );
04788         }
04789         /* Wait until message completion to increment in_msg_seq */
04790 
04791         /* Message reassembly is handled alongside buffering of future
04792          * messages; the commonality is that both handshake fragments and
04793          * future messages cannot be forwarded immediately to the
04794          * handshake logic layer. */
04795         if( ssl_hs_is_proper_fragment( ssl ) == 1 )
04796         {
04797             MBEDTLS_SSL_DEBUG_MSG( 2, ( "found fragmented DTLS handshake message" ) );
04798             return( MBEDTLS_ERR_SSL_EARLY_MESSAGE );
04799         }
04800     }
04801     else
04802 #endif /* MBEDTLS_SSL_PROTO_DTLS */
04803     /* With TLS we don't handle fragmentation (for now) */
04804     if( ssl->in_msglen < ssl->in_hslen )
04805     {
04806         MBEDTLS_SSL_DEBUG_MSG( 1, ( "TLS handshake fragmentation not supported" ) );
04807         return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
04808     }
04809 
04810     return( 0 );
04811 }
04812 
04813 void mbedtls_ssl_update_handshake_status( mbedtls_ssl_context *ssl )
04814 {
04815     mbedtls_ssl_handshake_params * const hs = ssl->handshake;
04816 
04817     if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER && hs != NULL )
04818     {
04819         ssl->handshake->update_checksum( ssl, ssl->in_msg, ssl->in_hslen );
04820     }
04821 
04822     /* Handshake message is complete, increment counter */
04823 #if defined(MBEDTLS_SSL_PROTO_DTLS)
04824     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
04825         ssl->handshake != NULL )
04826     {
04827         unsigned offset;
04828         mbedtls_ssl_hs_buffer *hs_buf;
04829 
04830         /* Increment handshake sequence number */
04831         hs->in_msg_seq++;
04832 
04833         /*
04834          * Clear up handshake buffering and reassembly structure.
04835          */
04836 
04837         /* Free first entry */
04838         ssl_buffering_free_slot( ssl, 0 );
04839 
04840         /* Shift all other entries */
04841         for( offset = 0, hs_buf = &hs->buffering.hs[0];
04842              offset + 1 < MBEDTLS_SSL_MAX_BUFFERED_HS;
04843              offset++, hs_buf++ )
04844         {
04845             *hs_buf = *(hs_buf + 1);
04846         }
04847 
04848         /* Create a fresh last entry */
04849         memset( hs_buf, 0, sizeof( mbedtls_ssl_hs_buffer ) );
04850     }
04851 #endif
04852 }
04853 
04854 /*
04855  * DTLS anti-replay: RFC 6347 4.1.2.6
04856  *
04857  * in_window is a field of bits numbered from 0 (lsb) to 63 (msb).
04858  * Bit n is set iff record number in_window_top - n has been seen.
04859  *
04860  * Usually, in_window_top is the last record number seen and the lsb of
04861  * in_window is set. The only exception is the initial state (record number 0
04862  * not seen yet).
04863  */
04864 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
04865 static void ssl_dtls_replay_reset( mbedtls_ssl_context *ssl )
04866 {
04867     ssl->in_window_top = 0;
04868     ssl->in_window = 0;
04869 }
04870 
04871 static inline uint64_t ssl_load_six_bytes( unsigned char *buf )
04872 {
04873     return( ( (uint64_t) buf[0] << 40 ) |
04874             ( (uint64_t) buf[1] << 32 ) |
04875             ( (uint64_t) buf[2] << 24 ) |
04876             ( (uint64_t) buf[3] << 16 ) |
04877             ( (uint64_t) buf[4] <<  8 ) |
04878             ( (uint64_t) buf[5]       ) );
04879 }
04880 
04881 /*
04882  * Return 0 if sequence number is acceptable, -1 otherwise
04883  */
04884 int mbedtls_ssl_dtls_replay_check( mbedtls_ssl_context const *ssl )
04885 {
04886     uint64_t rec_seqnum = ssl_load_six_bytes( ssl->in_ctr + 2 );
04887     uint64_t bit;
04888 
04889     if( ssl->conf->anti_replay == MBEDTLS_SSL_ANTI_REPLAY_DISABLED )
04890         return( 0 );
04891 
04892     if( rec_seqnum > ssl->in_window_top )
04893         return( 0 );
04894 
04895     bit = ssl->in_window_top - rec_seqnum;
04896 
04897     if( bit >= 64 )
04898         return( -1 );
04899 
04900     if( ( ssl->in_window & ( (uint64_t) 1 << bit ) ) != 0 )
04901         return( -1 );
04902 
04903     return( 0 );
04904 }
04905 
04906 /*
04907  * Update replay window on new validated record
04908  */
04909 void mbedtls_ssl_dtls_replay_update( mbedtls_ssl_context *ssl )
04910 {
04911     uint64_t rec_seqnum = ssl_load_six_bytes( ssl->in_ctr + 2 );
04912 
04913     if( ssl->conf->anti_replay == MBEDTLS_SSL_ANTI_REPLAY_DISABLED )
04914         return;
04915 
04916     if( rec_seqnum > ssl->in_window_top )
04917     {
04918         /* Update window_top and the contents of the window */
04919         uint64_t shift = rec_seqnum - ssl->in_window_top;
04920 
04921         if( shift >= 64 )
04922             ssl->in_window = 1;
04923         else
04924         {
04925             ssl->in_window <<= shift;
04926             ssl->in_window |= 1;
04927         }
04928 
04929         ssl->in_window_top = rec_seqnum;
04930     }
04931     else
04932     {
04933         /* Mark that number as seen in the current window */
04934         uint64_t bit = ssl->in_window_top - rec_seqnum;
04935 
04936         if( bit < 64 ) /* Always true, but be extra sure */
04937             ssl->in_window |= (uint64_t) 1 << bit;
04938     }
04939 }
04940 #endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */
04941 
04942 #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
04943 /* Forward declaration */
04944 static int ssl_session_reset_int( mbedtls_ssl_context *ssl, int partial );
04945 
04946 /*
04947  * Without any SSL context, check if a datagram looks like a ClientHello with
04948  * a valid cookie, and if it doesn't, generate a HelloVerifyRequest message.
04949  * Both input and output include full DTLS headers.
04950  *
04951  * - if cookie is valid, return 0
04952  * - if ClientHello looks superficially valid but cookie is not,
04953  *   fill obuf and set olen, then
04954  *   return MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED
04955  * - otherwise return a specific error code
04956  */
04957 static int ssl_check_dtls_clihlo_cookie(
04958                            mbedtls_ssl_cookie_write_t *f_cookie_write,
04959                            mbedtls_ssl_cookie_check_t *f_cookie_check,
04960                            void *p_cookie,
04961                            const unsigned char *cli_id, size_t cli_id_len,
04962                            const unsigned char *in, size_t in_len,
04963                            unsigned char *obuf, size_t buf_len, size_t *olen )
04964 {
04965     size_t sid_len, cookie_len;
04966     unsigned char *p;
04967 
04968     /*
04969      * Structure of ClientHello with record and handshake headers,
04970      * and expected values. We don't need to check a lot, more checks will be
04971      * done when actually parsing the ClientHello - skipping those checks
04972      * avoids code duplication and does not make cookie forging any easier.
04973      *
04974      *  0-0  ContentType type;                  copied, must be handshake
04975      *  1-2  ProtocolVersion version;           copied
04976      *  3-4  uint16 epoch;                      copied, must be 0
04977      *  5-10 uint48 sequence_number;            copied
04978      * 11-12 uint16 length;                     (ignored)
04979      *
04980      * 13-13 HandshakeType msg_type;            (ignored)
04981      * 14-16 uint24 length;                     (ignored)
04982      * 17-18 uint16 message_seq;                copied
04983      * 19-21 uint24 fragment_offset;            copied, must be 0
04984      * 22-24 uint24 fragment_length;            (ignored)
04985      *
04986      * 25-26 ProtocolVersion client_version;    (ignored)
04987      * 27-58 Random random;                     (ignored)
04988      * 59-xx SessionID session_id;              1 byte len + sid_len content
04989      * 60+   opaque cookie<0..2^8-1>;           1 byte len + content
04990      *       ...
04991      *
04992      * Minimum length is 61 bytes.
04993      */
04994     if( in_len < 61 ||
04995         in[0] != MBEDTLS_SSL_MSG_HANDSHAKE ||
04996         in[3] != 0 || in[4] != 0 ||
04997         in[19] != 0 || in[20] != 0 || in[21] != 0 )
04998     {
04999         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
05000     }
05001 
05002     sid_len = in[59];
05003     if( sid_len > in_len - 61 )
05004         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
05005 
05006     cookie_len = in[60 + sid_len];
05007     if( cookie_len > in_len - 60 )
05008         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
05009 
05010     if( f_cookie_check( p_cookie, in + sid_len + 61, cookie_len,
05011                         cli_id, cli_id_len ) == 0 )
05012     {
05013         /* Valid cookie */
05014         return( 0 );
05015     }
05016 
05017     /*
05018      * If we get here, we've got an invalid cookie, let's prepare HVR.
05019      *
05020      *  0-0  ContentType type;                  copied
05021      *  1-2  ProtocolVersion version;           copied
05022      *  3-4  uint16 epoch;                      copied
05023      *  5-10 uint48 sequence_number;            copied
05024      * 11-12 uint16 length;                     olen - 13
05025      *
05026      * 13-13 HandshakeType msg_type;            hello_verify_request
05027      * 14-16 uint24 length;                     olen - 25
05028      * 17-18 uint16 message_seq;                copied
05029      * 19-21 uint24 fragment_offset;            copied
05030      * 22-24 uint24 fragment_length;            olen - 25
05031      *
05032      * 25-26 ProtocolVersion server_version;    0xfe 0xff
05033      * 27-27 opaque cookie<0..2^8-1>;           cookie_len = olen - 27, cookie
05034      *
05035      * Minimum length is 28.
05036      */
05037     if( buf_len < 28 )
05038         return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
05039 
05040     /* Copy most fields and adapt others */
05041     memcpy( obuf, in, 25 );
05042     obuf[13] = MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST;
05043     obuf[25] = 0xfe;
05044     obuf[26] = 0xff;
05045 
05046     /* Generate and write actual cookie */
05047     p = obuf + 28;
05048     if( f_cookie_write( p_cookie,
05049                         &p, obuf + buf_len, cli_id, cli_id_len ) != 0 )
05050     {
05051         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
05052     }
05053 
05054     *olen = p - obuf;
05055 
05056     /* Go back and fill length fields */
05057     obuf[27] = (unsigned char)( *olen - 28 );
05058 
05059     obuf[14] = obuf[22] = (unsigned char)( ( *olen - 25 ) >> 16 );
05060     obuf[15] = obuf[23] = (unsigned char)( ( *olen - 25 ) >>  8 );
05061     obuf[16] = obuf[24] = (unsigned char)( ( *olen - 25 )       );
05062 
05063     obuf[11] = (unsigned char)( ( *olen - 13 ) >>  8 );
05064     obuf[12] = (unsigned char)( ( *olen - 13 )       );
05065 
05066     return( MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED );
05067 }
05068 
05069 /*
05070  * Handle possible client reconnect with the same UDP quadruplet
05071  * (RFC 6347 Section 4.2.8).
05072  *
05073  * Called by ssl_parse_record_header() in case we receive an epoch 0 record
05074  * that looks like a ClientHello.
05075  *
05076  * - if the input looks like a ClientHello without cookies,
05077  *   send back HelloVerifyRequest, then
05078  *   return MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED
05079  * - if the input looks like a ClientHello with a valid cookie,
05080  *   reset the session of the current context, and
05081  *   return MBEDTLS_ERR_SSL_CLIENT_RECONNECT
05082  * - if anything goes wrong, return a specific error code
05083  *
05084  * mbedtls_ssl_read_record() will ignore the record if anything else than
05085  * MBEDTLS_ERR_SSL_CLIENT_RECONNECT or 0 is returned, although this function
05086  * cannot not return 0.
05087  */
05088 static int ssl_handle_possible_reconnect( mbedtls_ssl_context *ssl )
05089 {
05090     int ret;
05091     size_t len;
05092 
05093     if( ssl->conf->f_cookie_write == NULL ||
05094         ssl->conf->f_cookie_check == NULL )
05095     {
05096         /* If we can't use cookies to verify reachability of the peer,
05097          * drop the record. */
05098         return( 0 );
05099     }
05100 
05101     ret = ssl_check_dtls_clihlo_cookie(
05102             ssl->conf->f_cookie_write,
05103             ssl->conf->f_cookie_check,
05104             ssl->conf->p_cookie,
05105             ssl->cli_id, ssl->cli_id_len,
05106             ssl->in_buf, ssl->in_left,
05107             ssl->out_buf, MBEDTLS_SSL_OUT_CONTENT_LEN, &len );
05108 
05109     MBEDTLS_SSL_DEBUG_RET( 2, "ssl_check_dtls_clihlo_cookie", ret );
05110 
05111     if( ret == MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED )
05112     {
05113         /* Don't check write errors as we can't do anything here.
05114          * If the error is permanent we'll catch it later,
05115          * if it's not, then hopefully it'll work next time. */
05116         (void) ssl->f_send( ssl->p_bio, ssl->out_buf, len );
05117         ret = 0;
05118     }
05119 
05120     if( ret == 0 )
05121     {
05122         /* Got a valid cookie, partially reset context */
05123         if( ( ret = ssl_session_reset_int( ssl, 1 ) ) != 0 )
05124         {
05125             MBEDTLS_SSL_DEBUG_RET( 1, "reset", ret );
05126             return( ret );
05127         }
05128 
05129         return( MBEDTLS_ERR_SSL_CLIENT_RECONNECT );
05130     }
05131 
05132     return( ret );
05133 }
05134 #endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */
05135 
05136 static int ssl_check_record_type( uint8_t record_type )
05137 {
05138     if( record_type != MBEDTLS_SSL_MSG_HANDSHAKE &&
05139         record_type != MBEDTLS_SSL_MSG_ALERT &&
05140         record_type != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC &&
05141         record_type != MBEDTLS_SSL_MSG_APPLICATION_DATA )
05142     {
05143         return( MBEDTLS_ERR_SSL_INVALID_RECORD );
05144     }
05145 
05146     return( 0 );
05147 }
05148 
05149 /*
05150  * ContentType type;
05151  * ProtocolVersion version;
05152  * uint16 epoch;            // DTLS only
05153  * uint48 sequence_number;  // DTLS only
05154  * uint16 length;
05155  *
05156  * Return 0 if header looks sane (and, for DTLS, the record is expected)
05157  * MBEDTLS_ERR_SSL_INVALID_RECORD if the header looks bad,
05158  * MBEDTLS_ERR_SSL_UNEXPECTED_RECORD (DTLS only) if sane but unexpected.
05159  *
05160  * With DTLS, mbedtls_ssl_read_record() will:
05161  * 1. proceed with the record if this function returns 0
05162  * 2. drop only the current record if this function returns UNEXPECTED_RECORD
05163  * 3. return CLIENT_RECONNECT if this function return that value
05164  * 4. drop the whole datagram if this function returns anything else.
05165  * Point 2 is needed when the peer is resending, and we have already received
05166  * the first record from a datagram but are still waiting for the others.
05167  */
05168 static int ssl_parse_record_header( mbedtls_ssl_context const *ssl,
05169                                     unsigned char *buf,
05170                                     size_t len,
05171                                     mbedtls_record *rec )
05172 {
05173     int major_ver, minor_ver;
05174 
05175     size_t const rec_hdr_type_offset    = 0;
05176     size_t const rec_hdr_type_len       = 1;
05177 
05178     size_t const rec_hdr_version_offset = rec_hdr_type_offset +
05179                                           rec_hdr_type_len;
05180     size_t const rec_hdr_version_len    = 2;
05181 
05182     size_t const rec_hdr_ctr_len        = 8;
05183 #if defined(MBEDTLS_SSL_PROTO_DTLS)
05184     uint32_t     rec_epoch;
05185     size_t const rec_hdr_ctr_offset     = rec_hdr_version_offset +
05186                                           rec_hdr_version_len;
05187 
05188 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
05189     size_t const rec_hdr_cid_offset     = rec_hdr_ctr_offset +
05190                                           rec_hdr_ctr_len;
05191     size_t       rec_hdr_cid_len        = 0;
05192 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
05193 #endif /* MBEDTLS_SSL_PROTO_DTLS */
05194 
05195     size_t       rec_hdr_len_offset; /* To be determined */
05196     size_t const rec_hdr_len_len    = 2;
05197 
05198     /*
05199      * Check minimum lengths for record header.
05200      */
05201 
05202 #if defined(MBEDTLS_SSL_PROTO_DTLS)
05203     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
05204     {
05205         rec_hdr_len_offset = rec_hdr_ctr_offset + rec_hdr_ctr_len;
05206     }
05207     else
05208 #endif /* MBEDTLS_SSL_PROTO_DTLS */
05209     {
05210         rec_hdr_len_offset = rec_hdr_version_offset + rec_hdr_version_len;
05211     }
05212 
05213     if( len < rec_hdr_len_offset + rec_hdr_len_len )
05214     {
05215         MBEDTLS_SSL_DEBUG_MSG( 1, ( "datagram of length %u too small to hold DTLS record header of length %u",
05216                  (unsigned) len,
05217                  (unsigned)( rec_hdr_len_len + rec_hdr_len_len ) ) );
05218         return( MBEDTLS_ERR_SSL_INVALID_RECORD );
05219     }
05220 
05221     /*
05222      * Parse and validate record content type
05223      */
05224 
05225     rec->type = buf[ rec_hdr_type_offset ];
05226 
05227     /* Check record content type */
05228 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
05229     rec->cid_len = 0;
05230 
05231     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
05232         ssl->conf->cid_len != 0                                &&
05233         rec->type == MBEDTLS_SSL_MSG_CID )
05234     {
05235         /* Shift pointers to account for record header including CID
05236          * struct {
05237          *   ContentType special_type = tls12_cid;
05238          *   ProtocolVersion version;
05239          *   uint16 epoch;
05240          *   uint48 sequence_number;
05241          *   opaque cid[cid_length]; // Additional field compared to
05242          *                           // default DTLS record format
05243          *   uint16 length;
05244          *   opaque enc_content[DTLSCiphertext.length];
05245          * } DTLSCiphertext;
05246          */
05247 
05248         /* So far, we only support static CID lengths
05249          * fixed in the configuration. */
05250         rec_hdr_cid_len = ssl->conf->cid_len;
05251         rec_hdr_len_offset += rec_hdr_cid_len;
05252 
05253         if( len < rec_hdr_len_offset + rec_hdr_len_len )
05254         {
05255             MBEDTLS_SSL_DEBUG_MSG( 1, ( "datagram of length %u too small to hold DTLS record header including CID, length %u",
05256                 (unsigned) len,
05257                 (unsigned)( rec_hdr_len_offset + rec_hdr_len_len ) ) );
05258             return( MBEDTLS_ERR_SSL_INVALID_RECORD );
05259         }
05260 
05261         /* configured CID len is guaranteed at most 255, see
05262          * MBEDTLS_SSL_CID_OUT_LEN_MAX in check_config.h */
05263         rec->cid_len = (uint8_t) rec_hdr_cid_len;
05264         memcpy( rec->cid, buf + rec_hdr_cid_offset, rec_hdr_cid_len );
05265     }
05266     else
05267 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
05268     {
05269         if( ssl_check_record_type( rec->type ) )
05270         {
05271             MBEDTLS_SSL_DEBUG_MSG( 1, ( "unknown record type %u",
05272                                         (unsigned) rec->type ) );
05273             return( MBEDTLS_ERR_SSL_INVALID_RECORD );
05274         }
05275     }
05276 
05277     /*
05278      * Parse and validate record version
05279      */
05280 
05281     rec->ver[0] = buf[ rec_hdr_version_offset + 0 ];
05282     rec->ver[1] = buf[ rec_hdr_version_offset + 1 ];
05283     mbedtls_ssl_read_version( &major_ver, &minor_ver,
05284                               ssl->conf->transport,
05285                               &rec->ver[0] );
05286 
05287     if( major_ver != ssl->major_ver )
05288     {
05289         MBEDTLS_SSL_DEBUG_MSG( 1, ( "major version mismatch" ) );
05290         return( MBEDTLS_ERR_SSL_INVALID_RECORD );
05291     }
05292 
05293     if( minor_ver > ssl->conf->max_minor_ver )
05294     {
05295         MBEDTLS_SSL_DEBUG_MSG( 1, ( "minor version mismatch" ) );
05296         return( MBEDTLS_ERR_SSL_INVALID_RECORD );
05297     }
05298 
05299     /*
05300      * Parse/Copy record sequence number.
05301      */
05302 
05303 #if defined(MBEDTLS_SSL_PROTO_DTLS)
05304     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
05305     {
05306         /* Copy explicit record sequence number from input buffer. */
05307         memcpy( &rec->ctr[0], buf + rec_hdr_ctr_offset,
05308                 rec_hdr_ctr_len );
05309     }
05310     else
05311 #endif /* MBEDTLS_SSL_PROTO_DTLS */
05312     {
05313         /* Copy implicit record sequence number from SSL context structure. */
05314         memcpy( &rec->ctr[0], ssl->in_ctr, rec_hdr_ctr_len );
05315     }
05316 
05317     /*
05318      * Parse record length.
05319      */
05320 
05321     rec->data_offset = rec_hdr_len_offset + rec_hdr_len_len;
05322     rec->data_len    = ( (size_t) buf[ rec_hdr_len_offset + 0 ] << 8 ) |
05323                        ( (size_t) buf[ rec_hdr_len_offset + 1 ] << 0 );
05324     MBEDTLS_SSL_DEBUG_BUF( 4, "input record header", buf, rec->data_offset );
05325 
05326     MBEDTLS_SSL_DEBUG_MSG( 3, ( "input record: msgtype = %d, "
05327                                 "version = [%d:%d], msglen = %d",
05328                                 rec->type,
05329                                 major_ver, minor_ver, rec->data_len ) );
05330 
05331     rec->buf     = buf;
05332     rec->buf_len = rec->data_offset + rec->data_len;
05333 
05334     if( rec->data_len == 0 )
05335         return( MBEDTLS_ERR_SSL_INVALID_RECORD );
05336 
05337     /*
05338      * DTLS-related tests.
05339      * Check epoch before checking length constraint because
05340      * the latter varies with the epoch. E.g., if a ChangeCipherSpec
05341      * message gets duplicated before the corresponding Finished message,
05342      * the second ChangeCipherSpec should be discarded because it belongs
05343      * to an old epoch, but not because its length is shorter than
05344      * the minimum record length for packets using the new record transform.
05345      * Note that these two kinds of failures are handled differently,
05346      * as an unexpected record is silently skipped but an invalid
05347      * record leads to the entire datagram being dropped.
05348      */
05349 #if defined(MBEDTLS_SSL_PROTO_DTLS)
05350     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
05351     {
05352         rec_epoch = ( rec->ctr[0] << 8 ) | rec->ctr[1];
05353 
05354         /* Check that the datagram is large enough to contain a record
05355          * of the advertised length. */
05356         if( len < rec->data_offset + rec->data_len )
05357         {
05358             MBEDTLS_SSL_DEBUG_MSG( 1, ( "Datagram of length %u too small to contain record of advertised length %u.",
05359                              (unsigned) len,
05360                              (unsigned)( rec->data_offset + rec->data_len ) ) );
05361             return( MBEDTLS_ERR_SSL_INVALID_RECORD );
05362         }
05363 
05364         /* Records from other, non-matching epochs are silently discarded.
05365          * (The case of same-port Client reconnects must be considered in
05366          *  the caller). */
05367         if( rec_epoch != ssl->in_epoch )
05368         {
05369             MBEDTLS_SSL_DEBUG_MSG( 1, ( "record from another epoch: "
05370                                         "expected %d, received %d",
05371                                         ssl->in_epoch, rec_epoch ) );
05372 
05373             /* Records from the next epoch are considered for buffering
05374              * (concretely: early Finished messages). */
05375             if( rec_epoch == (unsigned) ssl->in_epoch + 1 )
05376             {
05377                 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Consider record for buffering" ) );
05378                 return( MBEDTLS_ERR_SSL_EARLY_MESSAGE );
05379             }
05380 
05381             return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD );
05382         }
05383 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
05384         /* For records from the correct epoch, check whether their
05385          * sequence number has been seen before. */
05386         else if( mbedtls_ssl_dtls_replay_check( ssl ) != 0 )
05387         {
05388             MBEDTLS_SSL_DEBUG_MSG( 1, ( "replayed record" ) );
05389             return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD );
05390         }
05391 #endif
05392     }
05393 #endif /* MBEDTLS_SSL_PROTO_DTLS */
05394 
05395     return( 0 );
05396 }
05397 
05398 
05399 #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
05400 static int ssl_check_client_reconnect( mbedtls_ssl_context *ssl )
05401 {
05402     unsigned int rec_epoch = ( ssl->in_ctr[0] << 8 ) | ssl->in_ctr[1];
05403 
05404     /*
05405      * Check for an epoch 0 ClientHello. We can't use in_msg here to
05406      * access the first byte of record content (handshake type), as we
05407      * have an active transform (possibly iv_len != 0), so use the
05408      * fact that the record header len is 13 instead.
05409      */
05410     if( rec_epoch == 0 &&
05411         ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
05412         ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER &&
05413         ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
05414         ssl->in_left > 13 &&
05415         ssl->in_buf[13] == MBEDTLS_SSL_HS_CLIENT_HELLO )
05416     {
05417         MBEDTLS_SSL_DEBUG_MSG( 1, ( "possible client reconnect "
05418                                     "from the same port" ) );
05419         return( ssl_handle_possible_reconnect( ssl ) );
05420     }
05421 
05422     return( 0 );
05423 }
05424 #endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */
05425 
05426 /*
05427  * If applicable, decrypt (and decompress) record content
05428  */
05429 static int ssl_prepare_record_content( mbedtls_ssl_context *ssl,
05430                                        mbedtls_record *rec )
05431 {
05432     int ret, done = 0;
05433 
05434     MBEDTLS_SSL_DEBUG_BUF( 4, "input record from network",
05435                            rec->buf, rec->buf_len );
05436 
05437 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
05438     if( mbedtls_ssl_hw_record_read != NULL )
05439     {
05440         MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_read()" ) );
05441 
05442         ret = mbedtls_ssl_hw_record_read( ssl );
05443         if( ret != 0 && ret != MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH )
05444         {
05445             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_read", ret );
05446             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
05447         }
05448 
05449         if( ret == 0 )
05450             done = 1;
05451     }
05452 #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
05453     if( !done && ssl->transform_in != NULL )
05454     {
05455         unsigned char const old_msg_type = rec->type;
05456 
05457         if( ( ret = mbedtls_ssl_decrypt_buf( ssl, ssl->transform_in,
05458                                              rec ) ) != 0 )
05459         {
05460             MBEDTLS_SSL_DEBUG_RET( 1, "ssl_decrypt_buf", ret );
05461 
05462 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
05463             if( ret == MBEDTLS_ERR_SSL_UNEXPECTED_CID &&
05464                 ssl->conf->ignore_unexpected_cid
05465                     == MBEDTLS_SSL_UNEXPECTED_CID_IGNORE )
05466             {
05467                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "ignoring unexpected CID" ) );
05468                 ret = MBEDTLS_ERR_SSL_CONTINUE_PROCESSING;
05469             }
05470 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
05471 
05472             return( ret );
05473         }
05474 
05475         if( old_msg_type != rec->type )
05476         {
05477             MBEDTLS_SSL_DEBUG_MSG( 4, ( "record type after decrypt (before %d): %d",
05478                                         old_msg_type, rec->type ) );
05479         }
05480 
05481         MBEDTLS_SSL_DEBUG_BUF( 4, "input payload after decrypt",
05482                                rec->buf + rec->data_offset, rec->data_len );
05483 
05484 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
05485         /* We have already checked the record content type
05486          * in ssl_parse_record_header(), failing or silently
05487          * dropping the record in the case of an unknown type.
05488          *
05489          * Since with the use of CIDs, the record content type
05490          * might change during decryption, re-check the record
05491          * content type, but treat a failure as fatal this time. */
05492         if( ssl_check_record_type( rec->type ) )
05493         {
05494             MBEDTLS_SSL_DEBUG_MSG( 1, ( "unknown record type" ) );
05495             return( MBEDTLS_ERR_SSL_INVALID_RECORD );
05496         }
05497 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
05498 
05499         if( rec->data_len == 0 )
05500         {
05501 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
05502             if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3
05503                 && rec->type != MBEDTLS_SSL_MSG_APPLICATION_DATA )
05504             {
05505                 /* TLS v1.2 explicitly disallows zero-length messages which are not application data */
05506                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid zero-length message type: %d", ssl->in_msgtype ) );
05507                 return( MBEDTLS_ERR_SSL_INVALID_RECORD );
05508             }
05509 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
05510 
05511             ssl->nb_zero++;
05512 
05513             /*
05514              * Three or more empty messages may be a DoS attack
05515              * (excessive CPU consumption).
05516              */
05517             if( ssl->nb_zero > 3 )
05518             {
05519                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "received four consecutive empty "
05520                                             "messages, possible DoS attack" ) );
05521                 /* Treat the records as if they were not properly authenticated,
05522                  * thereby failing the connection if we see more than allowed
05523                  * by the configured bad MAC threshold. */
05524                 return( MBEDTLS_ERR_SSL_INVALID_MAC );
05525             }
05526         }
05527         else
05528             ssl->nb_zero = 0;
05529 
05530 #if defined(MBEDTLS_SSL_PROTO_DTLS)
05531         if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
05532         {
05533             ; /* in_ctr read from peer, not maintained internally */
05534         }
05535         else
05536 #endif
05537         {
05538             unsigned i;
05539             for( i = 8; i > ssl_ep_len( ssl ); i-- )
05540                 if( ++ssl->in_ctr[i - 1] != 0 )
05541                     break;
05542 
05543             /* The loop goes to its end iff the counter is wrapping */
05544             if( i == ssl_ep_len( ssl ) )
05545             {
05546                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "incoming message counter would wrap" ) );
05547                 return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
05548             }
05549         }
05550 
05551     }
05552 
05553 #if defined(MBEDTLS_ZLIB_SUPPORT)
05554     if( ssl->transform_in != NULL &&
05555         ssl->session_in->compression == MBEDTLS_SSL_COMPRESS_DEFLATE )
05556     {
05557         if( ( ret = ssl_decompress_buf( ssl ) ) != 0 )
05558         {
05559             MBEDTLS_SSL_DEBUG_RET( 1, "ssl_decompress_buf", ret );
05560             return( ret );
05561         }
05562     }
05563 #endif /* MBEDTLS_ZLIB_SUPPORT */
05564 
05565 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
05566     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
05567     {
05568         mbedtls_ssl_dtls_replay_update( ssl );
05569     }
05570 #endif
05571 
05572     /* Check actual (decrypted) record content length against
05573      * configured maximum. */
05574     if( ssl->in_msglen > MBEDTLS_SSL_IN_CONTENT_LEN )
05575     {
05576         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
05577         return( MBEDTLS_ERR_SSL_INVALID_RECORD );
05578     }
05579 
05580     return( 0 );
05581 }
05582 
05583 static void ssl_handshake_wrapup_free_hs_transform( mbedtls_ssl_context *ssl );
05584 
05585 /*
05586  * Read a record.
05587  *
05588  * Silently ignore non-fatal alert (and for DTLS, invalid records as well,
05589  * RFC 6347 4.1.2.7) and continue reading until a valid record is found.
05590  *
05591  */
05592 
05593 /* Helper functions for mbedtls_ssl_read_record(). */
05594 static int ssl_consume_current_message( mbedtls_ssl_context *ssl );
05595 static int ssl_get_next_record( mbedtls_ssl_context *ssl );
05596 static int ssl_record_is_in_progress( mbedtls_ssl_context *ssl );
05597 
05598 int mbedtls_ssl_read_record( mbedtls_ssl_context *ssl,
05599                              unsigned update_hs_digest )
05600 {
05601     int ret;
05602 
05603     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> read record" ) );
05604 
05605     if( ssl->keep_current_message == 0 )
05606     {
05607         do {
05608 
05609             ret = ssl_consume_current_message( ssl );
05610             if( ret != 0 )
05611                 return( ret );
05612 
05613             if( ssl_record_is_in_progress( ssl ) == 0 )
05614             {
05615 #if defined(MBEDTLS_SSL_PROTO_DTLS)
05616                 int have_buffered = 0;
05617 
05618                 /* We only check for buffered messages if the
05619                  * current datagram is fully consumed. */
05620                 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
05621                     ssl_next_record_is_in_datagram( ssl ) == 0 )
05622                 {
05623                     if( ssl_load_buffered_message( ssl ) == 0 )
05624                         have_buffered = 1;
05625                 }
05626 
05627                 if( have_buffered == 0 )
05628 #endif /* MBEDTLS_SSL_PROTO_DTLS */
05629                 {
05630                     ret = ssl_get_next_record( ssl );
05631                     if( ret == MBEDTLS_ERR_SSL_CONTINUE_PROCESSING )
05632                         continue;
05633 
05634                     if( ret != 0 )
05635                     {
05636                         MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_get_next_record" ), ret );
05637                         return( ret );
05638                     }
05639                 }
05640             }
05641 
05642             ret = mbedtls_ssl_handle_message_type( ssl );
05643 
05644 #if defined(MBEDTLS_SSL_PROTO_DTLS)
05645             if( ret == MBEDTLS_ERR_SSL_EARLY_MESSAGE )
05646             {
05647                 /* Buffer future message */
05648                 ret = ssl_buffer_message( ssl );
05649                 if( ret != 0 )
05650                     return( ret );
05651 
05652                 ret = MBEDTLS_ERR_SSL_CONTINUE_PROCESSING;
05653             }
05654 #endif /* MBEDTLS_SSL_PROTO_DTLS */
05655 
05656         } while( MBEDTLS_ERR_SSL_NON_FATAL           == ret  ||
05657                  MBEDTLS_ERR_SSL_CONTINUE_PROCESSING == ret );
05658 
05659         if( 0 != ret )
05660         {
05661             MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ssl_handle_message_type" ), ret );
05662             return( ret );
05663         }
05664 
05665         if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
05666             update_hs_digest == 1 )
05667         {
05668             mbedtls_ssl_update_handshake_status( ssl );
05669         }
05670     }
05671     else
05672     {
05673         MBEDTLS_SSL_DEBUG_MSG( 2, ( "reuse previously read message" ) );
05674         ssl->keep_current_message = 0;
05675     }
05676 
05677     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= read record" ) );
05678 
05679     return( 0 );
05680 }
05681 
05682 #if defined(MBEDTLS_SSL_PROTO_DTLS)
05683 static int ssl_next_record_is_in_datagram( mbedtls_ssl_context *ssl )
05684 {
05685     if( ssl->in_left > ssl->next_record_offset )
05686         return( 1 );
05687 
05688     return( 0 );
05689 }
05690 
05691 static int ssl_load_buffered_message( mbedtls_ssl_context *ssl )
05692 {
05693     mbedtls_ssl_handshake_params * const hs = ssl->handshake;
05694     mbedtls_ssl_hs_buffer * hs_buf;
05695     int ret = 0;
05696 
05697     if( hs == NULL )
05698         return( -1 );
05699 
05700     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> ssl_load_buffered_messsage" ) );
05701 
05702     if( ssl->state == MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC ||
05703         ssl->state == MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC )
05704     {
05705         /* Check if we have seen a ChangeCipherSpec before.
05706          * If yes, synthesize a CCS record. */
05707         if( !hs->buffering.seen_ccs )
05708         {
05709             MBEDTLS_SSL_DEBUG_MSG( 2, ( "CCS not seen in the current flight" ) );
05710             ret = -1;
05711             goto exit;
05712         }
05713 
05714         MBEDTLS_SSL_DEBUG_MSG( 2, ( "Injecting buffered CCS message" ) );
05715         ssl->in_msgtype = MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC;
05716         ssl->in_msglen = 1;
05717         ssl->in_msg[0] = 1;
05718 
05719         /* As long as they are equal, the exact value doesn't matter. */
05720         ssl->in_left            = 0;
05721         ssl->next_record_offset = 0;
05722 
05723         hs->buffering.seen_ccs = 0;
05724         goto exit;
05725     }
05726 
05727 #if defined(MBEDTLS_DEBUG_C)
05728     /* Debug only */
05729     {
05730         unsigned offset;
05731         for( offset = 1; offset < MBEDTLS_SSL_MAX_BUFFERED_HS; offset++ )
05732         {
05733             hs_buf = &hs->buffering.hs[offset];
05734             if( hs_buf->is_valid == 1 )
05735             {
05736                 MBEDTLS_SSL_DEBUG_MSG( 2, ( "Future message with sequence number %u %s buffered.",
05737                             hs->in_msg_seq + offset,
05738                             hs_buf->is_complete ? "fully" : "partially" ) );
05739             }
05740         }
05741     }
05742 #endif /* MBEDTLS_DEBUG_C */
05743 
05744     /* Check if we have buffered and/or fully reassembled the
05745      * next handshake message. */
05746     hs_buf = &hs->buffering.hs[0];
05747     if( ( hs_buf->is_valid == 1 ) && ( hs_buf->is_complete == 1 ) )
05748     {
05749         /* Synthesize a record containing the buffered HS message. */
05750         size_t msg_len = ( hs_buf->data[1] << 16 ) |
05751                          ( hs_buf->data[2] << 8  ) |
05752                            hs_buf->data[3];
05753 
05754         /* Double-check that we haven't accidentally buffered
05755          * a message that doesn't fit into the input buffer. */
05756         if( msg_len + 12 > MBEDTLS_SSL_IN_CONTENT_LEN )
05757         {
05758             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
05759             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
05760         }
05761 
05762         MBEDTLS_SSL_DEBUG_MSG( 2, ( "Next handshake message has been buffered - load" ) );
05763         MBEDTLS_SSL_DEBUG_BUF( 3, "Buffered handshake message (incl. header)",
05764                                hs_buf->data, msg_len + 12 );
05765 
05766         ssl->in_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
05767         ssl->in_hslen   = msg_len + 12;
05768         ssl->in_msglen  = msg_len + 12;
05769         memcpy( ssl->in_msg, hs_buf->data, ssl->in_hslen );
05770 
05771         ret = 0;
05772         goto exit;
05773     }
05774     else
05775     {
05776         MBEDTLS_SSL_DEBUG_MSG( 2, ( "Next handshake message %u not or only partially bufffered",
05777                                     hs->in_msg_seq ) );
05778     }
05779 
05780     ret = -1;
05781 
05782 exit:
05783 
05784     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= ssl_load_buffered_message" ) );
05785     return( ret );
05786 }
05787 
05788 static int ssl_buffer_make_space( mbedtls_ssl_context *ssl,
05789                                   size_t desired )
05790 {
05791     int offset;
05792     mbedtls_ssl_handshake_params * const hs = ssl->handshake;
05793     MBEDTLS_SSL_DEBUG_MSG( 2, ( "Attempt to free buffered messages to have %u bytes available",
05794                                 (unsigned) desired ) );
05795 
05796     /* Get rid of future records epoch first, if such exist. */
05797     ssl_free_buffered_record( ssl );
05798 
05799     /* Check if we have enough space available now. */
05800     if( desired <= ( MBEDTLS_SSL_DTLS_MAX_BUFFERING -
05801                      hs->buffering.total_bytes_buffered ) )
05802     {
05803         MBEDTLS_SSL_DEBUG_MSG( 2, ( "Enough space available after freeing future epoch record" ) );
05804         return( 0 );
05805     }
05806 
05807     /* We don't have enough space to buffer the next expected handshake
05808      * message. Remove buffers used for future messages to gain space,
05809      * starting with the most distant one. */
05810     for( offset = MBEDTLS_SSL_MAX_BUFFERED_HS - 1;
05811          offset >= 0; offset-- )
05812     {
05813         MBEDTLS_SSL_DEBUG_MSG( 2, ( "Free buffering slot %d to make space for reassembly of next handshake message",
05814                                     offset ) );
05815 
05816         ssl_buffering_free_slot( ssl, (uint8_t) offset );
05817 
05818         /* Check if we have enough space available now. */
05819         if( desired <= ( MBEDTLS_SSL_DTLS_MAX_BUFFERING -
05820                          hs->buffering.total_bytes_buffered ) )
05821         {
05822             MBEDTLS_SSL_DEBUG_MSG( 2, ( "Enough space available after freeing buffered HS messages" ) );
05823             return( 0 );
05824         }
05825     }
05826 
05827     return( -1 );
05828 }
05829 
05830 static int ssl_buffer_message( mbedtls_ssl_context *ssl )
05831 {
05832     int ret = 0;
05833     mbedtls_ssl_handshake_params * const hs = ssl->handshake;
05834 
05835     if( hs == NULL )
05836         return( 0 );
05837 
05838     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> ssl_buffer_message" ) );
05839 
05840     switch( ssl->in_msgtype )
05841     {
05842         case MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC:
05843             MBEDTLS_SSL_DEBUG_MSG( 2, ( "Remember CCS message" ) );
05844 
05845             hs->buffering.seen_ccs = 1;
05846             break;
05847 
05848         case MBEDTLS_SSL_MSG_HANDSHAKE:
05849         {
05850             unsigned recv_msg_seq_offset;
05851             unsigned recv_msg_seq = ( ssl->in_msg[4] << 8 ) | ssl->in_msg[5];
05852             mbedtls_ssl_hs_buffer *hs_buf;
05853             size_t msg_len = ssl->in_hslen - 12;
05854 
05855             /* We should never receive an old handshake
05856              * message - double-check nonetheless. */
05857             if( recv_msg_seq < ssl->handshake->in_msg_seq )
05858             {
05859                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
05860                 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
05861             }
05862 
05863             recv_msg_seq_offset = recv_msg_seq - ssl->handshake->in_msg_seq;
05864             if( recv_msg_seq_offset >= MBEDTLS_SSL_MAX_BUFFERED_HS )
05865             {
05866                 /* Silently ignore -- message too far in the future */
05867                 MBEDTLS_SSL_DEBUG_MSG( 2,
05868                  ( "Ignore future HS message with sequence number %u, "
05869                    "buffering window %u - %u",
05870                    recv_msg_seq, ssl->handshake->in_msg_seq,
05871                    ssl->handshake->in_msg_seq + MBEDTLS_SSL_MAX_BUFFERED_HS - 1 ) );
05872 
05873                 goto exit;
05874             }
05875 
05876             MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffering HS message with sequence number %u, offset %u ",
05877                                         recv_msg_seq, recv_msg_seq_offset ) );
05878 
05879             hs_buf = &hs->buffering.hs[ recv_msg_seq_offset ];
05880 
05881             /* Check if the buffering for this seq nr has already commenced. */
05882             if( !hs_buf->is_valid )
05883             {
05884                 size_t reassembly_buf_sz;
05885 
05886                 hs_buf->is_fragmented =
05887                     ( ssl_hs_is_proper_fragment( ssl ) == 1 );
05888 
05889                 /* We copy the message back into the input buffer
05890                  * after reassembly, so check that it's not too large.
05891                  * This is an implementation-specific limitation
05892                  * and not one from the standard, hence it is not
05893                  * checked in ssl_check_hs_header(). */
05894                 if( msg_len + 12 > MBEDTLS_SSL_IN_CONTENT_LEN )
05895                 {
05896                     /* Ignore message */
05897                     goto exit;
05898                 }
05899 
05900                 /* Check if we have enough space to buffer the message. */
05901                 if( hs->buffering.total_bytes_buffered >
05902                     MBEDTLS_SSL_DTLS_MAX_BUFFERING )
05903                 {
05904                     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
05905                     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
05906                 }
05907 
05908                 reassembly_buf_sz = ssl_get_reassembly_buffer_size( msg_len,
05909                                                        hs_buf->is_fragmented );
05910 
05911                 if( reassembly_buf_sz > ( MBEDTLS_SSL_DTLS_MAX_BUFFERING -
05912                                           hs->buffering.total_bytes_buffered ) )
05913                 {
05914                     if( recv_msg_seq_offset > 0 )
05915                     {
05916                         /* If we can't buffer a future message because
05917                          * of space limitations -- ignore. */
05918                         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",
05919                              (unsigned) msg_len, MBEDTLS_SSL_DTLS_MAX_BUFFERING,
05920                              (unsigned) hs->buffering.total_bytes_buffered ) );
05921                         goto exit;
05922                     }
05923                     else
05924                     {
05925                         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",
05926                              (unsigned) msg_len, MBEDTLS_SSL_DTLS_MAX_BUFFERING,
05927                              (unsigned) hs->buffering.total_bytes_buffered ) );
05928                     }
05929 
05930                     if( ssl_buffer_make_space( ssl, reassembly_buf_sz ) != 0 )
05931                     {
05932                         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",
05933                              (unsigned) msg_len,
05934                              (unsigned) reassembly_buf_sz,
05935                              MBEDTLS_SSL_DTLS_MAX_BUFFERING,
05936                              (unsigned) hs->buffering.total_bytes_buffered ) );
05937                         ret = MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
05938                         goto exit;
05939                     }
05940                 }
05941 
05942                 MBEDTLS_SSL_DEBUG_MSG( 2, ( "initialize reassembly, total length = %d",
05943                                             msg_len ) );
05944 
05945                 hs_buf->data = mbedtls_calloc( 1, reassembly_buf_sz );
05946                 if( hs_buf->data == NULL )
05947                 {
05948                     ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
05949                     goto exit;
05950                 }
05951                 hs_buf->data_len = reassembly_buf_sz;
05952 
05953                 /* Prepare final header: copy msg_type, length and message_seq,
05954                  * then add standardised fragment_offset and fragment_length */
05955                 memcpy( hs_buf->data, ssl->in_msg, 6 );
05956                 memset( hs_buf->data + 6, 0, 3 );
05957                 memcpy( hs_buf->data + 9, hs_buf->data + 1, 3 );
05958 
05959                 hs_buf->is_valid = 1;
05960 
05961                 hs->buffering.total_bytes_buffered += reassembly_buf_sz;
05962             }
05963             else
05964             {
05965                 /* Make sure msg_type and length are consistent */
05966                 if( memcmp( hs_buf->data, ssl->in_msg, 4 ) != 0 )
05967                 {
05968                     MBEDTLS_SSL_DEBUG_MSG( 1, ( "Fragment header mismatch - ignore" ) );
05969                     /* Ignore */
05970                     goto exit;
05971                 }
05972             }
05973 
05974             if( !hs_buf->is_complete )
05975             {
05976                 size_t frag_len, frag_off;
05977                 unsigned char * const msg = hs_buf->data + 12;
05978 
05979                 /*
05980                  * Check and copy current fragment
05981                  */
05982 
05983                 /* Validation of header fields already done in
05984                  * mbedtls_ssl_prepare_handshake_record(). */
05985                 frag_off = ssl_get_hs_frag_off( ssl );
05986                 frag_len = ssl_get_hs_frag_len( ssl );
05987 
05988                 MBEDTLS_SSL_DEBUG_MSG( 2, ( "adding fragment, offset = %d, length = %d",
05989                                             frag_off, frag_len ) );
05990                 memcpy( msg + frag_off, ssl->in_msg + 12, frag_len );
05991 
05992                 if( hs_buf->is_fragmented )
05993                 {
05994                     unsigned char * const bitmask = msg + msg_len;
05995                     ssl_bitmask_set( bitmask, frag_off, frag_len );
05996                     hs_buf->is_complete = ( ssl_bitmask_check( bitmask,
05997                                                                msg_len ) == 0 );
05998                 }
05999                 else
06000                 {
06001                     hs_buf->is_complete = 1;
06002                 }
06003 
06004                 MBEDTLS_SSL_DEBUG_MSG( 2, ( "message %scomplete",
06005                                    hs_buf->is_complete ? "" : "not yet " ) );
06006             }
06007 
06008             break;
06009         }
06010 
06011         default:
06012             /* We don't buffer other types of messages. */
06013             break;
06014     }
06015 
06016 exit:
06017 
06018     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= ssl_buffer_message" ) );
06019     return( ret );
06020 }
06021 #endif /* MBEDTLS_SSL_PROTO_DTLS */
06022 
06023 static int ssl_consume_current_message( mbedtls_ssl_context *ssl )
06024 {
06025     /*
06026      * Consume last content-layer message and potentially
06027      * update in_msglen which keeps track of the contents'
06028      * consumption state.
06029      *
06030      * (1) Handshake messages:
06031      *     Remove last handshake message, move content
06032      *     and adapt in_msglen.
06033      *
06034      * (2) Alert messages:
06035      *     Consume whole record content, in_msglen = 0.
06036      *
06037      * (3) Change cipher spec:
06038      *     Consume whole record content, in_msglen = 0.
06039      *
06040      * (4) Application data:
06041      *     Don't do anything - the record layer provides
06042      *     the application data as a stream transport
06043      *     and consumes through mbedtls_ssl_read only.
06044      *
06045      */
06046 
06047     /* Case (1): Handshake messages */
06048     if( ssl->in_hslen != 0 )
06049     {
06050         /* Hard assertion to be sure that no application data
06051          * is in flight, as corrupting ssl->in_msglen during
06052          * ssl->in_offt != NULL is fatal. */
06053         if( ssl->in_offt != NULL )
06054         {
06055             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
06056             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
06057         }
06058 
06059         /*
06060          * Get next Handshake message in the current record
06061          */
06062 
06063         /* Notes:
06064          * (1) in_hslen is not necessarily the size of the
06065          *     current handshake content: If DTLS handshake
06066          *     fragmentation is used, that's the fragment
06067          *     size instead. Using the total handshake message
06068          *     size here is faulty and should be changed at
06069          *     some point.
06070          * (2) While it doesn't seem to cause problems, one
06071          *     has to be very careful not to assume that in_hslen
06072          *     is always <= in_msglen in a sensible communication.
06073          *     Again, it's wrong for DTLS handshake fragmentation.
06074          *     The following check is therefore mandatory, and
06075          *     should not be treated as a silently corrected assertion.
06076          *     Additionally, ssl->in_hslen might be arbitrarily out of
06077          *     bounds after handling a DTLS message with an unexpected
06078          *     sequence number, see mbedtls_ssl_prepare_handshake_record.
06079          */
06080         if( ssl->in_hslen < ssl->in_msglen )
06081         {
06082             ssl->in_msglen -= ssl->in_hslen;
06083             memmove( ssl->in_msg, ssl->in_msg + ssl->in_hslen,
06084                      ssl->in_msglen );
06085 
06086             MBEDTLS_SSL_DEBUG_BUF( 4, "remaining content in record",
06087                                    ssl->in_msg, ssl->in_msglen );
06088         }
06089         else
06090         {
06091             ssl->in_msglen = 0;
06092         }
06093 
06094         ssl->in_hslen   = 0;
06095     }
06096     /* Case (4): Application data */
06097     else if( ssl->in_offt != NULL )
06098     {
06099         return( 0 );
06100     }
06101     /* Everything else (CCS & Alerts) */
06102     else
06103     {
06104         ssl->in_msglen = 0;
06105     }
06106 
06107     return( 0 );
06108 }
06109 
06110 static int ssl_record_is_in_progress( mbedtls_ssl_context *ssl )
06111 {
06112     if( ssl->in_msglen > 0 )
06113         return( 1 );
06114 
06115     return( 0 );
06116 }
06117 
06118 #if defined(MBEDTLS_SSL_PROTO_DTLS)
06119 
06120 static void ssl_free_buffered_record( mbedtls_ssl_context *ssl )
06121 {
06122     mbedtls_ssl_handshake_params * const hs = ssl->handshake;
06123     if( hs == NULL )
06124         return;
06125 
06126     if( hs->buffering.future_record.data != NULL )
06127     {
06128         hs->buffering.total_bytes_buffered -=
06129             hs->buffering.future_record.len;
06130 
06131         mbedtls_free( hs->buffering.future_record.data );
06132         hs->buffering.future_record.data = NULL;
06133     }
06134 }
06135 
06136 static int ssl_load_buffered_record( mbedtls_ssl_context *ssl )
06137 {
06138     mbedtls_ssl_handshake_params * const hs = ssl->handshake;
06139     unsigned char * rec;
06140     size_t rec_len;
06141     unsigned rec_epoch;
06142 
06143     if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM )
06144         return( 0 );
06145 
06146     if( hs == NULL )
06147         return( 0 );
06148 
06149     rec       = hs->buffering.future_record.data;
06150     rec_len   = hs->buffering.future_record.len;
06151     rec_epoch = hs->buffering.future_record.epoch;
06152 
06153     if( rec == NULL )
06154         return( 0 );
06155 
06156     /* Only consider loading future records if the
06157      * input buffer is empty. */
06158     if( ssl_next_record_is_in_datagram( ssl ) == 1 )
06159         return( 0 );
06160 
06161     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> ssl_load_buffered_record" ) );
06162 
06163     if( rec_epoch != ssl->in_epoch )
06164     {
06165         MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffered record not from current epoch." ) );
06166         goto exit;
06167     }
06168 
06169     MBEDTLS_SSL_DEBUG_MSG( 2, ( "Found buffered record from current epoch - load" ) );
06170 
06171     /* Double-check that the record is not too large */
06172     if( rec_len > MBEDTLS_SSL_IN_BUFFER_LEN -
06173         (size_t)( ssl->in_hdr - ssl->in_buf ) )
06174     {
06175         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
06176         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
06177     }
06178 
06179     memcpy( ssl->in_hdr, rec, rec_len );
06180     ssl->in_left = rec_len;
06181     ssl->next_record_offset = 0;
06182 
06183     ssl_free_buffered_record( ssl );
06184 
06185 exit:
06186     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= ssl_load_buffered_record" ) );
06187     return( 0 );
06188 }
06189 
06190 static int ssl_buffer_future_record( mbedtls_ssl_context *ssl,
06191                                      mbedtls_record const *rec )
06192 {
06193     mbedtls_ssl_handshake_params * const hs = ssl->handshake;
06194 
06195     /* Don't buffer future records outside handshakes. */
06196     if( hs == NULL )
06197         return( 0 );
06198 
06199     /* Only buffer handshake records (we are only interested
06200      * in Finished messages). */
06201     if( rec->type != MBEDTLS_SSL_MSG_HANDSHAKE )
06202         return( 0 );
06203 
06204     /* Don't buffer more than one future epoch record. */
06205     if( hs->buffering.future_record.data != NULL )
06206         return( 0 );
06207 
06208     /* Don't buffer record if there's not enough buffering space remaining. */
06209     if( rec->buf_len > ( MBEDTLS_SSL_DTLS_MAX_BUFFERING -
06210                          hs->buffering.total_bytes_buffered ) )
06211     {
06212         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",
06213                         (unsigned) rec->buf_len, MBEDTLS_SSL_DTLS_MAX_BUFFERING,
06214                         (unsigned) hs->buffering.total_bytes_buffered ) );
06215         return( 0 );
06216     }
06217 
06218     /* Buffer record */
06219     MBEDTLS_SSL_DEBUG_MSG( 2, ( "Buffer record from epoch %u",
06220                                 ssl->in_epoch + 1 ) );
06221     MBEDTLS_SSL_DEBUG_BUF( 3, "Buffered record", rec->buf, rec->buf_len );
06222 
06223     /* ssl_parse_record_header() only considers records
06224      * of the next epoch as candidates for buffering. */
06225     hs->buffering.future_record.epoch = ssl->in_epoch + 1;
06226     hs->buffering.future_record.len   = rec->buf_len;
06227 
06228     hs->buffering.future_record.data =
06229         mbedtls_calloc( 1, hs->buffering.future_record.len );
06230     if( hs->buffering.future_record.data == NULL )
06231     {
06232         /* If we run out of RAM trying to buffer a
06233          * record from the next epoch, just ignore. */
06234         return( 0 );
06235     }
06236 
06237     memcpy( hs->buffering.future_record.data, rec->buf, rec->buf_len );
06238 
06239     hs->buffering.total_bytes_buffered += rec->buf_len;
06240     return( 0 );
06241 }
06242 
06243 #endif /* MBEDTLS_SSL_PROTO_DTLS */
06244 
06245 static int ssl_get_next_record( mbedtls_ssl_context *ssl )
06246 {
06247     int ret;
06248     mbedtls_record rec;
06249 
06250 #if defined(MBEDTLS_SSL_PROTO_DTLS)
06251     /* We might have buffered a future record; if so,
06252      * and if the epoch matches now, load it.
06253      * On success, this call will set ssl->in_left to
06254      * the length of the buffered record, so that
06255      * the calls to ssl_fetch_input() below will
06256      * essentially be no-ops. */
06257     ret = ssl_load_buffered_record( ssl );
06258     if( ret != 0 )
06259         return( ret );
06260 #endif /* MBEDTLS_SSL_PROTO_DTLS */
06261 
06262     /* Ensure that we have enough space available for the default form
06263      * of TLS / DTLS record headers (5 Bytes for TLS, 13 Bytes for DTLS,
06264      * with no space for CIDs counted in). */
06265     ret = mbedtls_ssl_fetch_input( ssl, mbedtls_ssl_in_hdr_len( ssl ) );
06266     if( ret != 0 )
06267     {
06268         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret );
06269         return( ret );
06270     }
06271 
06272     ret = ssl_parse_record_header( ssl, ssl->in_hdr, ssl->in_left, &rec );
06273     if( ret != 0 )
06274     {
06275 #if defined(MBEDTLS_SSL_PROTO_DTLS)
06276         if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
06277         {
06278             if( ret == MBEDTLS_ERR_SSL_EARLY_MESSAGE )
06279             {
06280                 ret = ssl_buffer_future_record( ssl, &rec );
06281                 if( ret != 0 )
06282                     return( ret );
06283 
06284                 /* Fall through to handling of unexpected records */
06285                 ret = MBEDTLS_ERR_SSL_UNEXPECTED_RECORD;
06286             }
06287 
06288             if( ret == MBEDTLS_ERR_SSL_UNEXPECTED_RECORD )
06289             {
06290 #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
06291                 /* Reset in pointers to default state for TLS/DTLS records,
06292                  * assuming no CID and no offset between record content and
06293                  * record plaintext. */
06294                 ssl_update_in_pointers( ssl );
06295 
06296                 /* Setup internal message pointers from record structure. */
06297                 ssl->in_msgtype = rec.type;
06298 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
06299                 ssl->in_len = ssl->in_cid + rec.cid_len;
06300 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
06301                 ssl->in_iv  = ssl->in_msg = ssl->in_len + 2;
06302                 ssl->in_msglen = rec.data_len;
06303 
06304                 ret = ssl_check_client_reconnect( ssl );
06305                 if( ret != 0 )
06306                     return( ret );
06307 #endif
06308 
06309                 /* Skip unexpected record (but not whole datagram) */
06310                 ssl->next_record_offset = rec.buf_len;
06311 
06312                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding unexpected record "
06313                                             "(header)" ) );
06314             }
06315             else
06316             {
06317                 /* Skip invalid record and the rest of the datagram */
06318                 ssl->next_record_offset = 0;
06319                 ssl->in_left = 0;
06320 
06321                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding invalid record "
06322                                             "(header)" ) );
06323             }
06324 
06325             /* Get next record */
06326             return( MBEDTLS_ERR_SSL_CONTINUE_PROCESSING );
06327         }
06328         else
06329 #endif
06330         {
06331             return( ret );
06332         }
06333     }
06334 
06335 #if defined(MBEDTLS_SSL_PROTO_DTLS)
06336     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
06337     {
06338         /* Remember offset of next record within datagram. */
06339         ssl->next_record_offset = rec.buf_len;
06340         if( ssl->next_record_offset < ssl->in_left )
06341         {
06342             MBEDTLS_SSL_DEBUG_MSG( 3, ( "more than one record within datagram" ) );
06343         }
06344     }
06345     else
06346 #endif
06347     {
06348         /*
06349          * Fetch record contents from underlying transport.
06350          */
06351         ret = mbedtls_ssl_fetch_input( ssl, rec.buf_len );
06352         if( ret != 0 )
06353         {
06354             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret );
06355             return( ret );
06356         }
06357 
06358         ssl->in_left = 0;
06359     }
06360 
06361     /*
06362      * Decrypt record contents.
06363      */
06364 
06365     if( ( ret = ssl_prepare_record_content( ssl, &rec ) ) != 0 )
06366     {
06367 #if defined(MBEDTLS_SSL_PROTO_DTLS)
06368         if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
06369         {
06370             /* Silently discard invalid records */
06371             if( ret == MBEDTLS_ERR_SSL_INVALID_MAC )
06372             {
06373                 /* Except when waiting for Finished as a bad mac here
06374                  * probably means something went wrong in the handshake
06375                  * (eg wrong psk used, mitm downgrade attempt, etc.) */
06376                 if( ssl->state == MBEDTLS_SSL_CLIENT_FINISHED ||
06377                     ssl->state == MBEDTLS_SSL_SERVER_FINISHED )
06378                 {
06379 #if defined(MBEDTLS_SSL_ALL_ALERT_MESSAGES)
06380                     if( ret == MBEDTLS_ERR_SSL_INVALID_MAC )
06381                     {
06382                         mbedtls_ssl_send_alert_message( ssl,
06383                                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
06384                                 MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC );
06385                     }
06386 #endif
06387                     return( ret );
06388                 }
06389 
06390 #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT)
06391                 if( ssl->conf->badmac_limit != 0 &&
06392                     ++ssl->badmac_seen >= ssl->conf->badmac_limit )
06393                 {
06394                     MBEDTLS_SSL_DEBUG_MSG( 1, ( "too many records with bad MAC" ) );
06395                     return( MBEDTLS_ERR_SSL_INVALID_MAC );
06396                 }
06397 #endif
06398 
06399                 /* As above, invalid records cause
06400                  * dismissal of the whole datagram. */
06401 
06402                 ssl->next_record_offset = 0;
06403                 ssl->in_left = 0;
06404 
06405                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding invalid record (mac)" ) );
06406                 return( MBEDTLS_ERR_SSL_CONTINUE_PROCESSING );
06407             }
06408 
06409             return( ret );
06410         }
06411         else
06412 #endif
06413         {
06414             /* Error out (and send alert) on invalid records */
06415 #if defined(MBEDTLS_SSL_ALL_ALERT_MESSAGES)
06416             if( ret == MBEDTLS_ERR_SSL_INVALID_MAC )
06417             {
06418                 mbedtls_ssl_send_alert_message( ssl,
06419                         MBEDTLS_SSL_ALERT_LEVEL_FATAL,
06420                         MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC );
06421             }
06422 #endif
06423             return( ret );
06424         }
06425     }
06426 
06427 
06428     /* Reset in pointers to default state for TLS/DTLS records,
06429      * assuming no CID and no offset between record content and
06430      * record plaintext. */
06431     ssl_update_in_pointers( ssl );
06432 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
06433     ssl->in_len = ssl->in_cid + rec.cid_len;
06434 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
06435     ssl->in_iv  = ssl->in_msg = ssl->in_len + 2;
06436 
06437     /* The record content type may change during decryption,
06438      * so re-read it. */
06439     ssl->in_msgtype = rec.type;
06440     /* Also update the input buffer, because unfortunately
06441      * the server-side ssl_parse_client_hello() reparses the
06442      * record header when receiving a ClientHello initiating
06443      * a renegotiation. */
06444     ssl->in_hdr[0] = rec.type;
06445     ssl->in_msg    = rec.buf + rec.data_offset;
06446     ssl->in_msglen = rec.data_len;
06447     ssl->in_len[0] = (unsigned char)( rec.data_len >> 8 );
06448     ssl->in_len[1] = (unsigned char)( rec.data_len      );
06449 
06450     return( 0 );
06451 }
06452 
06453 int mbedtls_ssl_handle_message_type( mbedtls_ssl_context *ssl )
06454 {
06455     int ret;
06456 
06457     /*
06458      * Handle particular types of records
06459      */
06460     if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE )
06461     {
06462         if( ( ret = mbedtls_ssl_prepare_handshake_record( ssl ) ) != 0 )
06463         {
06464             return( ret );
06465         }
06466     }
06467 
06468     if( ssl->in_msgtype == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC )
06469     {
06470         if( ssl->in_msglen != 1 )
06471         {
06472             MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid CCS message, len: %d",
06473                            ssl->in_msglen ) );
06474             return( MBEDTLS_ERR_SSL_INVALID_RECORD );
06475         }
06476 
06477         if( ssl->in_msg[0] != 1 )
06478         {
06479             MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid CCS message, content: %02x",
06480                                         ssl->in_msg[0] ) );
06481             return( MBEDTLS_ERR_SSL_INVALID_RECORD );
06482         }
06483 
06484 #if defined(MBEDTLS_SSL_PROTO_DTLS)
06485         if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
06486             ssl->state != MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC    &&
06487             ssl->state != MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC )
06488         {
06489             if( ssl->handshake == NULL )
06490             {
06491                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "dropping ChangeCipherSpec outside handshake" ) );
06492                 return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD );
06493             }
06494 
06495             MBEDTLS_SSL_DEBUG_MSG( 1, ( "received out-of-order ChangeCipherSpec - remember" ) );
06496             return( MBEDTLS_ERR_SSL_EARLY_MESSAGE );
06497         }
06498 #endif
06499     }
06500 
06501     if( ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT )
06502     {
06503         if( ssl->in_msglen != 2 )
06504         {
06505             /* Note: Standard allows for more than one 2 byte alert
06506                to be packed in a single message, but Mbed TLS doesn't
06507                currently support this. */
06508             MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid alert message, len: %d",
06509                            ssl->in_msglen ) );
06510             return( MBEDTLS_ERR_SSL_INVALID_RECORD );
06511         }
06512 
06513         MBEDTLS_SSL_DEBUG_MSG( 2, ( "got an alert message, type: [%d:%d]",
06514                        ssl->in_msg[0], ssl->in_msg[1] ) );
06515 
06516         /*
06517          * Ignore non-fatal alerts, except close_notify and no_renegotiation
06518          */
06519         if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_FATAL )
06520         {
06521             MBEDTLS_SSL_DEBUG_MSG( 1, ( "is a fatal alert message (msg %d)",
06522                            ssl->in_msg[1] ) );
06523             return( MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE );
06524         }
06525 
06526         if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&
06527             ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY )
06528         {
06529             MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a close notify message" ) );
06530             return( MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY );
06531         }
06532 
06533 #if defined(MBEDTLS_SSL_RENEGOTIATION_ENABLED)
06534         if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&
06535             ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION )
06536         {
06537             MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a SSLv3 no renegotiation alert" ) );
06538             /* Will be handled when trying to parse ServerHello */
06539             return( 0 );
06540         }
06541 #endif
06542 
06543 #if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_SRV_C)
06544         if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 &&
06545             ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
06546             ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&
06547             ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_CERT )
06548         {
06549             MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a SSLv3 no_cert" ) );
06550             /* Will be handled in mbedtls_ssl_parse_certificate() */
06551             return( 0 );
06552         }
06553 #endif /* MBEDTLS_SSL_PROTO_SSL3 && MBEDTLS_SSL_SRV_C */
06554 
06555         /* Silently ignore: fetch new message */
06556         return MBEDTLS_ERR_SSL_NON_FATAL;
06557     }
06558 
06559 #if defined(MBEDTLS_SSL_PROTO_DTLS)
06560     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
06561     {
06562         /* Drop unexpected ApplicationData records,
06563          * except at the beginning of renegotiations */
06564         if( ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA &&
06565             ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER
06566 #if defined(MBEDTLS_SSL_RENEGOTIATION)
06567             && ! ( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
06568                    ssl->state == MBEDTLS_SSL_SERVER_HELLO )
06569 #endif
06570             )
06571         {
06572             MBEDTLS_SSL_DEBUG_MSG( 1, ( "dropping unexpected ApplicationData" ) );
06573             return( MBEDTLS_ERR_SSL_NON_FATAL );
06574         }
06575 
06576         if( ssl->handshake != NULL &&
06577             ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER  )
06578         {
06579             ssl_handshake_wrapup_free_hs_transform( ssl );
06580         }
06581     }
06582 #endif /* MBEDTLS_SSL_PROTO_DTLS */
06583 
06584     return( 0 );
06585 }
06586 
06587 int mbedtls_ssl_send_fatal_handshake_failure( mbedtls_ssl_context *ssl )
06588 {
06589     int ret;
06590 
06591     if( ( ret = mbedtls_ssl_send_alert_message( ssl,
06592                     MBEDTLS_SSL_ALERT_LEVEL_FATAL,
06593                     MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ) ) != 0 )
06594     {
06595         return( ret );
06596     }
06597 
06598     return( 0 );
06599 }
06600 
06601 int mbedtls_ssl_send_alert_message( mbedtls_ssl_context *ssl,
06602                             unsigned char level,
06603                             unsigned char message )
06604 {
06605     int ret;
06606 
06607     if( ssl == NULL || ssl->conf == NULL )
06608         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
06609 
06610     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> send alert message" ) );
06611     MBEDTLS_SSL_DEBUG_MSG( 3, ( "send alert level=%u message=%u", level, message ));
06612 
06613     ssl->out_msgtype = MBEDTLS_SSL_MSG_ALERT;
06614     ssl->out_msglen = 2;
06615     ssl->out_msg[0] = level;
06616     ssl->out_msg[1] = message;
06617 
06618     if( ( ret = mbedtls_ssl_write_record( ssl, SSL_FORCE_FLUSH ) ) != 0 )
06619     {
06620         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
06621         return( ret );
06622     }
06623     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= send alert message" ) );
06624 
06625     return( 0 );
06626 }
06627 
06628 #if defined(MBEDTLS_X509_CRT_PARSE_C)
06629 static void ssl_clear_peer_cert( mbedtls_ssl_session *session )
06630 {
06631 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
06632     if( session->peer_cert != NULL )
06633     {
06634         mbedtls_x509_crt_free( session->peer_cert );
06635         mbedtls_free( session->peer_cert );
06636         session->peer_cert = NULL;
06637     }
06638 #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
06639     if( session->peer_cert_digest != NULL )
06640     {
06641         /* Zeroization is not necessary. */
06642         mbedtls_free( session->peer_cert_digest );
06643         session->peer_cert_digest      = NULL;
06644         session->peer_cert_digest_type = MBEDTLS_MD_NONE;
06645         session->peer_cert_digest_len  = 0;
06646     }
06647 #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
06648 }
06649 #endif /* MBEDTLS_X509_CRT_PARSE_C */
06650 
06651 /*
06652  * Handshake functions
06653  */
06654 #if !defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
06655 /* No certificate support -> dummy functions */
06656 int mbedtls_ssl_write_certificate( mbedtls_ssl_context *ssl )
06657 {
06658     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
06659         ssl->handshake->ciphersuite_info;
06660 
06661     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate" ) );
06662 
06663     if( !mbedtls_ssl_ciphersuite_uses_srv_cert( ciphersuite_info ) )
06664     {
06665         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) );
06666         ssl->state++;
06667         return( 0 );
06668     }
06669 
06670     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
06671     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
06672 }
06673 
06674 int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl )
06675 {
06676     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
06677         ssl->handshake->ciphersuite_info;
06678 
06679     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) );
06680 
06681     if( !mbedtls_ssl_ciphersuite_uses_srv_cert( ciphersuite_info ) )
06682     {
06683         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
06684         ssl->state++;
06685         return( 0 );
06686     }
06687 
06688     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
06689     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
06690 }
06691 
06692 #else /* MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
06693 /* Some certificate support -> implement write and parse */
06694 
06695 int mbedtls_ssl_write_certificate( mbedtls_ssl_context *ssl )
06696 {
06697     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
06698     size_t i, n;
06699     const mbedtls_x509_crt *crt;
06700     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
06701         ssl->handshake->ciphersuite_info;
06702 
06703     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate" ) );
06704 
06705     if( !mbedtls_ssl_ciphersuite_uses_srv_cert( ciphersuite_info ) )
06706     {
06707         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) );
06708         ssl->state++;
06709         return( 0 );
06710     }
06711 
06712 #if defined(MBEDTLS_SSL_CLI_C)
06713     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
06714     {
06715         if( ssl->client_auth == 0 )
06716         {
06717             MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) );
06718             ssl->state++;
06719             return( 0 );
06720         }
06721 
06722 #if defined(MBEDTLS_SSL_PROTO_SSL3)
06723         /*
06724          * If using SSLv3 and got no cert, send an Alert message
06725          * (otherwise an empty Certificate message will be sent).
06726          */
06727         if( mbedtls_ssl_own_cert( ssl )  == NULL &&
06728             ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
06729         {
06730             ssl->out_msglen  = 2;
06731             ssl->out_msgtype = MBEDTLS_SSL_MSG_ALERT;
06732             ssl->out_msg[0]  = MBEDTLS_SSL_ALERT_LEVEL_WARNING;
06733             ssl->out_msg[1]  = MBEDTLS_SSL_ALERT_MSG_NO_CERT;
06734 
06735             MBEDTLS_SSL_DEBUG_MSG( 2, ( "got no certificate to send" ) );
06736             goto write_msg;
06737         }
06738 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
06739     }
06740 #endif /* MBEDTLS_SSL_CLI_C */
06741 #if defined(MBEDTLS_SSL_SRV_C)
06742     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
06743     {
06744         if( mbedtls_ssl_own_cert( ssl ) == NULL )
06745         {
06746             MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no certificate to send" ) );
06747             return( MBEDTLS_ERR_SSL_CERTIFICATE_REQUIRED );
06748         }
06749     }
06750 #endif
06751 
06752     MBEDTLS_SSL_DEBUG_CRT( 3, "own certificate", mbedtls_ssl_own_cert( ssl ) );
06753 
06754     /*
06755      *     0  .  0    handshake type
06756      *     1  .  3    handshake length
06757      *     4  .  6    length of all certs
06758      *     7  .  9    length of cert. 1
06759      *    10  . n-1   peer certificate
06760      *     n  . n+2   length of cert. 2
06761      *    n+3 . ...   upper level cert, etc.
06762      */
06763     i = 7;
06764     crt = mbedtls_ssl_own_cert( ssl );
06765 
06766     while( crt != NULL )
06767     {
06768         n = crt->raw.len;
06769         if( n > MBEDTLS_SSL_OUT_CONTENT_LEN - 3 - i )
06770         {
06771             MBEDTLS_SSL_DEBUG_MSG( 1, ( "certificate too large, %d > %d",
06772                            i + 3 + n, MBEDTLS_SSL_OUT_CONTENT_LEN ) );
06773             return( MBEDTLS_ERR_SSL_CERTIFICATE_TOO_LARGE );
06774         }
06775 
06776         ssl->out_msg[i    ] = (unsigned char)( n >> 16 );
06777         ssl->out_msg[i + 1] = (unsigned char)( n >>  8 );
06778         ssl->out_msg[i + 2] = (unsigned char)( n       );
06779 
06780         i += 3; memcpy( ssl->out_msg + i, crt->raw.p, n );
06781         i += n; crt = crt->next;
06782     }
06783 
06784     ssl->out_msg[4]  = (unsigned char)( ( i - 7 ) >> 16 );
06785     ssl->out_msg[5]  = (unsigned char)( ( i - 7 ) >>  8 );
06786     ssl->out_msg[6]  = (unsigned char)( ( i - 7 )       );
06787 
06788     ssl->out_msglen  = i;
06789     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
06790     ssl->out_msg[0]  = MBEDTLS_SSL_HS_CERTIFICATE;
06791 
06792 #if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_CLI_C)
06793 write_msg:
06794 #endif
06795 
06796     ssl->state++;
06797 
06798     if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
06799     {
06800         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
06801         return( ret );
06802     }
06803 
06804     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write certificate" ) );
06805 
06806     return( ret );
06807 }
06808 
06809 #if defined(MBEDTLS_SSL_RENEGOTIATION) && defined(MBEDTLS_SSL_CLI_C)
06810 
06811 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
06812 static int ssl_check_peer_crt_unchanged( mbedtls_ssl_context *ssl,
06813                                          unsigned char *crt_buf,
06814                                          size_t crt_buf_len )
06815 {
06816     mbedtls_x509_crt const * const peer_crt = ssl->session->peer_cert;
06817 
06818     if( peer_crt == NULL )
06819         return( -1 );
06820 
06821     if( peer_crt->raw.len != crt_buf_len )
06822         return( -1 );
06823 
06824     return( memcmp( peer_crt->raw.p, crt_buf, crt_buf_len ) );
06825 }
06826 #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
06827 static int ssl_check_peer_crt_unchanged( mbedtls_ssl_context *ssl,
06828                                          unsigned char *crt_buf,
06829                                          size_t crt_buf_len )
06830 {
06831     int ret;
06832     unsigned char const * const peer_cert_digest =
06833         ssl->session->peer_cert_digest;
06834     mbedtls_md_type_t const peer_cert_digest_type =
06835         ssl->session->peer_cert_digest_type;
06836     mbedtls_md_info_t const * const digest_info =
06837         mbedtls_md_info_from_type( peer_cert_digest_type );
06838     unsigned char tmp_digest[MBEDTLS_SSL_PEER_CERT_DIGEST_MAX_LEN];
06839     size_t digest_len;
06840 
06841     if( peer_cert_digest == NULL || digest_info == NULL )
06842         return( -1 );
06843 
06844     digest_len = mbedtls_md_get_size( digest_info );
06845     if( digest_len > MBEDTLS_SSL_PEER_CERT_DIGEST_MAX_LEN )
06846         return( -1 );
06847 
06848     ret = mbedtls_md( digest_info, crt_buf, crt_buf_len, tmp_digest );
06849     if( ret != 0 )
06850         return( -1 );
06851 
06852     return( memcmp( tmp_digest, peer_cert_digest, digest_len ) );
06853 }
06854 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
06855 #endif /* MBEDTLS_SSL_RENEGOTIATION && MBEDTLS_SSL_CLI_C */
06856 
06857 /*
06858  * Once the certificate message is read, parse it into a cert chain and
06859  * perform basic checks, but leave actual verification to the caller
06860  */
06861 static int ssl_parse_certificate_chain( mbedtls_ssl_context *ssl,
06862                                         mbedtls_x509_crt *chain )
06863 {
06864     int ret;
06865 #if defined(MBEDTLS_SSL_RENEGOTIATION) && defined(MBEDTLS_SSL_CLI_C)
06866     int crt_cnt=0;
06867 #endif
06868     size_t i, n;
06869     uint8_t alert;
06870 
06871     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
06872     {
06873         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
06874         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
06875                                         MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
06876         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
06877     }
06878 
06879     if( ssl->in_msg[0] != MBEDTLS_SSL_HS_CERTIFICATE ||
06880         ssl->in_hslen < mbedtls_ssl_hs_hdr_len( ssl ) + 3 + 3 )
06881     {
06882         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
06883         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
06884                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
06885         return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
06886     }
06887 
06888     i = mbedtls_ssl_hs_hdr_len( ssl );
06889 
06890     /*
06891      * Same message structure as in mbedtls_ssl_write_certificate()
06892      */
06893     n = ( ssl->in_msg[i+1] << 8 ) | ssl->in_msg[i+2];
06894 
06895     if( ssl->in_msg[i] != 0 ||
06896         ssl->in_hslen != n + 3 + mbedtls_ssl_hs_hdr_len( ssl ) )
06897     {
06898         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
06899         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
06900                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
06901         return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
06902     }
06903 
06904     /* Make &ssl->in_msg[i] point to the beginning of the CRT chain. */
06905     i += 3;
06906 
06907     /* Iterate through and parse the CRTs in the provided chain. */
06908     while( i < ssl->in_hslen )
06909     {
06910         /* Check that there's room for the next CRT's length fields. */
06911         if ( i + 3 > ssl->in_hslen ) {
06912             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
06913             mbedtls_ssl_send_alert_message( ssl,
06914                               MBEDTLS_SSL_ALERT_LEVEL_FATAL,
06915                               MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
06916             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
06917         }
06918         /* In theory, the CRT can be up to 2**24 Bytes, but we don't support
06919          * anything beyond 2**16 ~ 64K. */
06920         if( ssl->in_msg[i] != 0 )
06921         {
06922             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
06923             mbedtls_ssl_send_alert_message( ssl,
06924                             MBEDTLS_SSL_ALERT_LEVEL_FATAL,
06925                             MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
06926             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
06927         }
06928 
06929         /* Read length of the next CRT in the chain. */
06930         n = ( (unsigned int) ssl->in_msg[i + 1] << 8 )
06931             | (unsigned int) ssl->in_msg[i + 2];
06932         i += 3;
06933 
06934         if( n < 128 || i + n > ssl->in_hslen )
06935         {
06936             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
06937             mbedtls_ssl_send_alert_message( ssl,
06938                                  MBEDTLS_SSL_ALERT_LEVEL_FATAL,
06939                                  MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
06940             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
06941         }
06942 
06943         /* Check if we're handling the first CRT in the chain. */
06944 #if defined(MBEDTLS_SSL_RENEGOTIATION) && defined(MBEDTLS_SSL_CLI_C)
06945         if( crt_cnt++ == 0 &&
06946             ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&
06947             ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
06948         {
06949             /* During client-side renegotiation, check that the server's
06950              * end-CRTs hasn't changed compared to the initial handshake,
06951              * mitigating the triple handshake attack. On success, reuse
06952              * the original end-CRT instead of parsing it again. */
06953             MBEDTLS_SSL_DEBUG_MSG( 3, ( "Check that peer CRT hasn't changed during renegotiation" ) );
06954             if( ssl_check_peer_crt_unchanged( ssl,
06955                                               &ssl->in_msg[i],
06956                                               n ) != 0 )
06957             {
06958                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "new server cert during renegotiation" ) );
06959                 mbedtls_ssl_send_alert_message( ssl,
06960                                                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
06961                                                 MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED );
06962                 return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
06963             }
06964 
06965             /* Now we can safely free the original chain. */
06966             ssl_clear_peer_cert( ssl->session );
06967         }
06968 #endif /* MBEDTLS_SSL_RENEGOTIATION && MBEDTLS_SSL_CLI_C */
06969 
06970         /* Parse the next certificate in the chain. */
06971 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
06972         ret = mbedtls_x509_crt_parse_der( chain, ssl->in_msg + i, n );
06973 #else
06974         /* If we don't need to store the CRT chain permanently, parse
06975          * it in-place from the input buffer instead of making a copy. */
06976         ret = mbedtls_x509_crt_parse_der_nocopy( chain, ssl->in_msg + i, n );
06977 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
06978         switch( ret )
06979         {
06980             case 0: /*ok*/
06981             case MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG + MBEDTLS_ERR_OID_NOT_FOUND:
06982                 /* Ignore certificate with an unknown algorithm: maybe a
06983                    prior certificate was already trusted. */
06984                 break;
06985 
06986             case MBEDTLS_ERR_X509_ALLOC_FAILED:
06987                 alert = MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR;
06988                 goto crt_parse_der_failed;
06989 
06990             case MBEDTLS_ERR_X509_UNKNOWN_VERSION:
06991                 alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
06992                 goto crt_parse_der_failed;
06993 
06994             default:
06995                 alert = MBEDTLS_SSL_ALERT_MSG_BAD_CERT;
06996             crt_parse_der_failed:
06997                 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, alert );
06998                 MBEDTLS_SSL_DEBUG_RET( 1, " mbedtls_x509_crt_parse_der", ret );
06999                 return( ret );
07000         }
07001 
07002         i += n;
07003     }
07004 
07005     MBEDTLS_SSL_DEBUG_CRT( 3, "peer certificate", chain );
07006     return( 0 );
07007 }
07008 
07009 #if defined(MBEDTLS_SSL_SRV_C)
07010 static int ssl_srv_check_client_no_crt_notification( mbedtls_ssl_context *ssl )
07011 {
07012     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
07013         return( -1 );
07014 
07015 #if defined(MBEDTLS_SSL_PROTO_SSL3)
07016     /*
07017      * Check if the client sent an empty certificate
07018      */
07019     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
07020     {
07021         if( ssl->in_msglen  == 2                        &&
07022             ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT            &&
07023             ssl->in_msg[0]  == MBEDTLS_SSL_ALERT_LEVEL_WARNING  &&
07024             ssl->in_msg[1]  == MBEDTLS_SSL_ALERT_MSG_NO_CERT )
07025         {
07026             MBEDTLS_SSL_DEBUG_MSG( 1, ( "SSLv3 client has no certificate" ) );
07027             return( 0 );
07028         }
07029 
07030         return( -1 );
07031     }
07032 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
07033 
07034 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
07035     defined(MBEDTLS_SSL_PROTO_TLS1_2)
07036     if( ssl->in_hslen   == 3 + mbedtls_ssl_hs_hdr_len( ssl ) &&
07037         ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE    &&
07038         ssl->in_msg[0]  == MBEDTLS_SSL_HS_CERTIFICATE   &&
07039         memcmp( ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ), "\0\0\0", 3 ) == 0 )
07040     {
07041         MBEDTLS_SSL_DEBUG_MSG( 1, ( "TLSv1 client has no certificate" ) );
07042         return( 0 );
07043     }
07044 
07045     return( -1 );
07046 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
07047           MBEDTLS_SSL_PROTO_TLS1_2 */
07048 }
07049 #endif /* MBEDTLS_SSL_SRV_C */
07050 
07051 /* Check if a certificate message is expected.
07052  * Return either
07053  * - SSL_CERTIFICATE_EXPECTED, or
07054  * - SSL_CERTIFICATE_SKIP
07055  * indicating whether a Certificate message is expected or not.
07056  */
07057 #define SSL_CERTIFICATE_EXPECTED 0
07058 #define SSL_CERTIFICATE_SKIP     1
07059 static int ssl_parse_certificate_coordinate( mbedtls_ssl_context *ssl,
07060                                              int authmode )
07061 {
07062     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
07063         ssl->handshake->ciphersuite_info;
07064 
07065     if( !mbedtls_ssl_ciphersuite_uses_srv_cert( ciphersuite_info ) )
07066         return( SSL_CERTIFICATE_SKIP );
07067 
07068 #if defined(MBEDTLS_SSL_SRV_C)
07069     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
07070     {
07071         if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
07072             return( SSL_CERTIFICATE_SKIP );
07073 
07074         if( authmode == MBEDTLS_SSL_VERIFY_NONE )
07075         {
07076             ssl->session_negotiate->verify_result =
07077                 MBEDTLS_X509_BADCERT_SKIP_VERIFY;
07078             return( SSL_CERTIFICATE_SKIP );
07079         }
07080     }
07081 #else
07082     ((void) authmode);
07083 #endif /* MBEDTLS_SSL_SRV_C */
07084 
07085     return( SSL_CERTIFICATE_EXPECTED );
07086 }
07087 
07088 static int ssl_parse_certificate_verify( mbedtls_ssl_context *ssl,
07089                                          int authmode,
07090                                          mbedtls_x509_crt *chain,
07091                                          void *rs_ctx )
07092 {
07093     int ret = 0;
07094     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
07095         ssl->handshake->ciphersuite_info;
07096     int have_ca_chain = 0;
07097 
07098     int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *);
07099     void *p_vrfy;
07100 
07101     if( authmode == MBEDTLS_SSL_VERIFY_NONE )
07102         return( 0 );
07103 
07104     if( ssl->f_vrfy != NULL )
07105     {
07106         MBEDTLS_SSL_DEBUG_MSG( 3, ( "Use context-specific verification callback" ) );
07107         f_vrfy = ssl->f_vrfy;
07108         p_vrfy = ssl->p_vrfy;
07109     }
07110     else
07111     {
07112         MBEDTLS_SSL_DEBUG_MSG( 3, ( "Use configuration-specific verification callback" ) );
07113         f_vrfy = ssl->conf->f_vrfy;
07114         p_vrfy = ssl->conf->p_vrfy;
07115     }
07116 
07117     /*
07118      * Main check: verify certificate
07119      */
07120 #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK)
07121     if( ssl->conf->f_ca_cb != NULL )
07122     {
07123         ((void) rs_ctx);
07124         have_ca_chain = 1;
07125 
07126         MBEDTLS_SSL_DEBUG_MSG( 3, ( "use CA callback for X.509 CRT verification" ) );
07127         ret = mbedtls_x509_crt_verify_with_ca_cb(
07128             chain,
07129             ssl->conf->f_ca_cb,
07130             ssl->conf->p_ca_cb,
07131             ssl->conf->cert_profile,
07132             ssl->hostname,
07133             &ssl->session_negotiate->verify_result,
07134             f_vrfy, p_vrfy );
07135     }
07136     else
07137 #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */
07138     {
07139         mbedtls_x509_crt *ca_chain;
07140         mbedtls_x509_crl *ca_crl;
07141 
07142 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
07143         if( ssl->handshake->sni_ca_chain != NULL )
07144         {
07145             ca_chain = ssl->handshake->sni_ca_chain;
07146             ca_crl   = ssl->handshake->sni_ca_crl;
07147         }
07148         else
07149 #endif
07150         {
07151             ca_chain = ssl->conf->ca_chain;
07152             ca_crl   = ssl->conf->ca_crl;
07153         }
07154 
07155         if( ca_chain != NULL )
07156             have_ca_chain = 1;
07157 
07158         ret = mbedtls_x509_crt_verify_restartable(
07159             chain,
07160             ca_chain, ca_crl,
07161             ssl->conf->cert_profile,
07162             ssl->hostname,
07163             &ssl->session_negotiate->verify_result,
07164             f_vrfy, p_vrfy, rs_ctx );
07165     }
07166 
07167     if( ret != 0 )
07168     {
07169         MBEDTLS_SSL_DEBUG_RET( 1, "x509_verify_cert", ret );
07170     }
07171 
07172 #if defined(MBEDTLS_SSL__ECP_RESTARTABLE)
07173     if( ret == MBEDTLS_ERR_ECP_IN_PROGRESS )
07174         return( MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS );
07175 #endif
07176 
07177     /*
07178      * Secondary checks: always done, but change 'ret' only if it was 0
07179      */
07180 
07181 #if defined(MBEDTLS_ECP_C)
07182     {
07183         const mbedtls_pk_context *pk = &chain->pk;
07184 
07185         /* If certificate uses an EC key, make sure the curve is OK */
07186         if( mbedtls_pk_can_do( pk, MBEDTLS_PK_ECKEY ) &&
07187             mbedtls_ssl_check_curve( ssl, mbedtls_pk_ec( *pk )->grp .id  ) != 0 )
07188         {
07189             ssl->session_negotiate->verify_result |= MBEDTLS_X509_BADCERT_BAD_KEY;
07190 
07191             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate (EC key curve)" ) );
07192             if( ret == 0 )
07193                 ret = MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE;
07194         }
07195     }
07196 #endif /* MBEDTLS_ECP_C */
07197 
07198     if( mbedtls_ssl_check_cert_usage( chain,
07199                                       ciphersuite_info,
07200                                       ! ssl->conf->endpoint,
07201                                       &ssl->session_negotiate->verify_result ) != 0 )
07202     {
07203         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate (usage extensions)" ) );
07204         if( ret == 0 )
07205             ret = MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE;
07206     }
07207 
07208     /* mbedtls_x509_crt_verify_with_profile is supposed to report a
07209      * verification failure through MBEDTLS_ERR_X509_CERT_VERIFY_FAILED,
07210      * with details encoded in the verification flags. All other kinds
07211      * of error codes, including those from the user provided f_vrfy
07212      * functions, are treated as fatal and lead to a failure of
07213      * ssl_parse_certificate even if verification was optional. */
07214     if( authmode == MBEDTLS_SSL_VERIFY_OPTIONAL &&
07215         ( ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED ||
07216           ret == MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE ) )
07217     {
07218         ret = 0;
07219     }
07220 
07221     if( have_ca_chain == 0 && authmode == MBEDTLS_SSL_VERIFY_REQUIRED )
07222     {
07223         MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no CA chain" ) );
07224         ret = MBEDTLS_ERR_SSL_CA_CHAIN_REQUIRED;
07225     }
07226 
07227     if( ret != 0 )
07228     {
07229         uint8_t alert;
07230 
07231         /* The certificate may have been rejected for several reasons.
07232            Pick one and send the corresponding alert. Which alert to send
07233            may be a subject of debate in some cases. */
07234         if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_OTHER )
07235             alert = MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED;
07236         else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_CN_MISMATCH )
07237             alert = MBEDTLS_SSL_ALERT_MSG_BAD_CERT;
07238         else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_KEY_USAGE )
07239             alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
07240         else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_EXT_KEY_USAGE )
07241             alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
07242         else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_NS_CERT_TYPE )
07243             alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
07244         else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_BAD_PK )
07245             alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
07246         else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_BAD_KEY )
07247             alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
07248         else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_EXPIRED )
07249             alert = MBEDTLS_SSL_ALERT_MSG_CERT_EXPIRED;
07250         else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_REVOKED )
07251             alert = MBEDTLS_SSL_ALERT_MSG_CERT_REVOKED;
07252         else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_NOT_TRUSTED )
07253             alert = MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA;
07254         else
07255             alert = MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN;
07256         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
07257                                         alert );
07258     }
07259 
07260 #if defined(MBEDTLS_DEBUG_C)
07261     if( ssl->session_negotiate->verify_result != 0 )
07262     {
07263         MBEDTLS_SSL_DEBUG_MSG( 3, ( "! Certificate verification flags %x",
07264                                     ssl->session_negotiate->verify_result ) );
07265     }
07266     else
07267     {
07268         MBEDTLS_SSL_DEBUG_MSG( 3, ( "Certificate verification flags clear" ) );
07269     }
07270 #endif /* MBEDTLS_DEBUG_C */
07271 
07272     return( ret );
07273 }
07274 
07275 #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
07276 static int ssl_remember_peer_crt_digest( mbedtls_ssl_context *ssl,
07277                                          unsigned char *start, size_t len )
07278 {
07279     int ret;
07280     /* Remember digest of the peer's end-CRT. */
07281     ssl->session_negotiate->peer_cert_digest =
07282         mbedtls_calloc( 1, MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_LEN );
07283     if( ssl->session_negotiate->peer_cert_digest == NULL )
07284     {
07285         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed",
07286                                     sizeof( MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_LEN ) ) );
07287         mbedtls_ssl_send_alert_message( ssl,
07288                                         MBEDTLS_SSL_ALERT_LEVEL_FATAL,
07289                                         MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
07290 
07291         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
07292     }
07293 
07294     ret = mbedtls_md( mbedtls_md_info_from_type(
07295                           MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_TYPE ),
07296                       start, len,
07297                       ssl->session_negotiate->peer_cert_digest );
07298 
07299     ssl->session_negotiate->peer_cert_digest_type =
07300         MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_TYPE;
07301     ssl->session_negotiate->peer_cert_digest_len =
07302         MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_LEN;
07303 
07304     return( ret );
07305 }
07306 
07307 static int ssl_remember_peer_pubkey( mbedtls_ssl_context *ssl,
07308                                      unsigned char *start, size_t len )
07309 {
07310     unsigned char *end = start + len;
07311     int ret;
07312 
07313     /* Make a copy of the peer's raw public key. */
07314     mbedtls_pk_init( &ssl->handshake->peer_pubkey );
07315     ret = mbedtls_pk_parse_subpubkey( &start, end,
07316                                       &ssl->handshake->peer_pubkey );
07317     if( ret != 0 )
07318     {
07319         /* We should have parsed the public key before. */
07320         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
07321     }
07322 
07323     return( 0 );
07324 }
07325 #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
07326 
07327 int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl )
07328 {
07329     int ret = 0;
07330     int crt_expected;
07331 #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
07332     const int authmode = ssl->handshake->sni_authmode != MBEDTLS_SSL_VERIFY_UNSET
07333                        ? ssl->handshake->sni_authmode
07334                        : ssl->conf->authmode;
07335 #else
07336     const int authmode = ssl->conf->authmode;
07337 #endif
07338     void *rs_ctx = NULL;
07339     mbedtls_x509_crt *chain = NULL;
07340 
07341     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) );
07342 
07343     crt_expected = ssl_parse_certificate_coordinate( ssl, authmode );
07344     if( crt_expected == SSL_CERTIFICATE_SKIP )
07345     {
07346         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
07347         goto exit;
07348     }
07349 
07350 #if defined(MBEDTLS_SSL__ECP_RESTARTABLE)
07351     if( ssl->handshake->ecrs_enabled &&
07352         ssl->handshake->ecrs_state == ssl_ecrs_crt_verify )
07353     {
07354         chain = ssl->handshake->ecrs_peer_cert;
07355         ssl->handshake->ecrs_peer_cert = NULL;
07356         goto crt_verify;
07357     }
07358 #endif
07359 
07360     if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
07361     {
07362         /* mbedtls_ssl_read_record may have sent an alert already. We
07363            let it decide whether to alert. */
07364         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
07365         goto exit;
07366     }
07367 
07368 #if defined(MBEDTLS_SSL_SRV_C)
07369     if( ssl_srv_check_client_no_crt_notification( ssl ) == 0 )
07370     {
07371         ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_MISSING;
07372 
07373         if( authmode == MBEDTLS_SSL_VERIFY_OPTIONAL )
07374             ret = 0;
07375         else
07376             ret = MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE;
07377 
07378         goto exit;
07379     }
07380 #endif /* MBEDTLS_SSL_SRV_C */
07381 
07382     /* Clear existing peer CRT structure in case we tried to
07383      * reuse a session but it failed, and allocate a new one. */
07384     ssl_clear_peer_cert( ssl->session_negotiate );
07385 
07386     chain = mbedtls_calloc( 1, sizeof( mbedtls_x509_crt ) );
07387     if( chain == NULL )
07388     {
07389         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed",
07390                                     sizeof( mbedtls_x509_crt ) ) );
07391         mbedtls_ssl_send_alert_message( ssl,
07392                                         MBEDTLS_SSL_ALERT_LEVEL_FATAL,
07393                                         MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
07394 
07395         ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
07396         goto exit;
07397     }
07398     mbedtls_x509_crt_init( chain );
07399 
07400     ret = ssl_parse_certificate_chain( ssl, chain );
07401     if( ret != 0 )
07402         goto exit;
07403 
07404 #if defined(MBEDTLS_SSL__ECP_RESTARTABLE)
07405     if( ssl->handshake->ecrs_enabled)
07406         ssl->handshake->ecrs_state = ssl_ecrs_crt_verify;
07407 
07408 crt_verify:
07409     if( ssl->handshake->ecrs_enabled)
07410         rs_ctx = &ssl->handshake->ecrs_ctx;
07411 #endif
07412 
07413     ret = ssl_parse_certificate_verify( ssl, authmode,
07414                                         chain, rs_ctx );
07415     if( ret != 0 )
07416         goto exit;
07417 
07418 #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
07419     {
07420         unsigned char *crt_start, *pk_start;
07421         size_t crt_len, pk_len;
07422 
07423         /* We parse the CRT chain without copying, so
07424          * these pointers point into the input buffer,
07425          * and are hence still valid after freeing the
07426          * CRT chain. */
07427 
07428         crt_start = chain->raw.p;
07429         crt_len   = chain->raw.len;
07430 
07431         pk_start = chain->pk_raw.p;
07432         pk_len   = chain->pk_raw.len;
07433 
07434         /* Free the CRT structures before computing
07435          * digest and copying the peer's public key. */
07436         mbedtls_x509_crt_free( chain );
07437         mbedtls_free( chain );
07438         chain = NULL;
07439 
07440         ret = ssl_remember_peer_crt_digest( ssl, crt_start, crt_len );
07441         if( ret != 0 )
07442             goto exit;
07443 
07444         ret = ssl_remember_peer_pubkey( ssl, pk_start, pk_len );
07445         if( ret != 0 )
07446             goto exit;
07447     }
07448 #else /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
07449     /* Pass ownership to session structure. */
07450     ssl->session_negotiate->peer_cert = chain;
07451     chain = NULL;
07452 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
07453 
07454     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse certificate" ) );
07455 
07456 exit:
07457 
07458     if( ret == 0 )
07459         ssl->state++;
07460 
07461 #if defined(MBEDTLS_SSL__ECP_RESTARTABLE)
07462     if( ret == MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS )
07463     {
07464         ssl->handshake->ecrs_peer_cert = chain;
07465         chain = NULL;
07466     }
07467 #endif
07468 
07469     if( chain != NULL )
07470     {
07471         mbedtls_x509_crt_free( chain );
07472         mbedtls_free( chain );
07473     }
07474 
07475     return( ret );
07476 }
07477 #endif /* MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
07478 
07479 int mbedtls_ssl_write_change_cipher_spec( mbedtls_ssl_context *ssl )
07480 {
07481     int ret;
07482 
07483     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write change cipher spec" ) );
07484 
07485     ssl->out_msgtype = MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC;
07486     ssl->out_msglen  = 1;
07487     ssl->out_msg[0]  = 1;
07488 
07489     ssl->state++;
07490 
07491     if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
07492     {
07493         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
07494         return( ret );
07495     }
07496 
07497     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write change cipher spec" ) );
07498 
07499     return( 0 );
07500 }
07501 
07502 int mbedtls_ssl_parse_change_cipher_spec( mbedtls_ssl_context *ssl )
07503 {
07504     int ret;
07505 
07506     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse change cipher spec" ) );
07507 
07508     if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
07509     {
07510         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
07511         return( ret );
07512     }
07513 
07514     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC )
07515     {
07516         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad change cipher spec message" ) );
07517         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
07518                                         MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
07519         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
07520     }
07521 
07522     /* CCS records are only accepted if they have length 1 and content '1',
07523      * so we don't need to check this here. */
07524 
07525     /*
07526      * Switch to our negotiated transform and session parameters for inbound
07527      * data.
07528      */
07529     MBEDTLS_SSL_DEBUG_MSG( 3, ( "switching to new transform spec for inbound data" ) );
07530     ssl->transform_in = ssl->transform_negotiate;
07531     ssl->session_in = ssl->session_negotiate;
07532 
07533 #if defined(MBEDTLS_SSL_PROTO_DTLS)
07534     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
07535     {
07536 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
07537         ssl_dtls_replay_reset( ssl );
07538 #endif
07539 
07540         /* Increment epoch */
07541         if( ++ssl->in_epoch == 0 )
07542         {
07543             MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS epoch would wrap" ) );
07544             /* This is highly unlikely to happen for legitimate reasons, so
07545                treat it as an attack and don't send an alert. */
07546             return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
07547         }
07548     }
07549     else
07550 #endif /* MBEDTLS_SSL_PROTO_DTLS */
07551     memset( ssl->in_ctr, 0, 8 );
07552 
07553     ssl_update_in_pointers( ssl );
07554 
07555 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
07556     if( mbedtls_ssl_hw_record_activate != NULL )
07557     {
07558         if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_INBOUND ) ) != 0 )
07559         {
07560             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret );
07561             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
07562                                             MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
07563             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
07564         }
07565     }
07566 #endif
07567 
07568     ssl->state++;
07569 
07570     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse change cipher spec" ) );
07571 
07572     return( 0 );
07573 }
07574 
07575 void mbedtls_ssl_optimize_checksum( mbedtls_ssl_context *ssl,
07576                             const mbedtls_ssl_ciphersuite_t *ciphersuite_info )
07577 {
07578     ((void) ciphersuite_info);
07579 
07580 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
07581     defined(MBEDTLS_SSL_PROTO_TLS1_1)
07582     if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 )
07583         ssl->handshake->update_checksum = ssl_update_checksum_md5sha1;
07584     else
07585 #endif
07586 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
07587 #if defined(MBEDTLS_SHA512_C)
07588     if( ciphersuite_info->mac == MBEDTLS_MD_SHA384 )
07589         ssl->handshake->update_checksum = ssl_update_checksum_sha384;
07590     else
07591 #endif
07592 #if defined(MBEDTLS_SHA256_C)
07593     if( ciphersuite_info->mac != MBEDTLS_MD_SHA384 )
07594         ssl->handshake->update_checksum = ssl_update_checksum_sha256;
07595     else
07596 #endif
07597 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
07598     {
07599         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
07600         return;
07601     }
07602 }
07603 
07604 void mbedtls_ssl_reset_checksum( mbedtls_ssl_context *ssl )
07605 {
07606 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
07607     defined(MBEDTLS_SSL_PROTO_TLS1_1)
07608      mbedtls_md5_starts_ret( &ssl->handshake->fin_md5  );
07609     mbedtls_sha1_starts_ret( &ssl->handshake->fin_sha1 );
07610 #endif
07611 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
07612 #if defined(MBEDTLS_SHA256_C)
07613 #if defined(MBEDTLS_USE_PSA_CRYPTO)
07614     psa_hash_abort( &ssl->handshake->fin_sha256_psa );
07615     psa_hash_setup( &ssl->handshake->fin_sha256_psa, PSA_ALG_SHA_256 );
07616 #else
07617     mbedtls_sha256_starts_ret( &ssl->handshake->fin_sha256, 0 );
07618 #endif
07619 #endif
07620 #if defined(MBEDTLS_SHA512_C)
07621 #if defined(MBEDTLS_USE_PSA_CRYPTO)
07622     psa_hash_abort( &ssl->handshake->fin_sha384_psa );
07623     psa_hash_setup( &ssl->handshake->fin_sha384_psa, PSA_ALG_SHA_384 );
07624 #else
07625     mbedtls_sha512_starts_ret( &ssl->handshake->fin_sha512, 1 );
07626 #endif
07627 #endif
07628 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
07629 }
07630 
07631 static void ssl_update_checksum_start( mbedtls_ssl_context *ssl,
07632                                        const unsigned char *buf, size_t len )
07633 {
07634 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
07635     defined(MBEDTLS_SSL_PROTO_TLS1_1)
07636      mbedtls_md5_update_ret( &ssl->handshake->fin_md5 , buf, len );
07637     mbedtls_sha1_update_ret( &ssl->handshake->fin_sha1, buf, len );
07638 #endif
07639 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
07640 #if defined(MBEDTLS_SHA256_C)
07641 #if defined(MBEDTLS_USE_PSA_CRYPTO)
07642     psa_hash_update( &ssl->handshake->fin_sha256_psa, buf, len );
07643 #else
07644     mbedtls_sha256_update_ret( &ssl->handshake->fin_sha256, buf, len );
07645 #endif
07646 #endif
07647 #if defined(MBEDTLS_SHA512_C)
07648 #if defined(MBEDTLS_USE_PSA_CRYPTO)
07649     psa_hash_update( &ssl->handshake->fin_sha384_psa, buf, len );
07650 #else
07651     mbedtls_sha512_update_ret( &ssl->handshake->fin_sha512, buf, len );
07652 #endif
07653 #endif
07654 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
07655 }
07656 
07657 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
07658     defined(MBEDTLS_SSL_PROTO_TLS1_1)
07659 static void ssl_update_checksum_md5sha1( mbedtls_ssl_context *ssl,
07660                                          const unsigned char *buf, size_t len )
07661 {
07662      mbedtls_md5_update_ret( &ssl->handshake->fin_md5 , buf, len );
07663     mbedtls_sha1_update_ret( &ssl->handshake->fin_sha1, buf, len );
07664 }
07665 #endif
07666 
07667 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
07668 #if defined(MBEDTLS_SHA256_C)
07669 static void ssl_update_checksum_sha256( mbedtls_ssl_context *ssl,
07670                                         const unsigned char *buf, size_t len )
07671 {
07672 #if defined(MBEDTLS_USE_PSA_CRYPTO)
07673     psa_hash_update( &ssl->handshake->fin_sha256_psa, buf, len );
07674 #else
07675     mbedtls_sha256_update_ret( &ssl->handshake->fin_sha256, buf, len );
07676 #endif
07677 }
07678 #endif
07679 
07680 #if defined(MBEDTLS_SHA512_C)
07681 static void ssl_update_checksum_sha384( mbedtls_ssl_context *ssl,
07682                                         const unsigned char *buf, size_t len )
07683 {
07684 #if defined(MBEDTLS_USE_PSA_CRYPTO)
07685     psa_hash_update( &ssl->handshake->fin_sha384_psa, buf, len );
07686 #else
07687     mbedtls_sha512_update_ret( &ssl->handshake->fin_sha512, buf, len );
07688 #endif
07689 }
07690 #endif
07691 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
07692 
07693 #if defined(MBEDTLS_SSL_PROTO_SSL3)
07694 static void ssl_calc_finished_ssl(
07695                 mbedtls_ssl_context *ssl, unsigned char *buf, int from )
07696 {
07697     const char *sender;
07698     mbedtls_md5_context  md5;
07699     mbedtls_sha1_context sha1;
07700 
07701     unsigned char padbuf[48];
07702     unsigned char md5sum[16];
07703     unsigned char sha1sum[20];
07704 
07705     mbedtls_ssl_session *session = ssl->session_negotiate;
07706     if( !session )
07707         session = ssl->session;
07708 
07709     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc  finished ssl" ) );
07710 
07711     mbedtls_md5_init( &md5 );
07712     mbedtls_sha1_init( &sha1 );
07713 
07714     mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
07715     mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
07716 
07717     /*
07718      * SSLv3:
07719      *   hash =
07720      *      MD5( master + pad2 +
07721      *          MD5( handshake + sender + master + pad1 ) )
07722      *   + SHA1( master + pad2 +
07723      *         SHA1( handshake + sender + master + pad1 ) )
07724      */
07725 
07726 #if !defined(MBEDTLS_MD5_ALT)
07727     MBEDTLS_SSL_DEBUG_BUF( 4, "finished  md5 state", (unsigned char *)
07728                     md5.state , sizeof(  md5.state  ) );
07729 #endif
07730 
07731 #if !defined(MBEDTLS_SHA1_ALT)
07732     MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha1 state", (unsigned char *)
07733                    sha1.state , sizeof( sha1.state  ) );
07734 #endif
07735 
07736     sender = ( from == MBEDTLS_SSL_IS_CLIENT ) ? "CLNT"
07737                                        : "SRVR";
07738 
07739     memset( padbuf, 0x36, 48 );
07740 
07741     mbedtls_md5_update_ret( &md5, (const unsigned char *) sender, 4 );
07742     mbedtls_md5_update_ret( &md5, session->master, 48 );
07743     mbedtls_md5_update_ret( &md5, padbuf, 48 );
07744     mbedtls_md5_finish_ret( &md5, md5sum );
07745 
07746     mbedtls_sha1_update_ret( &sha1, (const unsigned char *) sender, 4 );
07747     mbedtls_sha1_update_ret( &sha1, session->master, 48 );
07748     mbedtls_sha1_update_ret( &sha1, padbuf, 40 );
07749     mbedtls_sha1_finish_ret( &sha1, sha1sum );
07750 
07751     memset( padbuf, 0x5C, 48 );
07752 
07753     mbedtls_md5_starts_ret( &md5 );
07754     mbedtls_md5_update_ret( &md5, session->master, 48 );
07755     mbedtls_md5_update_ret( &md5, padbuf, 48 );
07756     mbedtls_md5_update_ret( &md5, md5sum, 16 );
07757     mbedtls_md5_finish_ret( &md5, buf );
07758 
07759     mbedtls_sha1_starts_ret( &sha1 );
07760     mbedtls_sha1_update_ret( &sha1, session->master, 48 );
07761     mbedtls_sha1_update_ret( &sha1, padbuf , 40 );
07762     mbedtls_sha1_update_ret( &sha1, sha1sum, 20 );
07763     mbedtls_sha1_finish_ret( &sha1, buf + 16 );
07764 
07765     MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, 36 );
07766 
07767     mbedtls_md5_free(  &md5  );
07768     mbedtls_sha1_free( &sha1 );
07769 
07770     mbedtls_platform_zeroize(  padbuf, sizeof(  padbuf ) );
07771     mbedtls_platform_zeroize(  md5sum, sizeof(  md5sum ) );
07772     mbedtls_platform_zeroize( sha1sum, sizeof( sha1sum ) );
07773 
07774     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc  finished" ) );
07775 }
07776 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
07777 
07778 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
07779 static void ssl_calc_finished_tls(
07780                 mbedtls_ssl_context *ssl, unsigned char *buf, int from )
07781 {
07782     int len = 12;
07783     const char *sender;
07784     mbedtls_md5_context  md5;
07785     mbedtls_sha1_context sha1;
07786     unsigned char padbuf[36];
07787 
07788     mbedtls_ssl_session *session = ssl->session_negotiate;
07789     if( !session )
07790         session = ssl->session;
07791 
07792     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc  finished tls" ) );
07793 
07794     mbedtls_md5_init( &md5 );
07795     mbedtls_sha1_init( &sha1 );
07796 
07797     mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
07798     mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
07799 
07800     /*
07801      * TLSv1:
07802      *   hash = PRF( master, finished_label,
07803      *               MD5( handshake ) + SHA1( handshake ) )[0..11]
07804      */
07805 
07806 #if !defined(MBEDTLS_MD5_ALT)
07807     MBEDTLS_SSL_DEBUG_BUF( 4, "finished  md5 state", (unsigned char *)
07808                     md5.state , sizeof(  md5.state  ) );
07809 #endif
07810 
07811 #if !defined(MBEDTLS_SHA1_ALT)
07812     MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha1 state", (unsigned char *)
07813                    sha1.state , sizeof( sha1.state  ) );
07814 #endif
07815 
07816     sender = ( from == MBEDTLS_SSL_IS_CLIENT )
07817              ? "client finished"
07818              : "server finished";
07819 
07820     mbedtls_md5_finish_ret(  &md5, padbuf );
07821     mbedtls_sha1_finish_ret( &sha1, padbuf + 16 );
07822 
07823     ssl->handshake->tls_prf( session->master, 48, sender,
07824                              padbuf, 36, buf, len );
07825 
07826     MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len );
07827 
07828     mbedtls_md5_free(  &md5  );
07829     mbedtls_sha1_free( &sha1 );
07830 
07831     mbedtls_platform_zeroize(  padbuf, sizeof(  padbuf ) );
07832 
07833     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc  finished" ) );
07834 }
07835 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
07836 
07837 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
07838 #if defined(MBEDTLS_SHA256_C)
07839 static void ssl_calc_finished_tls_sha256(
07840                 mbedtls_ssl_context *ssl, unsigned char *buf, int from )
07841 {
07842     int len = 12;
07843     const char *sender;
07844     unsigned char padbuf[32];
07845 #if defined(MBEDTLS_USE_PSA_CRYPTO)
07846     size_t hash_size;
07847     psa_hash_operation_t sha256_psa = PSA_HASH_OPERATION_INIT;
07848     psa_status_t status;
07849 #else
07850     mbedtls_sha256_context sha256;
07851 #endif
07852 
07853     mbedtls_ssl_session *session = ssl->session_negotiate;
07854     if( !session )
07855         session = ssl->session;
07856 
07857     sender = ( from == MBEDTLS_SSL_IS_CLIENT )
07858              ? "client finished"
07859              : "server finished";
07860 
07861 #if defined(MBEDTLS_USE_PSA_CRYPTO)
07862     sha256_psa = psa_hash_operation_init();
07863 
07864     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc PSA finished tls sha256" ) );
07865 
07866     status = psa_hash_clone( &ssl->handshake->fin_sha256_psa, &sha256_psa );
07867     if( status != PSA_SUCCESS )
07868     {
07869         MBEDTLS_SSL_DEBUG_MSG( 2, ( "PSA hash clone failed" ) );
07870         return;
07871     }
07872 
07873     status = psa_hash_finish( &sha256_psa, padbuf, sizeof( padbuf ), &hash_size );
07874     if( status != PSA_SUCCESS )
07875     {
07876         MBEDTLS_SSL_DEBUG_MSG( 2, ( "PSA hash finish failed" ) );
07877         return;
07878     }
07879     MBEDTLS_SSL_DEBUG_BUF( 3, "PSA calculated padbuf", padbuf, 32 );
07880 #else
07881 
07882     mbedtls_sha256_init( &sha256 );
07883 
07884     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc  finished tls sha256" ) );
07885 
07886     mbedtls_sha256_clone( &sha256, &ssl->handshake->fin_sha256 );
07887 
07888     /*
07889      * TLSv1.2:
07890      *   hash = PRF( master, finished_label,
07891      *               Hash( handshake ) )[0.11]
07892      */
07893 
07894 #if !defined(MBEDTLS_SHA256_ALT)
07895     MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha2 state", (unsigned char *)
07896                    sha256.state , sizeof( sha256.state  ) );
07897 #endif
07898 
07899     mbedtls_sha256_finish_ret( &sha256, padbuf );
07900     mbedtls_sha256_free( &sha256 );
07901 #endif /* MBEDTLS_USE_PSA_CRYPTO */
07902 
07903     ssl->handshake->tls_prf( session->master, 48, sender,
07904                              padbuf, 32, buf, len );
07905 
07906     MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len );
07907 
07908     mbedtls_platform_zeroize(  padbuf, sizeof(  padbuf ) );
07909 
07910     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc  finished" ) );
07911 }
07912 #endif /* MBEDTLS_SHA256_C */
07913 
07914 #if defined(MBEDTLS_SHA512_C)
07915 static void ssl_calc_finished_tls_sha384(
07916                 mbedtls_ssl_context *ssl, unsigned char *buf, int from )
07917 {
07918     int len = 12;
07919     const char *sender;
07920     unsigned char padbuf[48];
07921 #if defined(MBEDTLS_USE_PSA_CRYPTO)
07922     size_t hash_size;
07923     psa_hash_operation_t sha384_psa = PSA_HASH_OPERATION_INIT;
07924     psa_status_t status;
07925 #else
07926     mbedtls_sha512_context sha512;
07927 #endif
07928 
07929     mbedtls_ssl_session *session = ssl->session_negotiate;
07930     if( !session )
07931         session = ssl->session;
07932 
07933     sender = ( from == MBEDTLS_SSL_IS_CLIENT )
07934                 ? "client finished"
07935                 : "server finished";
07936 
07937 #if defined(MBEDTLS_USE_PSA_CRYPTO)
07938     sha384_psa = psa_hash_operation_init();
07939 
07940     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc PSA finished tls sha384" ) );
07941 
07942     status = psa_hash_clone( &ssl->handshake->fin_sha384_psa, &sha384_psa );
07943     if( status != PSA_SUCCESS )
07944     {
07945         MBEDTLS_SSL_DEBUG_MSG( 2, ( "PSA hash clone failed" ) );
07946         return;
07947     }
07948 
07949     status = psa_hash_finish( &sha384_psa, padbuf, sizeof( padbuf ), &hash_size );
07950     if( status != PSA_SUCCESS )
07951     {
07952         MBEDTLS_SSL_DEBUG_MSG( 2, ( "PSA hash finish failed" ) );
07953         return;
07954     }
07955     MBEDTLS_SSL_DEBUG_BUF( 3, "PSA calculated padbuf", padbuf, 48 );
07956 #else
07957     mbedtls_sha512_init( &sha512 );
07958 
07959     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc  finished tls sha384" ) );
07960 
07961     mbedtls_sha512_clone( &sha512, &ssl->handshake->fin_sha512 );
07962 
07963     /*
07964      * TLSv1.2:
07965      *   hash = PRF( master, finished_label,
07966      *               Hash( handshake ) )[0.11]
07967      */
07968 
07969 #if !defined(MBEDTLS_SHA512_ALT)
07970     MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha512 state", (unsigned char *)
07971                    sha512.state , sizeof( sha512.state  ) );
07972 #endif
07973 
07974     mbedtls_sha512_finish_ret( &sha512, padbuf );
07975     mbedtls_sha512_free( &sha512 );
07976 #endif
07977 
07978     ssl->handshake->tls_prf( session->master, 48, sender,
07979                              padbuf, 48, buf, len );
07980 
07981     MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len );
07982 
07983     mbedtls_platform_zeroize(  padbuf, sizeof( padbuf ) );
07984 
07985     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc  finished" ) );
07986 }
07987 #endif /* MBEDTLS_SHA512_C */
07988 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
07989 
07990 static void ssl_handshake_wrapup_free_hs_transform( mbedtls_ssl_context *ssl )
07991 {
07992     MBEDTLS_SSL_DEBUG_MSG( 3, ( "=> handshake wrapup: final free" ) );
07993 
07994     /*
07995      * Free our handshake params
07996      */
07997     mbedtls_ssl_handshake_free( ssl );
07998     mbedtls_free( ssl->handshake );
07999     ssl->handshake = NULL;
08000 
08001     /*
08002      * Free the previous transform and swith in the current one
08003      */
08004     if( ssl->transform )
08005     {
08006         mbedtls_ssl_transform_free( ssl->transform );
08007         mbedtls_free( ssl->transform );
08008     }
08009     ssl->transform = ssl->transform_negotiate;
08010     ssl->transform_negotiate = NULL;
08011 
08012     MBEDTLS_SSL_DEBUG_MSG( 3, ( "<= handshake wrapup: final free" ) );
08013 }
08014 
08015 void mbedtls_ssl_handshake_wrapup( mbedtls_ssl_context *ssl )
08016 {
08017     int resume = ssl->handshake->resume;
08018 
08019     MBEDTLS_SSL_DEBUG_MSG( 3, ( "=> handshake wrapup" ) );
08020 
08021 #if defined(MBEDTLS_SSL_RENEGOTIATION)
08022     if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
08023     {
08024         ssl->renego_status =  MBEDTLS_SSL_RENEGOTIATION_DONE;
08025         ssl->renego_records_seen = 0;
08026     }
08027 #endif
08028 
08029     /*
08030      * Free the previous session and switch in the current one
08031      */
08032     if( ssl->session )
08033     {
08034 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
08035         /* RFC 7366 3.1: keep the EtM state */
08036         ssl->session_negotiate->encrypt_then_mac =
08037                   ssl->session->encrypt_then_mac;
08038 #endif
08039 
08040         mbedtls_ssl_session_free( ssl->session );
08041         mbedtls_free( ssl->session );
08042     }
08043     ssl->session = ssl->session_negotiate;
08044     ssl->session_negotiate = NULL;
08045 
08046     /*
08047      * Add cache entry
08048      */
08049     if( ssl->conf->f_set_cache != NULL &&
08050         ssl->session->id_len != 0 &&
08051         resume == 0 )
08052     {
08053         if( ssl->conf->f_set_cache( ssl->conf->p_cache, ssl->session ) != 0 )
08054             MBEDTLS_SSL_DEBUG_MSG( 1, ( "cache did not store session" ) );
08055     }
08056 
08057 #if defined(MBEDTLS_SSL_PROTO_DTLS)
08058     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
08059         ssl->handshake->flight != NULL )
08060     {
08061         /* Cancel handshake timer */
08062         ssl_set_timer( ssl, 0 );
08063 
08064         /* Keep last flight around in case we need to resend it:
08065          * we need the handshake and transform structures for that */
08066         MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip freeing handshake and transform" ) );
08067     }
08068     else
08069 #endif
08070         ssl_handshake_wrapup_free_hs_transform( ssl );
08071 
08072     ssl->state++;
08073 
08074     MBEDTLS_SSL_DEBUG_MSG( 3, ( "<= handshake wrapup" ) );
08075 }
08076 
08077 int mbedtls_ssl_write_finished( mbedtls_ssl_context *ssl )
08078 {
08079     int ret, hash_len;
08080 
08081     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write finished" ) );
08082 
08083     ssl_update_out_pointers( ssl, ssl->transform_negotiate );
08084 
08085     ssl->handshake->calc_finished( ssl, ssl->out_msg + 4, ssl->conf->endpoint );
08086 
08087     /*
08088      * RFC 5246 7.4.9 (Page 63) says 12 is the default length and ciphersuites
08089      * may define some other value. Currently (early 2016), no defined
08090      * ciphersuite does this (and this is unlikely to change as activity has
08091      * moved to TLS 1.3 now) so we can keep the hardcoded 12 here.
08092      */
08093     hash_len = ( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) ? 36 : 12;
08094 
08095 #if defined(MBEDTLS_SSL_RENEGOTIATION)
08096     ssl->verify_data_len = hash_len;
08097     memcpy( ssl->own_verify_data, ssl->out_msg + 4, hash_len );
08098 #endif
08099 
08100     ssl->out_msglen  = 4 + hash_len;
08101     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
08102     ssl->out_msg[0]  = MBEDTLS_SSL_HS_FINISHED;
08103 
08104     /*
08105      * In case of session resuming, invert the client and server
08106      * ChangeCipherSpec messages order.
08107      */
08108     if( ssl->handshake->resume != 0 )
08109     {
08110 #if defined(MBEDTLS_SSL_CLI_C)
08111         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
08112             ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
08113 #endif
08114 #if defined(MBEDTLS_SSL_SRV_C)
08115         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
08116             ssl->state = MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC;
08117 #endif
08118     }
08119     else
08120         ssl->state++;
08121 
08122     /*
08123      * Switch to our negotiated transform and session parameters for outbound
08124      * data.
08125      */
08126     MBEDTLS_SSL_DEBUG_MSG( 3, ( "switching to new transform spec for outbound data" ) );
08127 
08128 #if defined(MBEDTLS_SSL_PROTO_DTLS)
08129     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
08130     {
08131         unsigned char i;
08132 
08133         /* Remember current epoch settings for resending */
08134         ssl->handshake->alt_transform_out = ssl->transform_out;
08135         memcpy( ssl->handshake->alt_out_ctr, ssl->cur_out_ctr, 8 );
08136 
08137         /* Set sequence_number to zero */
08138         memset( ssl->cur_out_ctr + 2, 0, 6 );
08139 
08140         /* Increment epoch */
08141         for( i = 2; i > 0; i-- )
08142             if( ++ssl->cur_out_ctr[i - 1] != 0 )
08143                 break;
08144 
08145         /* The loop goes to its end iff the counter is wrapping */
08146         if( i == 0 )
08147         {
08148             MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS epoch would wrap" ) );
08149             return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
08150         }
08151     }
08152     else
08153 #endif /* MBEDTLS_SSL_PROTO_DTLS */
08154     memset( ssl->cur_out_ctr, 0, 8 );
08155 
08156     ssl->transform_out = ssl->transform_negotiate;
08157     ssl->session_out = ssl->session_negotiate;
08158 
08159 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
08160     if( mbedtls_ssl_hw_record_activate != NULL )
08161     {
08162         if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_OUTBOUND ) ) != 0 )
08163         {
08164             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret );
08165             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
08166         }
08167     }
08168 #endif
08169 
08170 #if defined(MBEDTLS_SSL_PROTO_DTLS)
08171     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
08172         mbedtls_ssl_send_flight_completed( ssl );
08173 #endif
08174 
08175     if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
08176     {
08177         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
08178         return( ret );
08179     }
08180 
08181 #if defined(MBEDTLS_SSL_PROTO_DTLS)
08182     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
08183         ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 )
08184     {
08185         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flight_transmit", ret );
08186         return( ret );
08187     }
08188 #endif
08189 
08190     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write finished" ) );
08191 
08192     return( 0 );
08193 }
08194 
08195 #if defined(MBEDTLS_SSL_PROTO_SSL3)
08196 #define SSL_MAX_HASH_LEN 36
08197 #else
08198 #define SSL_MAX_HASH_LEN 12
08199 #endif
08200 
08201 int mbedtls_ssl_parse_finished( mbedtls_ssl_context *ssl )
08202 {
08203     int ret;
08204     unsigned int hash_len;
08205     unsigned char buf[SSL_MAX_HASH_LEN];
08206 
08207     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse finished" ) );
08208 
08209     ssl->handshake->calc_finished( ssl, buf, ssl->conf->endpoint ^ 1 );
08210 
08211     if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
08212     {
08213         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
08214         return( ret );
08215     }
08216 
08217     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
08218     {
08219         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
08220         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
08221                                         MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
08222         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
08223     }
08224 
08225     /* There is currently no ciphersuite using another length with TLS 1.2 */
08226 #if defined(MBEDTLS_SSL_PROTO_SSL3)
08227     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
08228         hash_len = 36;
08229     else
08230 #endif
08231         hash_len = 12;
08232 
08233     if( ssl->in_msg[0] != MBEDTLS_SSL_HS_FINISHED ||
08234         ssl->in_hslen  != mbedtls_ssl_hs_hdr_len( ssl ) + hash_len )
08235     {
08236         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
08237         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
08238                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
08239         return( MBEDTLS_ERR_SSL_BAD_HS_FINISHED );
08240     }
08241 
08242     if( mbedtls_ssl_safer_memcmp( ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ),
08243                       buf, hash_len ) != 0 )
08244     {
08245         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
08246         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
08247                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
08248         return( MBEDTLS_ERR_SSL_BAD_HS_FINISHED );
08249     }
08250 
08251 #if defined(MBEDTLS_SSL_RENEGOTIATION)
08252     ssl->verify_data_len = hash_len;
08253     memcpy( ssl->peer_verify_data, buf, hash_len );
08254 #endif
08255 
08256     if( ssl->handshake->resume != 0 )
08257     {
08258 #if defined(MBEDTLS_SSL_CLI_C)
08259         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
08260             ssl->state = MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC;
08261 #endif
08262 #if defined(MBEDTLS_SSL_SRV_C)
08263         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
08264             ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
08265 #endif
08266     }
08267     else
08268         ssl->state++;
08269 
08270 #if defined(MBEDTLS_SSL_PROTO_DTLS)
08271     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
08272         mbedtls_ssl_recv_flight_completed( ssl );
08273 #endif
08274 
08275     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse finished" ) );
08276 
08277     return( 0 );
08278 }
08279 
08280 static void ssl_handshake_params_init( mbedtls_ssl_handshake_params *handshake )
08281 {
08282     memset( handshake, 0, sizeof( mbedtls_ssl_handshake_params ) );
08283 
08284 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
08285     defined(MBEDTLS_SSL_PROTO_TLS1_1)
08286      mbedtls_md5_init(   &handshake->fin_md5  );
08287     mbedtls_sha1_init(   &handshake->fin_sha1 );
08288      mbedtls_md5_starts_ret( &handshake->fin_md5  );
08289     mbedtls_sha1_starts_ret( &handshake->fin_sha1 );
08290 #endif
08291 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
08292 #if defined(MBEDTLS_SHA256_C)
08293 #if defined(MBEDTLS_USE_PSA_CRYPTO)
08294     handshake->fin_sha256_psa = psa_hash_operation_init();
08295     psa_hash_setup( &handshake->fin_sha256_psa, PSA_ALG_SHA_256 );
08296 #else
08297     mbedtls_sha256_init(   &handshake->fin_sha256    );
08298     mbedtls_sha256_starts_ret( &handshake->fin_sha256, 0 );
08299 #endif
08300 #endif
08301 #if defined(MBEDTLS_SHA512_C)
08302 #if defined(MBEDTLS_USE_PSA_CRYPTO)
08303     handshake->fin_sha384_psa = psa_hash_operation_init();
08304     psa_hash_setup( &handshake->fin_sha384_psa, PSA_ALG_SHA_384 );
08305 #else
08306     mbedtls_sha512_init(   &handshake->fin_sha512    );
08307     mbedtls_sha512_starts_ret( &handshake->fin_sha512, 1 );
08308 #endif
08309 #endif
08310 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
08311 
08312     handshake->update_checksum = ssl_update_checksum_start;
08313 
08314 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
08315     defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
08316     mbedtls_ssl_sig_hash_set_init( &handshake->hash_algs );
08317 #endif
08318 
08319 #if defined(MBEDTLS_DHM_C)
08320     mbedtls_dhm_init( &handshake->dhm_ctx );
08321 #endif
08322 #if defined(MBEDTLS_ECDH_C)
08323     mbedtls_ecdh_init( &handshake->ecdh_ctx );
08324 #endif
08325 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
08326     mbedtls_ecjpake_init( &handshake->ecjpake_ctx );
08327 #if defined(MBEDTLS_SSL_CLI_C)
08328     handshake->ecjpake_cache = NULL;
08329     handshake->ecjpake_cache_len = 0;
08330 #endif
08331 #endif
08332 
08333 #if defined(MBEDTLS_SSL__ECP_RESTARTABLE)
08334     mbedtls_x509_crt_restart_init( &handshake->ecrs_ctx );
08335 #endif
08336 
08337 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
08338     handshake->sni_authmode = MBEDTLS_SSL_VERIFY_UNSET;
08339 #endif
08340 
08341 #if defined(MBEDTLS_X509_CRT_PARSE_C) && \
08342     !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
08343     mbedtls_pk_init( &handshake->peer_pubkey );
08344 #endif
08345 }
08346 
08347 void mbedtls_ssl_transform_init( mbedtls_ssl_transform *transform )
08348 {
08349     memset( transform, 0, sizeof(mbedtls_ssl_transform) );
08350 
08351     mbedtls_cipher_init( &transform->cipher_ctx_enc );
08352     mbedtls_cipher_init( &transform->cipher_ctx_dec );
08353 
08354 #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
08355     mbedtls_md_init( &transform->md_ctx_enc );
08356     mbedtls_md_init( &transform->md_ctx_dec );
08357 #endif
08358 }
08359 
08360 void mbedtls_ssl_session_init( mbedtls_ssl_session *session )
08361 {
08362     memset( session, 0, sizeof(mbedtls_ssl_session) );
08363 }
08364 
08365 static int ssl_handshake_init( mbedtls_ssl_context *ssl )
08366 {
08367     /* Clear old handshake information if present */
08368     if( ssl->transform_negotiate )
08369         mbedtls_ssl_transform_free( ssl->transform_negotiate );
08370     if( ssl->session_negotiate )
08371         mbedtls_ssl_session_free( ssl->session_negotiate );
08372     if( ssl->handshake )
08373         mbedtls_ssl_handshake_free( ssl );
08374 
08375     /*
08376      * Either the pointers are now NULL or cleared properly and can be freed.
08377      * Now allocate missing structures.
08378      */
08379     if( ssl->transform_negotiate == NULL )
08380     {
08381         ssl->transform_negotiate = mbedtls_calloc( 1, sizeof(mbedtls_ssl_transform) );
08382     }
08383 
08384     if( ssl->session_negotiate == NULL )
08385     {
08386         ssl->session_negotiate = mbedtls_calloc( 1, sizeof(mbedtls_ssl_session) );
08387     }
08388 
08389     if( ssl->handshake == NULL )
08390     {
08391         ssl->handshake = mbedtls_calloc( 1, sizeof(mbedtls_ssl_handshake_params) );
08392     }
08393 
08394     /* All pointers should exist and can be directly freed without issue */
08395     if( ssl->handshake == NULL ||
08396         ssl->transform_negotiate == NULL ||
08397         ssl->session_negotiate == NULL )
08398     {
08399         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc() of ssl sub-contexts failed" ) );
08400 
08401         mbedtls_free( ssl->handshake );
08402         mbedtls_free( ssl->transform_negotiate );
08403         mbedtls_free( ssl->session_negotiate );
08404 
08405         ssl->handshake = NULL;
08406         ssl->transform_negotiate = NULL;
08407         ssl->session_negotiate = NULL;
08408 
08409         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
08410     }
08411 
08412     /* Initialize structures */
08413     mbedtls_ssl_session_init( ssl->session_negotiate );
08414     mbedtls_ssl_transform_init( ssl->transform_negotiate );
08415     ssl_handshake_params_init( ssl->handshake );
08416 
08417 #if defined(MBEDTLS_SSL_PROTO_DTLS)
08418     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
08419     {
08420         ssl->handshake->alt_transform_out = ssl->transform_out;
08421 
08422         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
08423             ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_PREPARING;
08424         else
08425             ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
08426 
08427         ssl_set_timer( ssl, 0 );
08428     }
08429 #endif
08430 
08431     return( 0 );
08432 }
08433 
08434 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
08435 /* Dummy cookie callbacks for defaults */
08436 static int ssl_cookie_write_dummy( void *ctx,
08437                       unsigned char **p, unsigned char *end,
08438                       const unsigned char *cli_id, size_t cli_id_len )
08439 {
08440     ((void) ctx);
08441     ((void) p);
08442     ((void) end);
08443     ((void) cli_id);
08444     ((void) cli_id_len);
08445 
08446     return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
08447 }
08448 
08449 static int ssl_cookie_check_dummy( void *ctx,
08450                       const unsigned char *cookie, size_t cookie_len,
08451                       const unsigned char *cli_id, size_t cli_id_len )
08452 {
08453     ((void) ctx);
08454     ((void) cookie);
08455     ((void) cookie_len);
08456     ((void) cli_id);
08457     ((void) cli_id_len);
08458 
08459     return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
08460 }
08461 #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY && MBEDTLS_SSL_SRV_C */
08462 
08463 /* Once ssl->out_hdr as the address of the beginning of the
08464  * next outgoing record is set, deduce the other pointers.
08465  *
08466  * Note: For TLS, we save the implicit record sequence number
08467  *       (entering MAC computation) in the 8 bytes before ssl->out_hdr,
08468  *       and the caller has to make sure there's space for this.
08469  */
08470 
08471 static void ssl_update_out_pointers( mbedtls_ssl_context *ssl,
08472                                      mbedtls_ssl_transform *transform )
08473 {
08474 #if defined(MBEDTLS_SSL_PROTO_DTLS)
08475     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
08476     {
08477         ssl->out_ctr = ssl->out_hdr +  3;
08478 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
08479         ssl->out_cid = ssl->out_ctr +  8;
08480         ssl->out_len = ssl->out_cid;
08481         if( transform != NULL )
08482             ssl->out_len += transform->out_cid_len;
08483 #else /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
08484         ssl->out_len = ssl->out_ctr + 8;
08485 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
08486         ssl->out_iv  = ssl->out_len + 2;
08487     }
08488     else
08489 #endif
08490     {
08491         ssl->out_ctr = ssl->out_hdr - 8;
08492         ssl->out_len = ssl->out_hdr + 3;
08493 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
08494         ssl->out_cid = ssl->out_len;
08495 #endif
08496         ssl->out_iv  = ssl->out_hdr + 5;
08497     }
08498 
08499     /* Adjust out_msg to make space for explicit IV, if used. */
08500     if( transform != NULL &&
08501         ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
08502     {
08503         ssl->out_msg = ssl->out_iv + transform->ivlen - transform->fixed_ivlen;
08504     }
08505     else
08506         ssl->out_msg = ssl->out_iv;
08507 }
08508 
08509 /* Once ssl->in_hdr as the address of the beginning of the
08510  * next incoming record is set, deduce the other pointers.
08511  *
08512  * Note: For TLS, we save the implicit record sequence number
08513  *       (entering MAC computation) in the 8 bytes before ssl->in_hdr,
08514  *       and the caller has to make sure there's space for this.
08515  */
08516 
08517 static void ssl_update_in_pointers( mbedtls_ssl_context *ssl )
08518 {
08519     /* This function sets the pointers to match the case
08520      * of unprotected TLS/DTLS records, with both  ssl->in_iv
08521      * and ssl->in_msg pointing to the beginning of the record
08522      * content.
08523      *
08524      * When decrypting a protected record, ssl->in_msg
08525      * will be shifted to point to the beginning of the
08526      * record plaintext.
08527      */
08528 
08529 #if defined(MBEDTLS_SSL_PROTO_DTLS)
08530     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
08531     {
08532         /* This sets the header pointers to match records
08533          * without CID. When we receive a record containing
08534          * a CID, the fields are shifted accordingly in
08535          * ssl_parse_record_header(). */
08536         ssl->in_ctr = ssl->in_hdr +  3;
08537 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
08538         ssl->in_cid = ssl->in_ctr +  8;
08539         ssl->in_len = ssl->in_cid; /* Default: no CID */
08540 #else /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
08541         ssl->in_len = ssl->in_ctr + 8;
08542 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
08543         ssl->in_iv  = ssl->in_len + 2;
08544     }
08545     else
08546 #endif
08547     {
08548         ssl->in_ctr = ssl->in_hdr - 8;
08549         ssl->in_len = ssl->in_hdr + 3;
08550 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
08551         ssl->in_cid = ssl->in_len;
08552 #endif
08553         ssl->in_iv  = ssl->in_hdr + 5;
08554     }
08555 
08556     /* This will be adjusted at record decryption time. */
08557     ssl->in_msg = ssl->in_iv;
08558 }
08559 
08560 /*
08561  * Initialize an SSL context
08562  */
08563 void mbedtls_ssl_init( mbedtls_ssl_context *ssl )
08564 {
08565     memset( ssl, 0, sizeof( mbedtls_ssl_context ) );
08566 }
08567 
08568 /*
08569  * Setup an SSL context
08570  */
08571 
08572 static void ssl_reset_in_out_pointers( mbedtls_ssl_context *ssl )
08573 {
08574     /* Set the incoming and outgoing record pointers. */
08575 #if defined(MBEDTLS_SSL_PROTO_DTLS)
08576     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
08577     {
08578         ssl->out_hdr = ssl->out_buf;
08579         ssl->in_hdr  = ssl->in_buf;
08580     }
08581     else
08582 #endif /* MBEDTLS_SSL_PROTO_DTLS */
08583     {
08584         ssl->out_hdr = ssl->out_buf + 8;
08585         ssl->in_hdr  = ssl->in_buf  + 8;
08586     }
08587 
08588     /* Derive other internal pointers. */
08589     ssl_update_out_pointers( ssl, NULL /* no transform enabled */ );
08590     ssl_update_in_pointers ( ssl );
08591 }
08592 
08593 int mbedtls_ssl_setup( mbedtls_ssl_context *ssl,
08594                        const mbedtls_ssl_config *conf )
08595 {
08596     int ret;
08597 
08598     ssl->conf = conf;
08599 
08600     /*
08601      * Prepare base structures
08602      */
08603 
08604     /* Set to NULL in case of an error condition */
08605     ssl->out_buf = NULL;
08606 
08607     ssl->in_buf = mbedtls_calloc( 1, MBEDTLS_SSL_IN_BUFFER_LEN );
08608     if( ssl->in_buf == NULL )
08609     {
08610         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed", MBEDTLS_SSL_IN_BUFFER_LEN) );
08611         ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
08612         goto error;
08613     }
08614 
08615     ssl->out_buf = mbedtls_calloc( 1, MBEDTLS_SSL_OUT_BUFFER_LEN );
08616     if( ssl->out_buf == NULL )
08617     {
08618         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed", MBEDTLS_SSL_OUT_BUFFER_LEN) );
08619         ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
08620         goto error;
08621     }
08622 
08623     ssl_reset_in_out_pointers( ssl );
08624 
08625     if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
08626         goto error;
08627 
08628     return( 0 );
08629 
08630 error:
08631     mbedtls_free( ssl->in_buf );
08632     mbedtls_free( ssl->out_buf );
08633 
08634     ssl->conf = NULL;
08635 
08636     ssl->in_buf = NULL;
08637     ssl->out_buf = NULL;
08638 
08639     ssl->in_hdr = NULL;
08640     ssl->in_ctr = NULL;
08641     ssl->in_len = NULL;
08642     ssl->in_iv = NULL;
08643     ssl->in_msg = NULL;
08644 
08645     ssl->out_hdr = NULL;
08646     ssl->out_ctr = NULL;
08647     ssl->out_len = NULL;
08648     ssl->out_iv = NULL;
08649     ssl->out_msg = NULL;
08650 
08651     return( ret );
08652 }
08653 
08654 /*
08655  * Reset an initialized and used SSL context for re-use while retaining
08656  * all application-set variables, function pointers and data.
08657  *
08658  * If partial is non-zero, keep data in the input buffer and client ID.
08659  * (Use when a DTLS client reconnects from the same port.)
08660  */
08661 static int ssl_session_reset_int( mbedtls_ssl_context *ssl, int partial )
08662 {
08663     int ret;
08664 
08665 #if !defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) ||     \
08666     !defined(MBEDTLS_SSL_SRV_C)
08667     ((void) partial);
08668 #endif
08669 
08670     ssl->state = MBEDTLS_SSL_HELLO_REQUEST;
08671 
08672     /* Cancel any possibly running timer */
08673     ssl_set_timer( ssl, 0 );
08674 
08675 #if defined(MBEDTLS_SSL_RENEGOTIATION)
08676     ssl->renego_status = MBEDTLS_SSL_INITIAL_HANDSHAKE;
08677     ssl->renego_records_seen = 0;
08678 
08679     ssl->verify_data_len = 0;
08680     memset( ssl->own_verify_data, 0, MBEDTLS_SSL_VERIFY_DATA_MAX_LEN );
08681     memset( ssl->peer_verify_data, 0, MBEDTLS_SSL_VERIFY_DATA_MAX_LEN );
08682 #endif
08683     ssl->secure_renegotiation = MBEDTLS_SSL_LEGACY_RENEGOTIATION;
08684 
08685     ssl->in_offt = NULL;
08686     ssl_reset_in_out_pointers( ssl );
08687 
08688     ssl->in_msgtype = 0;
08689     ssl->in_msglen = 0;
08690 #if defined(MBEDTLS_SSL_PROTO_DTLS)
08691     ssl->next_record_offset = 0;
08692     ssl->in_epoch = 0;
08693 #endif
08694 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
08695     ssl_dtls_replay_reset( ssl );
08696 #endif
08697 
08698     ssl->in_hslen = 0;
08699     ssl->nb_zero = 0;
08700 
08701     ssl->keep_current_message = 0;
08702 
08703     ssl->out_msgtype = 0;
08704     ssl->out_msglen = 0;
08705     ssl->out_left = 0;
08706 #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
08707     if( ssl->split_done != MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED )
08708         ssl->split_done = 0;
08709 #endif
08710 
08711     memset( ssl->cur_out_ctr, 0, sizeof( ssl->cur_out_ctr ) );
08712 
08713     ssl->transform_in = NULL;
08714     ssl->transform_out = NULL;
08715 
08716     ssl->session_in = NULL;
08717     ssl->session_out = NULL;
08718 
08719     memset( ssl->out_buf, 0, MBEDTLS_SSL_OUT_BUFFER_LEN );
08720 
08721 #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
08722     if( partial == 0 )
08723 #endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */
08724     {
08725         ssl->in_left = 0;
08726         memset( ssl->in_buf, 0, MBEDTLS_SSL_IN_BUFFER_LEN );
08727     }
08728 
08729 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
08730     if( mbedtls_ssl_hw_record_reset != NULL )
08731     {
08732         MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_reset()" ) );
08733         if( ( ret = mbedtls_ssl_hw_record_reset( ssl ) ) != 0 )
08734         {
08735             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_reset", ret );
08736             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
08737         }
08738     }
08739 #endif
08740 
08741     if( ssl->transform )
08742     {
08743         mbedtls_ssl_transform_free( ssl->transform );
08744         mbedtls_free( ssl->transform );
08745         ssl->transform = NULL;
08746     }
08747 
08748     if( ssl->session )
08749     {
08750         mbedtls_ssl_session_free( ssl->session );
08751         mbedtls_free( ssl->session );
08752         ssl->session = NULL;
08753     }
08754 
08755 #if defined(MBEDTLS_SSL_ALPN)
08756     ssl->alpn_chosen = NULL;
08757 #endif
08758 
08759 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
08760 #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE)
08761     if( partial == 0 )
08762 #endif
08763     {
08764         mbedtls_free( ssl->cli_id );
08765         ssl->cli_id = NULL;
08766         ssl->cli_id_len = 0;
08767     }
08768 #endif
08769 
08770     if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
08771         return( ret );
08772 
08773     return( 0 );
08774 }
08775 
08776 /*
08777  * Reset an initialized and used SSL context for re-use while retaining
08778  * all application-set variables, function pointers and data.
08779  */
08780 int mbedtls_ssl_session_reset( mbedtls_ssl_context *ssl )
08781 {
08782     return( ssl_session_reset_int( ssl, 0 ) );
08783 }
08784 
08785 /*
08786  * SSL set accessors
08787  */
08788 void mbedtls_ssl_conf_endpoint( mbedtls_ssl_config *conf, int endpoint )
08789 {
08790     conf->endpoint    = endpoint;
08791 }
08792 
08793 void mbedtls_ssl_conf_transport( mbedtls_ssl_config *conf, int transport )
08794 {
08795     conf->transport  = transport;
08796 }
08797 
08798 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
08799 void mbedtls_ssl_conf_dtls_anti_replay( mbedtls_ssl_config *conf, char mode )
08800 {
08801     conf->anti_replay  = mode;
08802 }
08803 #endif
08804 
08805 #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT)
08806 void mbedtls_ssl_conf_dtls_badmac_limit( mbedtls_ssl_config *conf, unsigned limit )
08807 {
08808     conf->badmac_limit  = limit;
08809 }
08810 #endif
08811 
08812 #if defined(MBEDTLS_SSL_PROTO_DTLS)
08813 
08814 void mbedtls_ssl_set_datagram_packing( mbedtls_ssl_context *ssl,
08815                                        unsigned allow_packing )
08816 {
08817     ssl->disable_datagram_packing = !allow_packing;
08818 }
08819 
08820 void mbedtls_ssl_conf_handshake_timeout( mbedtls_ssl_config *conf,
08821                                          uint32_t min, uint32_t max )
08822 {
08823     conf->hs_timeout_min  = min;
08824     conf->hs_timeout_max  = max;
08825 }
08826 #endif
08827 
08828 void mbedtls_ssl_conf_authmode( mbedtls_ssl_config *conf, int authmode )
08829 {
08830     conf->authmode    = authmode;
08831 }
08832 
08833 #if defined(MBEDTLS_X509_CRT_PARSE_C)
08834 void mbedtls_ssl_conf_verify( mbedtls_ssl_config *conf,
08835                      int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
08836                      void *p_vrfy )
08837 {
08838     conf->f_vrfy      = f_vrfy;
08839     conf->p_vrfy       = p_vrfy;
08840 }
08841 #endif /* MBEDTLS_X509_CRT_PARSE_C */
08842 
08843 void mbedtls_ssl_conf_rng( mbedtls_ssl_config *conf,
08844                   int (*f_rng)(void *, unsigned char *, size_t),
08845                   void *p_rng )
08846 {
08847     conf->f_rng      = f_rng;
08848     conf->p_rng       = p_rng;
08849 }
08850 
08851 void mbedtls_ssl_conf_dbg( mbedtls_ssl_config *conf,
08852                   void (*f_dbg)(void *, int, const char *, int, const char *),
08853                   void  *p_dbg )
08854 {
08855     conf->f_dbg      = f_dbg;
08856     conf->p_dbg       = p_dbg;
08857 }
08858 
08859 void mbedtls_ssl_set_bio( mbedtls_ssl_context *ssl,
08860         void *p_bio,
08861         mbedtls_ssl_send_t *f_send,
08862         mbedtls_ssl_recv_t *f_recv,
08863         mbedtls_ssl_recv_timeout_t *f_recv_timeout )
08864 {
08865     ssl->p_bio          = p_bio;
08866     ssl->f_send         = f_send;
08867     ssl->f_recv         = f_recv;
08868     ssl->f_recv_timeout = f_recv_timeout;
08869 }
08870 
08871 #if defined(MBEDTLS_SSL_PROTO_DTLS)
08872 void mbedtls_ssl_set_mtu( mbedtls_ssl_context *ssl, uint16_t mtu )
08873 {
08874     ssl->mtu = mtu;
08875 }
08876 #endif
08877 
08878 void mbedtls_ssl_conf_read_timeout( mbedtls_ssl_config *conf, uint32_t timeout )
08879 {
08880     conf->read_timeout    = timeout;
08881 }
08882 
08883 void mbedtls_ssl_set_timer_cb( mbedtls_ssl_context *ssl,
08884                                void *p_timer,
08885                                mbedtls_ssl_set_timer_t *f_set_timer,
08886                                mbedtls_ssl_get_timer_t *f_get_timer )
08887 {
08888     ssl->p_timer        = p_timer;
08889     ssl->f_set_timer    = f_set_timer;
08890     ssl->f_get_timer    = f_get_timer;
08891 
08892     /* Make sure we start with no timer running */
08893     ssl_set_timer( ssl, 0 );
08894 }
08895 
08896 #if defined(MBEDTLS_SSL_SRV_C)
08897 void mbedtls_ssl_conf_session_cache( mbedtls_ssl_config *conf,
08898         void *p_cache,
08899         int (*f_get_cache)(void *, mbedtls_ssl_session *),
08900         int (*f_set_cache)(void *, const mbedtls_ssl_session *) )
08901 {
08902     conf->p_cache  = p_cache;
08903     conf->f_get_cache = f_get_cache;
08904     conf->f_set_cache = f_set_cache;
08905 }
08906 #endif /* MBEDTLS_SSL_SRV_C */
08907 
08908 #if defined(MBEDTLS_SSL_CLI_C)
08909 int mbedtls_ssl_set_session( mbedtls_ssl_context *ssl, const mbedtls_ssl_session *session )
08910 {
08911     int ret;
08912 
08913     if( ssl == NULL ||
08914         session == NULL ||
08915         ssl->session_negotiate == NULL ||
08916         ssl->conf->endpoint != MBEDTLS_SSL_IS_CLIENT )
08917     {
08918         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
08919     }
08920 
08921     if( ( ret = mbedtls_ssl_session_copy( ssl->session_negotiate,
08922                                           session ) ) != 0 )
08923         return( ret );
08924 
08925     ssl->handshake->resume = 1;
08926 
08927     return( 0 );
08928 }
08929 #endif /* MBEDTLS_SSL_CLI_C */
08930 
08931 void mbedtls_ssl_conf_ciphersuites( mbedtls_ssl_config *conf,
08932                                    const int *ciphersuites )
08933 {
08934     conf->ciphersuite_list [MBEDTLS_SSL_MINOR_VERSION_0] = ciphersuites;
08935     conf->ciphersuite_list [MBEDTLS_SSL_MINOR_VERSION_1] = ciphersuites;
08936     conf->ciphersuite_list [MBEDTLS_SSL_MINOR_VERSION_2] = ciphersuites;
08937     conf->ciphersuite_list [MBEDTLS_SSL_MINOR_VERSION_3] = ciphersuites;
08938 }
08939 
08940 void mbedtls_ssl_conf_ciphersuites_for_version( mbedtls_ssl_config *conf,
08941                                        const int *ciphersuites,
08942                                        int major, int minor )
08943 {
08944     if( major != MBEDTLS_SSL_MAJOR_VERSION_3 )
08945         return;
08946 
08947     if( minor < MBEDTLS_SSL_MINOR_VERSION_0 || minor > MBEDTLS_SSL_MINOR_VERSION_3 )
08948         return;
08949 
08950     conf->ciphersuite_list [minor] = ciphersuites;
08951 }
08952 
08953 #if defined(MBEDTLS_X509_CRT_PARSE_C)
08954 void mbedtls_ssl_conf_cert_profile( mbedtls_ssl_config *conf,
08955                                     const mbedtls_x509_crt_profile *profile )
08956 {
08957     conf->cert_profile  = profile;
08958 }
08959 
08960 /* Append a new keycert entry to a (possibly empty) list */
08961 static int ssl_append_key_cert( mbedtls_ssl_key_cert **head,
08962                                 mbedtls_x509_crt *cert,
08963                                 mbedtls_pk_context *key )
08964 {
08965     mbedtls_ssl_key_cert *new_cert;
08966 
08967     new_cert = mbedtls_calloc( 1, sizeof( mbedtls_ssl_key_cert ) );
08968     if( new_cert == NULL )
08969         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
08970 
08971     new_cert->cert = cert;
08972     new_cert->key  = key;
08973     new_cert->next = NULL;
08974 
08975     /* Update head is the list was null, else add to the end */
08976     if( *head == NULL )
08977     {
08978         *head = new_cert;
08979     }
08980     else
08981     {
08982         mbedtls_ssl_key_cert *cur = *head;
08983         while( cur->next != NULL )
08984             cur = cur->next;
08985         cur->next = new_cert;
08986     }
08987 
08988     return( 0 );
08989 }
08990 
08991 int mbedtls_ssl_conf_own_cert( mbedtls_ssl_config *conf,
08992                               mbedtls_x509_crt *own_cert,
08993                               mbedtls_pk_context *pk_key )
08994 {
08995     return( ssl_append_key_cert( &conf->key_cert , own_cert, pk_key ) );
08996 }
08997 
08998 void mbedtls_ssl_conf_ca_chain( mbedtls_ssl_config *conf,
08999                                mbedtls_x509_crt *ca_chain,
09000                                mbedtls_x509_crl *ca_crl )
09001 {
09002     conf->ca_chain    = ca_chain;
09003     conf->ca_crl      = ca_crl;
09004 
09005 #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK)
09006     /* mbedtls_ssl_conf_ca_chain() and mbedtls_ssl_conf_ca_cb()
09007      * cannot be used together. */
09008     conf->f_ca_cb = NULL;
09009     conf->p_ca_cb = NULL;
09010 #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */
09011 }
09012 
09013 #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK)
09014 void mbedtls_ssl_conf_ca_cb( mbedtls_ssl_config *conf,
09015                              mbedtls_x509_crt_ca_cb_t f_ca_cb,
09016                              void *p_ca_cb )
09017 {
09018     conf->f_ca_cb = f_ca_cb;
09019     conf->p_ca_cb = p_ca_cb;
09020 
09021     /* mbedtls_ssl_conf_ca_chain() and mbedtls_ssl_conf_ca_cb()
09022      * cannot be used together. */
09023     conf->ca_chain    = NULL;
09024     conf->ca_crl      = NULL;
09025 }
09026 #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */
09027 #endif /* MBEDTLS_X509_CRT_PARSE_C */
09028 
09029 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
09030 int mbedtls_ssl_set_hs_own_cert( mbedtls_ssl_context *ssl,
09031                                  mbedtls_x509_crt *own_cert,
09032                                  mbedtls_pk_context *pk_key )
09033 {
09034     return( ssl_append_key_cert( &ssl->handshake->sni_key_cert,
09035                                  own_cert, pk_key ) );
09036 }
09037 
09038 void mbedtls_ssl_set_hs_ca_chain( mbedtls_ssl_context *ssl,
09039                                   mbedtls_x509_crt *ca_chain,
09040                                   mbedtls_x509_crl *ca_crl )
09041 {
09042     ssl->handshake->sni_ca_chain   = ca_chain;
09043     ssl->handshake->sni_ca_crl     = ca_crl;
09044 }
09045 
09046 void mbedtls_ssl_set_hs_authmode( mbedtls_ssl_context *ssl,
09047                                   int authmode )
09048 {
09049     ssl->handshake->sni_authmode = authmode;
09050 }
09051 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
09052 
09053 #if defined(MBEDTLS_X509_CRT_PARSE_C)
09054 void mbedtls_ssl_set_verify( mbedtls_ssl_context *ssl,
09055                      int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
09056                      void *p_vrfy )
09057 {
09058     ssl->f_vrfy = f_vrfy;
09059     ssl->p_vrfy = p_vrfy;
09060 }
09061 #endif
09062 
09063 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
09064 /*
09065  * Set EC J-PAKE password for current handshake
09066  */
09067 int mbedtls_ssl_set_hs_ecjpake_password( mbedtls_ssl_context *ssl,
09068                                          const unsigned char *pw,
09069                                          size_t pw_len )
09070 {
09071     mbedtls_ecjpake_role role;
09072 
09073     if( ssl->handshake == NULL || ssl->conf == NULL )
09074         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
09075 
09076     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
09077         role = MBEDTLS_ECJPAKE_SERVER;
09078     else
09079         role = MBEDTLS_ECJPAKE_CLIENT;
09080 
09081     return( mbedtls_ecjpake_setup( &ssl->handshake->ecjpake_ctx,
09082                                    role,
09083                                    MBEDTLS_MD_SHA256,
09084                                    MBEDTLS_ECP_DP_SECP256R1,
09085                                    pw, pw_len ) );
09086 }
09087 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
09088 
09089 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
09090 
09091 static void ssl_conf_remove_psk( mbedtls_ssl_config *conf )
09092 {
09093     /* Remove reference to existing PSK, if any. */
09094 #if defined(MBEDTLS_USE_PSA_CRYPTO)
09095     if( conf->psk_opaque  != 0 )
09096     {
09097         /* The maintenance of the PSK key slot is the
09098          * user's responsibility. */
09099         conf->psk_opaque  = 0;
09100     }
09101     /* This and the following branch should never
09102      * be taken simultaenously as we maintain the
09103      * invariant that raw and opaque PSKs are never
09104      * configured simultaneously. As a safeguard,
09105      * though, `else` is omitted here. */
09106 #endif /* MBEDTLS_USE_PSA_CRYPTO */
09107     if( conf->psk  != NULL )
09108     {
09109         mbedtls_platform_zeroize( conf->psk , conf->psk_len  );
09110 
09111         mbedtls_free( conf->psk  );
09112         conf->psk  = NULL;
09113         conf->psk_len  = 0;
09114     }
09115 
09116     /* Remove reference to PSK identity, if any. */
09117     if( conf->psk_identity  != NULL )
09118     {
09119         mbedtls_free( conf->psk_identity  );
09120         conf->psk_identity  = NULL;
09121         conf->psk_identity_len  = 0;
09122     }
09123 }
09124 
09125 /* This function assumes that PSK identity in the SSL config is unset.
09126  * It checks that the provided identity is well-formed and attempts
09127  * to make a copy of it in the SSL config.
09128  * On failure, the PSK identity in the config remains unset. */
09129 static int ssl_conf_set_psk_identity( mbedtls_ssl_config *conf,
09130                                       unsigned char const *psk_identity,
09131                                       size_t psk_identity_len )
09132 {
09133     /* Identity len will be encoded on two bytes */
09134     if( psk_identity               == NULL ||
09135         ( psk_identity_len >> 16 ) != 0    ||
09136         psk_identity_len > MBEDTLS_SSL_OUT_CONTENT_LEN )
09137     {
09138         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
09139     }
09140 
09141     conf->psk_identity  = mbedtls_calloc( 1, psk_identity_len );
09142     if( conf->psk_identity  == NULL )
09143         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
09144 
09145     conf->psk_identity_len  = psk_identity_len;
09146     memcpy( conf->psk_identity , psk_identity, conf->psk_identity_len  );
09147 
09148     return( 0 );
09149 }
09150 
09151 int mbedtls_ssl_conf_psk( mbedtls_ssl_config *conf,
09152                 const unsigned char *psk, size_t psk_len,
09153                 const unsigned char *psk_identity, size_t psk_identity_len )
09154 {
09155     int ret;
09156     /* Remove opaque/raw PSK + PSK Identity */
09157     ssl_conf_remove_psk( conf );
09158 
09159     /* Check and set raw PSK */
09160     if( psk == NULL || psk_len > MBEDTLS_PSK_MAX_LEN )
09161         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
09162     if( ( conf->psk  = mbedtls_calloc( 1, psk_len ) ) == NULL )
09163         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
09164     conf->psk_len  = psk_len;
09165     memcpy( conf->psk , psk, conf->psk_len  );
09166 
09167     /* Check and set PSK Identity */
09168     ret = ssl_conf_set_psk_identity( conf, psk_identity, psk_identity_len );
09169     if( ret != 0 )
09170         ssl_conf_remove_psk( conf );
09171 
09172     return( ret );
09173 }
09174 
09175 static void ssl_remove_psk( mbedtls_ssl_context *ssl )
09176 {
09177 #if defined(MBEDTLS_USE_PSA_CRYPTO)
09178     if( ssl->handshake->psk_opaque != 0 )
09179     {
09180         ssl->handshake->psk_opaque = 0;
09181     }
09182     else
09183 #endif /* MBEDTLS_USE_PSA_CRYPTO */
09184     if( ssl->handshake->psk != NULL )
09185     {
09186         mbedtls_platform_zeroize( ssl->handshake->psk,
09187                                   ssl->handshake->psk_len );
09188         mbedtls_free( ssl->handshake->psk );
09189         ssl->handshake->psk_len = 0;
09190     }
09191 }
09192 
09193 int mbedtls_ssl_set_hs_psk( mbedtls_ssl_context *ssl,
09194                             const unsigned char *psk, size_t psk_len )
09195 {
09196     if( psk == NULL || ssl->handshake == NULL )
09197         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
09198 
09199     if( psk_len > MBEDTLS_PSK_MAX_LEN )
09200         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
09201 
09202     ssl_remove_psk( ssl );
09203 
09204     if( ( ssl->handshake->psk = mbedtls_calloc( 1, psk_len ) ) == NULL )
09205         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
09206 
09207     ssl->handshake->psk_len = psk_len;
09208     memcpy( ssl->handshake->psk, psk, ssl->handshake->psk_len );
09209 
09210     return( 0 );
09211 }
09212 
09213 #if defined(MBEDTLS_USE_PSA_CRYPTO)
09214 int mbedtls_ssl_conf_psk_opaque( mbedtls_ssl_config *conf,
09215                                  psa_key_handle_t psk_slot,
09216                                  const unsigned char *psk_identity,
09217                                  size_t psk_identity_len )
09218 {
09219     int ret;
09220     /* Clear opaque/raw PSK + PSK Identity, if present. */
09221     ssl_conf_remove_psk( conf );
09222 
09223     /* Check and set opaque PSK */
09224     if( psk_slot == 0 )
09225         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
09226     conf->psk_opaque  = psk_slot;
09227 
09228     /* Check and set PSK Identity */
09229     ret = ssl_conf_set_psk_identity( conf, psk_identity,
09230                                      psk_identity_len );
09231     if( ret != 0 )
09232         ssl_conf_remove_psk( conf );
09233 
09234     return( ret );
09235 }
09236 
09237 int mbedtls_ssl_set_hs_psk_opaque( mbedtls_ssl_context *ssl,
09238                                    psa_key_handle_t psk_slot )
09239 {
09240     if( psk_slot == 0 || ssl->handshake == NULL )
09241         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
09242 
09243     ssl_remove_psk( ssl );
09244     ssl->handshake->psk_opaque = psk_slot;
09245     return( 0 );
09246 }
09247 #endif /* MBEDTLS_USE_PSA_CRYPTO */
09248 
09249 void mbedtls_ssl_conf_psk_cb( mbedtls_ssl_config *conf,
09250                      int (*f_psk)(void *, mbedtls_ssl_context *, const unsigned char *,
09251                      size_t),
09252                      void *p_psk )
09253 {
09254     conf->f_psk = f_psk;
09255     conf->p_psk  = p_psk;
09256 }
09257 #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
09258 
09259 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
09260 
09261 #if !defined(MBEDTLS_DEPRECATED_REMOVED)
09262 int mbedtls_ssl_conf_dh_param( mbedtls_ssl_config *conf, const char *dhm_P, const char *dhm_G )
09263 {
09264     int ret;
09265 
09266     if( ( ret = mbedtls_mpi_read_string( &conf->dhm_P , 16, dhm_P ) ) != 0 ||
09267         ( ret = mbedtls_mpi_read_string( &conf->dhm_G , 16, dhm_G ) ) != 0 )
09268     {
09269         mbedtls_mpi_free( &conf->dhm_P  );
09270         mbedtls_mpi_free( &conf->dhm_G  );
09271         return( ret );
09272     }
09273 
09274     return( 0 );
09275 }
09276 #endif /* MBEDTLS_DEPRECATED_REMOVED */
09277 
09278 int mbedtls_ssl_conf_dh_param_bin( mbedtls_ssl_config *conf,
09279                                    const unsigned char *dhm_P, size_t P_len,
09280                                    const unsigned char *dhm_G, size_t G_len )
09281 {
09282     int ret;
09283 
09284     if( ( ret = mbedtls_mpi_read_binary( &conf->dhm_P , dhm_P, P_len ) ) != 0 ||
09285         ( ret = mbedtls_mpi_read_binary( &conf->dhm_G , dhm_G, G_len ) ) != 0 )
09286     {
09287         mbedtls_mpi_free( &conf->dhm_P  );
09288         mbedtls_mpi_free( &conf->dhm_G  );
09289         return( ret );
09290     }
09291 
09292     return( 0 );
09293 }
09294 
09295 int mbedtls_ssl_conf_dh_param_ctx( mbedtls_ssl_config *conf, mbedtls_dhm_context *dhm_ctx )
09296 {
09297     int ret;
09298 
09299     if( ( ret = mbedtls_mpi_copy( &conf->dhm_P , &dhm_ctx->P  ) ) != 0 ||
09300         ( ret = mbedtls_mpi_copy( &conf->dhm_G , &dhm_ctx->G  ) ) != 0 )
09301     {
09302         mbedtls_mpi_free( &conf->dhm_P  );
09303         mbedtls_mpi_free( &conf->dhm_G  );
09304         return( ret );
09305     }
09306 
09307     return( 0 );
09308 }
09309 #endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_SRV_C */
09310 
09311 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C)
09312 /*
09313  * Set the minimum length for Diffie-Hellman parameters
09314  */
09315 void mbedtls_ssl_conf_dhm_min_bitlen( mbedtls_ssl_config *conf,
09316                                       unsigned int bitlen )
09317 {
09318     conf->dhm_min_bitlen  = bitlen;
09319 }
09320 #endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_CLI_C */
09321 
09322 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
09323 /*
09324  * Set allowed/preferred hashes for handshake signatures
09325  */
09326 void mbedtls_ssl_conf_sig_hashes( mbedtls_ssl_config *conf,
09327                                   const int *hashes )
09328 {
09329     conf->sig_hashes  = hashes;
09330 }
09331 #endif /* MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
09332 
09333 #if defined(MBEDTLS_ECP_C)
09334 /*
09335  * Set the allowed elliptic curves
09336  */
09337 void mbedtls_ssl_conf_curves( mbedtls_ssl_config *conf,
09338                              const mbedtls_ecp_group_id *curve_list )
09339 {
09340     conf->curve_list  = curve_list;
09341 }
09342 #endif /* MBEDTLS_ECP_C */
09343 
09344 #if defined(MBEDTLS_X509_CRT_PARSE_C)
09345 int mbedtls_ssl_set_hostname( mbedtls_ssl_context *ssl, const char *hostname )
09346 {
09347     /* Initialize to suppress unnecessary compiler warning */
09348     size_t hostname_len = 0;
09349 
09350     /* Check if new hostname is valid before
09351      * making any change to current one */
09352     if( hostname != NULL )
09353     {
09354         hostname_len = strlen( hostname );
09355 
09356         if( hostname_len > MBEDTLS_SSL_MAX_HOST_NAME_LEN )
09357             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
09358     }
09359 
09360     /* Now it's clear that we will overwrite the old hostname,
09361      * so we can free it safely */
09362 
09363     if( ssl->hostname != NULL )
09364     {
09365         mbedtls_platform_zeroize( ssl->hostname, strlen( ssl->hostname ) );
09366         mbedtls_free( ssl->hostname );
09367     }
09368 
09369     /* Passing NULL as hostname shall clear the old one */
09370 
09371     if( hostname == NULL )
09372     {
09373         ssl->hostname = NULL;
09374     }
09375     else
09376     {
09377         ssl->hostname = mbedtls_calloc( 1, hostname_len + 1 );
09378         if( ssl->hostname == NULL )
09379             return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
09380 
09381         memcpy( ssl->hostname, hostname, hostname_len );
09382 
09383         ssl->hostname[hostname_len] = '\0';
09384     }
09385 
09386     return( 0 );
09387 }
09388 #endif /* MBEDTLS_X509_CRT_PARSE_C */
09389 
09390 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
09391 void mbedtls_ssl_conf_sni( mbedtls_ssl_config *conf,
09392                   int (*f_sni)(void *, mbedtls_ssl_context *,
09393                                 const unsigned char *, size_t),
09394                   void *p_sni )
09395 {
09396     conf->f_sni = f_sni;
09397     conf->p_sni  = p_sni;
09398 }
09399 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
09400 
09401 #if defined(MBEDTLS_SSL_ALPN)
09402 int mbedtls_ssl_conf_alpn_protocols( mbedtls_ssl_config *conf, const char **protos )
09403 {
09404     size_t cur_len, tot_len;
09405     const char **p;
09406 
09407     /*
09408      * RFC 7301 3.1: "Empty strings MUST NOT be included and byte strings
09409      * MUST NOT be truncated."
09410      * We check lengths now rather than later.
09411      */
09412     tot_len = 0;
09413     for( p = protos; *p != NULL; p++ )
09414     {
09415         cur_len = strlen( *p );
09416         tot_len += cur_len;
09417 
09418         if( cur_len == 0 || cur_len > 255 || tot_len > 65535 )
09419             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
09420     }
09421 
09422     conf->alpn_list  = protos;
09423 
09424     return( 0 );
09425 }
09426 
09427 const char *mbedtls_ssl_get_alpn_protocol( const mbedtls_ssl_context *ssl )
09428 {
09429     return( ssl->alpn_chosen );
09430 }
09431 #endif /* MBEDTLS_SSL_ALPN */
09432 
09433 void mbedtls_ssl_conf_max_version( mbedtls_ssl_config *conf, int major, int minor )
09434 {
09435     conf->max_major_ver  = major;
09436     conf->max_minor_ver  = minor;
09437 }
09438 
09439 void mbedtls_ssl_conf_min_version( mbedtls_ssl_config *conf, int major, int minor )
09440 {
09441     conf->min_major_ver  = major;
09442     conf->min_minor_ver  = minor;
09443 }
09444 
09445 #if defined(MBEDTLS_SSL_FALLBACK_SCSV) && defined(MBEDTLS_SSL_CLI_C)
09446 void mbedtls_ssl_conf_fallback( mbedtls_ssl_config *conf, char fallback )
09447 {
09448     conf->fallback  = fallback;
09449 }
09450 #endif
09451 
09452 #if defined(MBEDTLS_SSL_SRV_C)
09453 void mbedtls_ssl_conf_cert_req_ca_list( mbedtls_ssl_config *conf,
09454                                           char cert_req_ca_list )
09455 {
09456     conf->cert_req_ca_list  = cert_req_ca_list;
09457 }
09458 #endif
09459 
09460 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
09461 void mbedtls_ssl_conf_encrypt_then_mac( mbedtls_ssl_config *conf, char etm )
09462 {
09463     conf->encrypt_then_mac  = etm;
09464 }
09465 #endif
09466 
09467 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
09468 void mbedtls_ssl_conf_extended_master_secret( mbedtls_ssl_config *conf, char ems )
09469 {
09470     conf->extended_ms  = ems;
09471 }
09472 #endif
09473 
09474 #if defined(MBEDTLS_ARC4_C)
09475 void mbedtls_ssl_conf_arc4_support( mbedtls_ssl_config *conf, char arc4 )
09476 {
09477     conf->arc4_disabled  = arc4;
09478 }
09479 #endif
09480 
09481 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
09482 int mbedtls_ssl_conf_max_frag_len( mbedtls_ssl_config *conf, unsigned char mfl_code )
09483 {
09484     if( mfl_code >= MBEDTLS_SSL_MAX_FRAG_LEN_INVALID ||
09485         ssl_mfl_code_to_length( mfl_code ) > MBEDTLS_TLS_EXT_ADV_CONTENT_LEN )
09486     {
09487         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
09488     }
09489 
09490     conf->mfl_code  = mfl_code;
09491 
09492     return( 0 );
09493 }
09494 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
09495 
09496 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
09497 void mbedtls_ssl_conf_truncated_hmac( mbedtls_ssl_config *conf, int truncate )
09498 {
09499     conf->trunc_hmac  = truncate;
09500 }
09501 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
09502 
09503 #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
09504 void mbedtls_ssl_conf_cbc_record_splitting( mbedtls_ssl_config *conf, char split )
09505 {
09506     conf->cbc_record_splitting  = split;
09507 }
09508 #endif
09509 
09510 void mbedtls_ssl_conf_legacy_renegotiation( mbedtls_ssl_config *conf, int allow_legacy )
09511 {
09512     conf->allow_legacy_renegotiation  = allow_legacy;
09513 }
09514 
09515 #if defined(MBEDTLS_SSL_RENEGOTIATION)
09516 void mbedtls_ssl_conf_renegotiation( mbedtls_ssl_config *conf, int renegotiation )
09517 {
09518     conf->disable_renegotiation  = renegotiation;
09519 }
09520 
09521 void mbedtls_ssl_conf_renegotiation_enforced( mbedtls_ssl_config *conf, int max_records )
09522 {
09523     conf->renego_max_records  = max_records;
09524 }
09525 
09526 void mbedtls_ssl_conf_renegotiation_period( mbedtls_ssl_config *conf,
09527                                    const unsigned char period[8] )
09528 {
09529     memcpy( conf->renego_period , period, 8 );
09530 }
09531 #endif /* MBEDTLS_SSL_RENEGOTIATION */
09532 
09533 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
09534 #if defined(MBEDTLS_SSL_CLI_C)
09535 void mbedtls_ssl_conf_session_tickets( mbedtls_ssl_config *conf, int use_tickets )
09536 {
09537     conf->session_tickets  = use_tickets;
09538 }
09539 #endif
09540 
09541 #if defined(MBEDTLS_SSL_SRV_C)
09542 void mbedtls_ssl_conf_session_tickets_cb( mbedtls_ssl_config *conf,
09543         mbedtls_ssl_ticket_write_t *f_ticket_write,
09544         mbedtls_ssl_ticket_parse_t *f_ticket_parse,
09545         void *p_ticket )
09546 {
09547     conf->f_ticket_write = f_ticket_write;
09548     conf->f_ticket_parse = f_ticket_parse;
09549     conf->p_ticket        = p_ticket;
09550 }
09551 #endif
09552 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
09553 
09554 #if defined(MBEDTLS_SSL_EXPORT_KEYS)
09555 void mbedtls_ssl_conf_export_keys_cb( mbedtls_ssl_config *conf,
09556         mbedtls_ssl_export_keys_t *f_export_keys,
09557         void *p_export_keys )
09558 {
09559     conf->f_export_keys = f_export_keys;
09560     conf->p_export_keys  = p_export_keys;
09561 }
09562 
09563 void mbedtls_ssl_conf_export_keys_ext_cb( mbedtls_ssl_config *conf,
09564         mbedtls_ssl_export_keys_ext_t *f_export_keys_ext,
09565         void *p_export_keys )
09566 {
09567     conf->f_export_keys_ext = f_export_keys_ext;
09568     conf->p_export_keys  = p_export_keys;
09569 }
09570 #endif
09571 
09572 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
09573 void mbedtls_ssl_conf_async_private_cb(
09574     mbedtls_ssl_config *conf,
09575     mbedtls_ssl_async_sign_t *f_async_sign,
09576     mbedtls_ssl_async_decrypt_t *f_async_decrypt,
09577     mbedtls_ssl_async_resume_t *f_async_resume,
09578     mbedtls_ssl_async_cancel_t *f_async_cancel,
09579     void *async_config_data )
09580 {
09581     conf->f_async_sign_start  = f_async_sign;
09582     conf->f_async_decrypt_start  = f_async_decrypt;
09583     conf->f_async_resume  = f_async_resume;
09584     conf->f_async_cancel  = f_async_cancel;
09585     conf->p_async_config_data  = async_config_data;
09586 }
09587 
09588 void *mbedtls_ssl_conf_get_async_config_data( const mbedtls_ssl_config *conf )
09589 {
09590     return( conf->p_async_config_data  );
09591 }
09592 
09593 void *mbedtls_ssl_get_async_operation_data( const mbedtls_ssl_context *ssl )
09594 {
09595     if( ssl->handshake == NULL )
09596         return( NULL );
09597     else
09598         return( ssl->handshake->user_async_ctx );
09599 }
09600 
09601 void mbedtls_ssl_set_async_operation_data( mbedtls_ssl_context *ssl,
09602                                  void *ctx )
09603 {
09604     if( ssl->handshake != NULL )
09605         ssl->handshake->user_async_ctx = ctx;
09606 }
09607 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
09608 
09609 /*
09610  * SSL get accessors
09611  */
09612 size_t mbedtls_ssl_get_bytes_avail( const mbedtls_ssl_context *ssl )
09613 {
09614     return( ssl->in_offt == NULL ? 0 : ssl->in_msglen );
09615 }
09616 
09617 int mbedtls_ssl_check_pending( const mbedtls_ssl_context *ssl )
09618 {
09619     /*
09620      * Case A: We're currently holding back
09621      * a message for further processing.
09622      */
09623 
09624     if( ssl->keep_current_message == 1 )
09625     {
09626         MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: record held back for processing" ) );
09627         return( 1 );
09628     }
09629 
09630     /*
09631      * Case B: Further records are pending in the current datagram.
09632      */
09633 
09634 #if defined(MBEDTLS_SSL_PROTO_DTLS)
09635     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
09636         ssl->in_left > ssl->next_record_offset )
09637     {
09638         MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: more records within current datagram" ) );
09639         return( 1 );
09640     }
09641 #endif /* MBEDTLS_SSL_PROTO_DTLS */
09642 
09643     /*
09644      * Case C: A handshake message is being processed.
09645      */
09646 
09647     if( ssl->in_hslen > 0 && ssl->in_hslen < ssl->in_msglen )
09648     {
09649         MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: more handshake messages within current record" ) );
09650         return( 1 );
09651     }
09652 
09653     /*
09654      * Case D: An application data message is being processed
09655      */
09656     if( ssl->in_offt != NULL )
09657     {
09658         MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: application data record is being processed" ) );
09659         return( 1 );
09660     }
09661 
09662     /*
09663      * In all other cases, the rest of the message can be dropped.
09664      * As in ssl_get_next_record, this needs to be adapted if
09665      * we implement support for multiple alerts in single records.
09666      */
09667 
09668     MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_check_pending: nothing pending" ) );
09669     return( 0 );
09670 }
09671 
09672 uint32_t mbedtls_ssl_get_verify_result( const mbedtls_ssl_context *ssl )
09673 {
09674     if( ssl->session != NULL )
09675         return( ssl->session->verify_result );
09676 
09677     if( ssl->session_negotiate != NULL )
09678         return( ssl->session_negotiate->verify_result );
09679 
09680     return( 0xFFFFFFFF );
09681 }
09682 
09683 const char *mbedtls_ssl_get_ciphersuite( const mbedtls_ssl_context *ssl )
09684 {
09685     if( ssl == NULL || ssl->session == NULL )
09686         return( NULL );
09687 
09688     return mbedtls_ssl_get_ciphersuite_name( ssl->session->ciphersuite );
09689 }
09690 
09691 const char *mbedtls_ssl_get_version( const mbedtls_ssl_context *ssl )
09692 {
09693 #if defined(MBEDTLS_SSL_PROTO_DTLS)
09694     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
09695     {
09696         switch( ssl->minor_ver )
09697         {
09698             case MBEDTLS_SSL_MINOR_VERSION_2:
09699                 return( "DTLSv1.0" );
09700 
09701             case MBEDTLS_SSL_MINOR_VERSION_3:
09702                 return( "DTLSv1.2" );
09703 
09704             default:
09705                 return( "unknown (DTLS)" );
09706         }
09707     }
09708 #endif
09709 
09710     switch( ssl->minor_ver )
09711     {
09712         case MBEDTLS_SSL_MINOR_VERSION_0:
09713             return( "SSLv3.0" );
09714 
09715         case MBEDTLS_SSL_MINOR_VERSION_1:
09716             return( "TLSv1.0" );
09717 
09718         case MBEDTLS_SSL_MINOR_VERSION_2:
09719             return( "TLSv1.1" );
09720 
09721         case MBEDTLS_SSL_MINOR_VERSION_3:
09722             return( "TLSv1.2" );
09723 
09724         default:
09725             return( "unknown" );
09726     }
09727 }
09728 
09729 int mbedtls_ssl_get_record_expansion( const mbedtls_ssl_context *ssl )
09730 {
09731     size_t transform_expansion = 0;
09732     const mbedtls_ssl_transform *transform = ssl->transform_out;
09733     unsigned block_size;
09734 
09735     size_t out_hdr_len = mbedtls_ssl_out_hdr_len( ssl );
09736 
09737     if( transform == NULL )
09738         return( (int) out_hdr_len );
09739 
09740 #if defined(MBEDTLS_ZLIB_SUPPORT)
09741     if( ssl->session_out->compression != MBEDTLS_SSL_COMPRESS_NULL )
09742         return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
09743 #endif
09744 
09745     switch( mbedtls_cipher_get_cipher_mode( &transform->cipher_ctx_enc ) )
09746     {
09747         case MBEDTLS_MODE_GCM:
09748         case MBEDTLS_MODE_CCM:
09749         case MBEDTLS_MODE_CHACHAPOLY:
09750         case MBEDTLS_MODE_STREAM:
09751             transform_expansion = transform->minlen;
09752             break;
09753 
09754         case MBEDTLS_MODE_CBC:
09755 
09756             block_size = mbedtls_cipher_get_block_size(
09757                 &transform->cipher_ctx_enc );
09758 
09759             /* Expansion due to the addition of the MAC. */
09760             transform_expansion += transform->maclen;
09761 
09762             /* Expansion due to the addition of CBC padding;
09763              * Theoretically up to 256 bytes, but we never use
09764              * more than the block size of the underlying cipher. */
09765             transform_expansion += block_size;
09766 
09767             /* For TLS 1.1 or higher, an explicit IV is added
09768              * after the record header. */
09769 #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
09770             if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
09771                 transform_expansion += block_size;
09772 #endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */
09773 
09774             break;
09775 
09776         default:
09777             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
09778             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
09779     }
09780 
09781 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
09782     if( transform->out_cid_len != 0 )
09783         transform_expansion += MBEDTLS_SSL_MAX_CID_EXPANSION;
09784 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
09785 
09786     return( (int)( out_hdr_len + transform_expansion ) );
09787 }
09788 
09789 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
09790 size_t mbedtls_ssl_get_max_frag_len( const mbedtls_ssl_context *ssl )
09791 {
09792     size_t max_len;
09793 
09794     /*
09795      * Assume mfl_code is correct since it was checked when set
09796      */
09797     max_len = ssl_mfl_code_to_length( ssl->conf->mfl_code );
09798 
09799     /* Check if a smaller max length was negotiated */
09800     if( ssl->session_out != NULL &&
09801         ssl_mfl_code_to_length( ssl->session_out->mfl_code ) < max_len )
09802     {
09803         max_len = ssl_mfl_code_to_length( ssl->session_out->mfl_code );
09804     }
09805 
09806     /* During a handshake, use the value being negotiated */
09807     if( ssl->session_negotiate != NULL &&
09808         ssl_mfl_code_to_length( ssl->session_negotiate->mfl_code ) < max_len )
09809     {
09810         max_len = ssl_mfl_code_to_length( ssl->session_negotiate->mfl_code );
09811     }
09812 
09813     return( max_len );
09814 }
09815 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
09816 
09817 #if defined(MBEDTLS_SSL_PROTO_DTLS)
09818 static size_t ssl_get_current_mtu( const mbedtls_ssl_context *ssl )
09819 {
09820     /* Return unlimited mtu for client hello messages to avoid fragmentation. */
09821     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&
09822         ( ssl->state == MBEDTLS_SSL_CLIENT_HELLO ||
09823           ssl->state == MBEDTLS_SSL_SERVER_HELLO ) )
09824         return ( 0 );
09825 
09826     if( ssl->handshake == NULL || ssl->handshake->mtu == 0 )
09827         return( ssl->mtu );
09828 
09829     if( ssl->mtu == 0 )
09830         return( ssl->handshake->mtu );
09831 
09832     return( ssl->mtu < ssl->handshake->mtu ?
09833             ssl->mtu : ssl->handshake->mtu );
09834 }
09835 #endif /* MBEDTLS_SSL_PROTO_DTLS */
09836 
09837 int mbedtls_ssl_get_max_out_record_payload( const mbedtls_ssl_context *ssl )
09838 {
09839     size_t max_len = MBEDTLS_SSL_OUT_CONTENT_LEN;
09840 
09841 #if !defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) && \
09842     !defined(MBEDTLS_SSL_PROTO_DTLS)
09843     (void) ssl;
09844 #endif
09845 
09846 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
09847     const size_t mfl = mbedtls_ssl_get_max_frag_len( ssl );
09848 
09849     if( max_len > mfl )
09850         max_len = mfl;
09851 #endif
09852 
09853 #if defined(MBEDTLS_SSL_PROTO_DTLS)
09854     if( ssl_get_current_mtu( ssl ) != 0 )
09855     {
09856         const size_t mtu = ssl_get_current_mtu( ssl );
09857         const int ret = mbedtls_ssl_get_record_expansion( ssl );
09858         const size_t overhead = (size_t) ret;
09859 
09860         if( ret < 0 )
09861             return( ret );
09862 
09863         if( mtu <= overhead )
09864         {
09865             MBEDTLS_SSL_DEBUG_MSG( 1, ( "MTU too low for record expansion" ) );
09866             return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
09867         }
09868 
09869         if( max_len > mtu - overhead )
09870             max_len = mtu - overhead;
09871     }
09872 #endif /* MBEDTLS_SSL_PROTO_DTLS */
09873 
09874 #if !defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) &&        \
09875     !defined(MBEDTLS_SSL_PROTO_DTLS)
09876     ((void) ssl);
09877 #endif
09878 
09879     return( (int) max_len );
09880 }
09881 
09882 #if defined(MBEDTLS_X509_CRT_PARSE_C)
09883 const mbedtls_x509_crt *mbedtls_ssl_get_peer_cert( const mbedtls_ssl_context *ssl )
09884 {
09885     if( ssl == NULL || ssl->session == NULL )
09886         return( NULL );
09887 
09888 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
09889     return( ssl->session->peer_cert );
09890 #else
09891     return( NULL );
09892 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
09893 }
09894 #endif /* MBEDTLS_X509_CRT_PARSE_C */
09895 
09896 #if defined(MBEDTLS_SSL_CLI_C)
09897 int mbedtls_ssl_get_session( const mbedtls_ssl_context *ssl,
09898                              mbedtls_ssl_session *dst )
09899 {
09900     if( ssl == NULL ||
09901         dst == NULL ||
09902         ssl->session == NULL ||
09903         ssl->conf->endpoint != MBEDTLS_SSL_IS_CLIENT )
09904     {
09905         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
09906     }
09907 
09908     return( mbedtls_ssl_session_copy( dst, ssl->session ) );
09909 }
09910 #endif /* MBEDTLS_SSL_CLI_C */
09911 
09912 const mbedtls_ssl_session *mbedtls_ssl_get_session_pointer( const mbedtls_ssl_context *ssl )
09913 {
09914     if( ssl == NULL )
09915         return( NULL );
09916 
09917     return( ssl->session );
09918 }
09919 
09920 /*
09921  * Define ticket header determining Mbed TLS version
09922  * and structure of the ticket.
09923  */
09924 
09925 /*
09926  * Define bitflag determining compile-time settings influencing
09927  * structure of serialized SSL sessions.
09928  */
09929 
09930 #if defined(MBEDTLS_HAVE_TIME)
09931 #define SSL_SERIALIZED_SESSION_CONFIG_TIME 1
09932 #else
09933 #define SSL_SERIALIZED_SESSION_CONFIG_TIME 0
09934 #endif /* MBEDTLS_HAVE_TIME */
09935 
09936 #if defined(MBEDTLS_X509_CRT_PARSE_C)
09937 #define SSL_SERIALIZED_SESSION_CONFIG_CRT 1
09938 #else
09939 #define SSL_SERIALIZED_SESSION_CONFIG_CRT 0
09940 #endif /* MBEDTLS_X509_CRT_PARSE_C */
09941 
09942 #if defined(MBEDTLS_SSL_CLI_C) && defined(MBEDTLS_SSL_SESSION_TICKETS)
09943 #define SSL_SERIALIZED_SESSION_CONFIG_CLIENT_TICKET 1
09944 #else
09945 #define SSL_SERIALIZED_SESSION_CONFIG_CLIENT_TICKET 0
09946 #endif /* MBEDTLS_SSL_CLI_C && MBEDTLS_SSL_SESSION_TICKETS */
09947 
09948 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
09949 #define SSL_SERIALIZED_SESSION_CONFIG_MFL 1
09950 #else
09951 #define SSL_SERIALIZED_SESSION_CONFIG_MFL 0
09952 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
09953 
09954 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
09955 #define SSL_SERIALIZED_SESSION_CONFIG_TRUNC_HMAC 1
09956 #else
09957 #define SSL_SERIALIZED_SESSION_CONFIG_TRUNC_HMAC 0
09958 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
09959 
09960 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
09961 #define SSL_SERIALIZED_SESSION_CONFIG_ETM 1
09962 #else
09963 #define SSL_SERIALIZED_SESSION_CONFIG_ETM 0
09964 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
09965 
09966 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
09967 #define SSL_SERIALIZED_SESSION_CONFIG_TICKET 1
09968 #else
09969 #define SSL_SERIALIZED_SESSION_CONFIG_TICKET 0
09970 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
09971 
09972 #define SSL_SERIALIZED_SESSION_CONFIG_TIME_BIT          0
09973 #define SSL_SERIALIZED_SESSION_CONFIG_CRT_BIT           1
09974 #define SSL_SERIALIZED_SESSION_CONFIG_CLIENT_TICKET_BIT 2
09975 #define SSL_SERIALIZED_SESSION_CONFIG_MFL_BIT           3
09976 #define SSL_SERIALIZED_SESSION_CONFIG_TRUNC_HMAC_BIT    4
09977 #define SSL_SERIALIZED_SESSION_CONFIG_ETM_BIT           5
09978 #define SSL_SERIALIZED_SESSION_CONFIG_TICKET_BIT        6
09979 
09980 #define SSL_SERIALIZED_SESSION_CONFIG_BITFLAG                           \
09981     ( (uint16_t) (                                                      \
09982         ( SSL_SERIALIZED_SESSION_CONFIG_TIME          << SSL_SERIALIZED_SESSION_CONFIG_TIME_BIT          ) | \
09983         ( SSL_SERIALIZED_SESSION_CONFIG_CRT           << SSL_SERIALIZED_SESSION_CONFIG_CRT_BIT           ) | \
09984         ( SSL_SERIALIZED_SESSION_CONFIG_CLIENT_TICKET << SSL_SERIALIZED_SESSION_CONFIG_CLIENT_TICKET_BIT ) | \
09985         ( SSL_SERIALIZED_SESSION_CONFIG_MFL           << SSL_SERIALIZED_SESSION_CONFIG_MFL_BIT           ) | \
09986         ( SSL_SERIALIZED_SESSION_CONFIG_TRUNC_HMAC    << SSL_SERIALIZED_SESSION_CONFIG_TRUNC_HMAC_BIT    ) | \
09987         ( SSL_SERIALIZED_SESSION_CONFIG_ETM           << SSL_SERIALIZED_SESSION_CONFIG_ETM_BIT           ) | \
09988         ( SSL_SERIALIZED_SESSION_CONFIG_TICKET        << SSL_SERIALIZED_SESSION_CONFIG_TICKET_BIT        ) ) )
09989 
09990 static unsigned char ssl_serialized_session_header[] = {
09991     MBEDTLS_VERSION_MAJOR,
09992     MBEDTLS_VERSION_MINOR,
09993     MBEDTLS_VERSION_PATCH,
09994     ( SSL_SERIALIZED_SESSION_CONFIG_BITFLAG >> 8 ) & 0xFF,
09995     ( SSL_SERIALIZED_SESSION_CONFIG_BITFLAG >> 0 ) & 0xFF,
09996 };
09997 
09998 /*
09999  * Serialize a session in the following format:
10000  * (in the presentation language of TLS, RFC 8446 section 3)
10001  *
10002  *  opaque mbedtls_version[3];   // major, minor, patch
10003  *  opaque session_format[2];    // version-specific 16-bit field determining
10004  *                               // the format of the remaining
10005  *                               // serialized data.
10006  *
10007  *  Note: When updating the format, remember to keep
10008  *        these version+format bytes.
10009  *
10010  *                               // In this version, `session_format` determines
10011  *                               // the setting of those compile-time
10012  *                               // configuration options which influence
10013  *                               // the structure of mbedtls_ssl_session.
10014  *  uint64 start_time;
10015  *  uint8 ciphersuite[2];        // defined by the standard
10016  *  uint8 compression;           // 0 or 1
10017  *  uint8 session_id_len;        // at most 32
10018  *  opaque session_id[32];
10019  *  opaque master[48];           // fixed length in the standard
10020  *  uint32 verify_result;
10021  *  opaque peer_cert<0..2^24-1>; // length 0 means no peer cert
10022  *  opaque ticket<0..2^24-1>;    // length 0 means no ticket
10023  *  uint32 ticket_lifetime;
10024  *  uint8 mfl_code;              // up to 255 according to standard
10025  *  uint8 trunc_hmac;            // 0 or 1
10026  *  uint8 encrypt_then_mac;      // 0 or 1
10027  *
10028  * The order is the same as in the definition of the structure, except
10029  * verify_result is put before peer_cert so that all mandatory fields come
10030  * together in one block.
10031  */
10032 static int ssl_session_save( const mbedtls_ssl_session *session,
10033                              unsigned char omit_header,
10034                              unsigned char *buf,
10035                              size_t buf_len,
10036                              size_t *olen )
10037 {
10038     unsigned char *p = buf;
10039     size_t used = 0;
10040 #if defined(MBEDTLS_HAVE_TIME)
10041     uint64_t start;
10042 #endif
10043 #if defined(MBEDTLS_X509_CRT_PARSE_C)
10044 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
10045     size_t cert_len;
10046 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
10047 #endif /* MBEDTLS_X509_CRT_PARSE_C */
10048 
10049 
10050     if( !omit_header )
10051     {
10052         /*
10053          * Add version identifier
10054          */
10055 
10056         used += sizeof( ssl_serialized_session_header );
10057 
10058         if( used <= buf_len )
10059         {
10060             memcpy( p, ssl_serialized_session_header,
10061                     sizeof( ssl_serialized_session_header ) );
10062             p += sizeof( ssl_serialized_session_header );
10063         }
10064     }
10065 
10066     /*
10067      * Time
10068      */
10069 #if defined(MBEDTLS_HAVE_TIME)
10070     used += 8;
10071 
10072     if( used <= buf_len )
10073     {
10074         start = (uint64_t) session->start;
10075 
10076         *p++ = (unsigned char)( ( start >> 56 ) & 0xFF );
10077         *p++ = (unsigned char)( ( start >> 48 ) & 0xFF );
10078         *p++ = (unsigned char)( ( start >> 40 ) & 0xFF );
10079         *p++ = (unsigned char)( ( start >> 32 ) & 0xFF );
10080         *p++ = (unsigned char)( ( start >> 24 ) & 0xFF );
10081         *p++ = (unsigned char)( ( start >> 16 ) & 0xFF );
10082         *p++ = (unsigned char)( ( start >>  8 ) & 0xFF );
10083         *p++ = (unsigned char)( ( start       ) & 0xFF );
10084     }
10085 #endif /* MBEDTLS_HAVE_TIME */
10086 
10087     /*
10088      * Basic mandatory fields
10089      */
10090     used += 2   /* ciphersuite */
10091           + 1   /* compression */
10092           + 1   /* id_len */
10093           + sizeof( session->id )
10094           + sizeof( session->master )
10095           + 4;  /* verify_result */
10096 
10097     if( used <= buf_len )
10098     {
10099         *p++ = (unsigned char)( ( session->ciphersuite >> 8 ) & 0xFF );
10100         *p++ = (unsigned char)( ( session->ciphersuite      ) & 0xFF );
10101 
10102         *p++ = (unsigned char)( session->compression & 0xFF );
10103 
10104         *p++ = (unsigned char)( session->id_len & 0xFF );
10105         memcpy( p, session->id, 32 );
10106         p += 32;
10107 
10108         memcpy( p, session->master, 48 );
10109         p += 48;
10110 
10111         *p++ = (unsigned char)( ( session->verify_result >> 24 ) & 0xFF );
10112         *p++ = (unsigned char)( ( session->verify_result >> 16 ) & 0xFF );
10113         *p++ = (unsigned char)( ( session->verify_result >>  8 ) & 0xFF );
10114         *p++ = (unsigned char)( ( session->verify_result       ) & 0xFF );
10115     }
10116 
10117     /*
10118      * Peer's end-entity certificate
10119      */
10120 #if defined(MBEDTLS_X509_CRT_PARSE_C)
10121 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
10122     if( session->peer_cert == NULL )
10123         cert_len = 0;
10124     else
10125         cert_len = session->peer_cert->raw.len;
10126 
10127     used += 3 + cert_len;
10128 
10129     if( used <= buf_len )
10130     {
10131         *p++ = (unsigned char)( ( cert_len >> 16 ) & 0xFF );
10132         *p++ = (unsigned char)( ( cert_len >>  8 ) & 0xFF );
10133         *p++ = (unsigned char)( ( cert_len       ) & 0xFF );
10134 
10135         if( session->peer_cert != NULL )
10136         {
10137             memcpy( p, session->peer_cert->raw.p, cert_len );
10138             p += cert_len;
10139         }
10140     }
10141 #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
10142     if( session->peer_cert_digest != NULL )
10143     {
10144         used += 1 /* type */ + 1 /* length */ + session->peer_cert_digest_len;
10145         if( used <= buf_len )
10146         {
10147             *p++ = (unsigned char) session->peer_cert_digest_type;
10148             *p++ = (unsigned char) session->peer_cert_digest_len;
10149             memcpy( p, session->peer_cert_digest,
10150                     session->peer_cert_digest_len );
10151             p += session->peer_cert_digest_len;
10152         }
10153     }
10154     else
10155     {
10156         used += 2;
10157         if( used <= buf_len )
10158         {
10159             *p++ = (unsigned char) MBEDTLS_MD_NONE;
10160             *p++ = 0;
10161         }
10162     }
10163 #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
10164 #endif /* MBEDTLS_X509_CRT_PARSE_C */
10165 
10166     /*
10167      * Session ticket if any, plus associated data
10168      */
10169 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
10170     used += 3 + session->ticket_len + 4; /* len + ticket + lifetime */
10171 
10172     if( used <= buf_len )
10173     {
10174         *p++ = (unsigned char)( ( session->ticket_len >> 16 ) & 0xFF );
10175         *p++ = (unsigned char)( ( session->ticket_len >>  8 ) & 0xFF );
10176         *p++ = (unsigned char)( ( session->ticket_len       ) & 0xFF );
10177 
10178         if( session->ticket != NULL )
10179         {
10180             memcpy( p, session->ticket, session->ticket_len );
10181             p += session->ticket_len;
10182         }
10183 
10184         *p++ = (unsigned char)( ( session->ticket_lifetime >> 24 ) & 0xFF );
10185         *p++ = (unsigned char)( ( session->ticket_lifetime >> 16 ) & 0xFF );
10186         *p++ = (unsigned char)( ( session->ticket_lifetime >>  8 ) & 0xFF );
10187         *p++ = (unsigned char)( ( session->ticket_lifetime       ) & 0xFF );
10188     }
10189 #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */
10190 
10191     /*
10192      * Misc extension-related info
10193      */
10194 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
10195     used += 1;
10196 
10197     if( used <= buf_len )
10198         *p++ = session->mfl_code;
10199 #endif
10200 
10201 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
10202     used += 1;
10203 
10204     if( used <= buf_len )
10205         *p++ = (unsigned char)( ( session->trunc_hmac ) & 0xFF );
10206 #endif
10207 
10208 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
10209     used += 1;
10210 
10211     if( used <= buf_len )
10212         *p++ = (unsigned char)( ( session->encrypt_then_mac ) & 0xFF );
10213 #endif
10214 
10215     /* Done */
10216     *olen = used;
10217 
10218     if( used > buf_len )
10219         return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
10220 
10221     return( 0 );
10222 }
10223 
10224 /*
10225  * Public wrapper for ssl_session_save()
10226  */
10227 int mbedtls_ssl_session_save( const mbedtls_ssl_session *session,
10228                               unsigned char *buf,
10229                               size_t buf_len,
10230                               size_t *olen )
10231 {
10232     return( ssl_session_save( session, 0, buf, buf_len, olen ) );
10233 }
10234 
10235 /*
10236  * Deserialize session, see mbedtls_ssl_session_save() for format.
10237  *
10238  * This internal version is wrapped by a public function that cleans up in
10239  * case of error, and has an extra option omit_header.
10240  */
10241 static int ssl_session_load( mbedtls_ssl_session *session,
10242                              unsigned char omit_header,
10243                              const unsigned char *buf,
10244                              size_t len )
10245 {
10246     const unsigned char *p = buf;
10247     const unsigned char * const end = buf + len;
10248 #if defined(MBEDTLS_HAVE_TIME)
10249     uint64_t start;
10250 #endif
10251 #if defined(MBEDTLS_X509_CRT_PARSE_C)
10252 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
10253     size_t cert_len;
10254 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
10255 #endif /* MBEDTLS_X509_CRT_PARSE_C */
10256 
10257     if( !omit_header )
10258     {
10259         /*
10260          * Check version identifier
10261          */
10262 
10263         if( (size_t)( end - p ) < sizeof( ssl_serialized_session_header ) )
10264             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
10265 
10266         if( memcmp( p, ssl_serialized_session_header,
10267                     sizeof( ssl_serialized_session_header ) ) != 0 )
10268         {
10269             return( MBEDTLS_ERR_SSL_VERSION_MISMATCH );
10270         }
10271         p += sizeof( ssl_serialized_session_header );
10272     }
10273 
10274     /*
10275      * Time
10276      */
10277 #if defined(MBEDTLS_HAVE_TIME)
10278     if( 8 > (size_t)( end - p ) )
10279         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
10280 
10281     start = ( (uint64_t) p[0] << 56 ) |
10282             ( (uint64_t) p[1] << 48 ) |
10283             ( (uint64_t) p[2] << 40 ) |
10284             ( (uint64_t) p[3] << 32 ) |
10285             ( (uint64_t) p[4] << 24 ) |
10286             ( (uint64_t) p[5] << 16 ) |
10287             ( (uint64_t) p[6] <<  8 ) |
10288             ( (uint64_t) p[7]       );
10289     p += 8;
10290 
10291     session->start = (time_t) start;
10292 #endif /* MBEDTLS_HAVE_TIME */
10293 
10294     /*
10295      * Basic mandatory fields
10296      */
10297     if( 2 + 1 + 1 + 32 + 48 + 4 > (size_t)( end - p ) )
10298         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
10299 
10300     session->ciphersuite = ( p[0] << 8 ) | p[1];
10301     p += 2;
10302 
10303     session->compression = *p++;
10304 
10305     session->id_len = *p++;
10306     memcpy( session->id, p, 32 );
10307     p += 32;
10308 
10309     memcpy( session->master, p, 48 );
10310     p += 48;
10311 
10312     session->verify_result = ( (uint32_t) p[0] << 24 ) |
10313                              ( (uint32_t) p[1] << 16 ) |
10314                              ( (uint32_t) p[2] <<  8 ) |
10315                              ( (uint32_t) p[3]       );
10316     p += 4;
10317 
10318     /* Immediately clear invalid pointer values that have been read, in case
10319      * we exit early before we replaced them with valid ones. */
10320 #if defined(MBEDTLS_X509_CRT_PARSE_C)
10321 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
10322     session->peer_cert = NULL;
10323 #else
10324     session->peer_cert_digest = NULL;
10325 #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
10326 #endif /* MBEDTLS_X509_CRT_PARSE_C */
10327 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
10328     session->ticket = NULL;
10329 #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */
10330 
10331     /*
10332      * Peer certificate
10333      */
10334 #if defined(MBEDTLS_X509_CRT_PARSE_C)
10335 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
10336     /* Deserialize CRT from the end of the ticket. */
10337     if( 3 > (size_t)( end - p ) )
10338         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
10339 
10340     cert_len = ( p[0] << 16 ) | ( p[1] << 8 ) | p[2];
10341     p += 3;
10342 
10343     if( cert_len != 0 )
10344     {
10345         int ret;
10346 
10347         if( cert_len > (size_t)( end - p ) )
10348             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
10349 
10350         session->peer_cert = mbedtls_calloc( 1, sizeof( mbedtls_x509_crt ) );
10351 
10352         if( session->peer_cert == NULL )
10353             return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
10354 
10355         mbedtls_x509_crt_init( session->peer_cert );
10356 
10357         if( ( ret = mbedtls_x509_crt_parse_der( session->peer_cert,
10358                                                 p, cert_len ) ) != 0 )
10359         {
10360             mbedtls_x509_crt_free( session->peer_cert );
10361             mbedtls_free( session->peer_cert );
10362             session->peer_cert = NULL;
10363             return( ret );
10364         }
10365 
10366         p += cert_len;
10367     }
10368 #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
10369     /* Deserialize CRT digest from the end of the ticket. */
10370     if( 2 > (size_t)( end - p ) )
10371         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
10372 
10373     session->peer_cert_digest_type = (mbedtls_md_type_t) *p++;
10374     session->peer_cert_digest_len  = (size_t) *p++;
10375 
10376     if( session->peer_cert_digest_len != 0 )
10377     {
10378         const mbedtls_md_info_t *md_info =
10379             mbedtls_md_info_from_type( session->peer_cert_digest_type );
10380         if( md_info == NULL )
10381             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
10382         if( session->peer_cert_digest_len != mbedtls_md_get_size( md_info ) )
10383             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
10384 
10385         if( session->peer_cert_digest_len > (size_t)( end - p ) )
10386             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
10387 
10388         session->peer_cert_digest =
10389             mbedtls_calloc( 1, session->peer_cert_digest_len );
10390         if( session->peer_cert_digest == NULL )
10391             return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
10392 
10393         memcpy( session->peer_cert_digest, p,
10394                 session->peer_cert_digest_len );
10395         p += session->peer_cert_digest_len;
10396     }
10397 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
10398 #endif /* MBEDTLS_X509_CRT_PARSE_C */
10399 
10400     /*
10401      * Session ticket and associated data
10402      */
10403 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
10404     if( 3 > (size_t)( end - p ) )
10405         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
10406 
10407     session->ticket_len = ( p[0] << 16 ) | ( p[1] << 8 ) | p[2];
10408     p += 3;
10409 
10410     if( session->ticket_len != 0 )
10411     {
10412         if( session->ticket_len > (size_t)( end - p ) )
10413             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
10414 
10415         session->ticket = mbedtls_calloc( 1, session->ticket_len );
10416         if( session->ticket == NULL )
10417             return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
10418 
10419         memcpy( session->ticket, p, session->ticket_len );
10420         p += session->ticket_len;
10421     }
10422 
10423     if( 4 > (size_t)( end - p ) )
10424         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
10425 
10426     session->ticket_lifetime = ( (uint32_t) p[0] << 24 ) |
10427                                ( (uint32_t) p[1] << 16 ) |
10428                                ( (uint32_t) p[2] <<  8 ) |
10429                                ( (uint32_t) p[3]       );
10430     p += 4;
10431 #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */
10432 
10433     /*
10434      * Misc extension-related info
10435      */
10436 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
10437     if( 1 > (size_t)( end - p ) )
10438         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
10439 
10440     session->mfl_code = *p++;
10441 #endif
10442 
10443 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
10444     if( 1 > (size_t)( end - p ) )
10445         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
10446 
10447     session->trunc_hmac = *p++;
10448 #endif
10449 
10450 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
10451     if( 1 > (size_t)( end - p ) )
10452         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
10453 
10454     session->encrypt_then_mac = *p++;
10455 #endif
10456 
10457     /* Done, should have consumed entire buffer */
10458     if( p != end )
10459         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
10460 
10461     return( 0 );
10462 }
10463 
10464 /*
10465  * Deserialize session: public wrapper for error cleaning
10466  */
10467 int mbedtls_ssl_session_load( mbedtls_ssl_session *session,
10468                               const unsigned char *buf,
10469                               size_t len )
10470 {
10471     int ret = ssl_session_load( session, 0, buf, len );
10472 
10473     if( ret != 0 )
10474         mbedtls_ssl_session_free( session );
10475 
10476     return( ret );
10477 }
10478 
10479 /*
10480  * Perform a single step of the SSL handshake
10481  */
10482 int mbedtls_ssl_handshake_step( mbedtls_ssl_context *ssl )
10483 {
10484     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
10485 
10486     if( ssl == NULL || ssl->conf == NULL )
10487         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
10488 
10489 #if defined(MBEDTLS_SSL_CLI_C)
10490     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
10491         ret = mbedtls_ssl_handshake_client_step( ssl );
10492 #endif
10493 #if defined(MBEDTLS_SSL_SRV_C)
10494     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
10495         ret = mbedtls_ssl_handshake_server_step( ssl );
10496 #endif
10497 
10498     return( ret );
10499 }
10500 
10501 /*
10502  * Perform the SSL handshake
10503  */
10504 int mbedtls_ssl_handshake( mbedtls_ssl_context *ssl )
10505 {
10506     int ret = 0;
10507 
10508     if( ssl == NULL || ssl->conf == NULL )
10509         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
10510 
10511     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> handshake" ) );
10512 
10513     while( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
10514     {
10515         ret = mbedtls_ssl_handshake_step( ssl );
10516 
10517         if( ret != 0 )
10518             break;
10519     }
10520 
10521     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= handshake" ) );
10522 
10523     return( ret );
10524 }
10525 
10526 #if defined(MBEDTLS_SSL_RENEGOTIATION)
10527 #if defined(MBEDTLS_SSL_SRV_C)
10528 /*
10529  * Write HelloRequest to request renegotiation on server
10530  */
10531 static int ssl_write_hello_request( mbedtls_ssl_context *ssl )
10532 {
10533     int ret;
10534 
10535     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write hello request" ) );
10536 
10537     ssl->out_msglen  = 4;
10538     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
10539     ssl->out_msg[0]  = MBEDTLS_SSL_HS_HELLO_REQUEST;
10540 
10541     if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
10542     {
10543         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
10544         return( ret );
10545     }
10546 
10547     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write hello request" ) );
10548 
10549     return( 0 );
10550 }
10551 #endif /* MBEDTLS_SSL_SRV_C */
10552 
10553 /*
10554  * Actually renegotiate current connection, triggered by either:
10555  * - any side: calling mbedtls_ssl_renegotiate(),
10556  * - client: receiving a HelloRequest during mbedtls_ssl_read(),
10557  * - server: receiving any handshake message on server during mbedtls_ssl_read() after
10558  *   the initial handshake is completed.
10559  * If the handshake doesn't complete due to waiting for I/O, it will continue
10560  * during the next calls to mbedtls_ssl_renegotiate() or mbedtls_ssl_read() respectively.
10561  */
10562 static int ssl_start_renegotiation( mbedtls_ssl_context *ssl )
10563 {
10564     int ret;
10565 
10566     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> renegotiate" ) );
10567 
10568     if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
10569         return( ret );
10570 
10571     /* RFC 6347 4.2.2: "[...] the HelloRequest will have message_seq = 0 and
10572      * the ServerHello will have message_seq = 1" */
10573 #if defined(MBEDTLS_SSL_PROTO_DTLS)
10574     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
10575         ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
10576     {
10577         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
10578             ssl->handshake->out_msg_seq = 1;
10579         else
10580             ssl->handshake->in_msg_seq = 1;
10581     }
10582 #endif
10583 
10584     ssl->state = MBEDTLS_SSL_HELLO_REQUEST;
10585     ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS;
10586 
10587     if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 )
10588     {
10589         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
10590         return( ret );
10591     }
10592 
10593     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= renegotiate" ) );
10594 
10595     return( 0 );
10596 }
10597 
10598 /*
10599  * Renegotiate current connection on client,
10600  * or request renegotiation on server
10601  */
10602 int mbedtls_ssl_renegotiate( mbedtls_ssl_context *ssl )
10603 {
10604     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
10605 
10606     if( ssl == NULL || ssl->conf == NULL )
10607         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
10608 
10609 #if defined(MBEDTLS_SSL_SRV_C)
10610     /* On server, just send the request */
10611     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
10612     {
10613         if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
10614             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
10615 
10616         ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_PENDING;
10617 
10618         /* Did we already try/start sending HelloRequest? */
10619         if( ssl->out_left != 0 )
10620             return( mbedtls_ssl_flush_output( ssl ) );
10621 
10622         return( ssl_write_hello_request( ssl ) );
10623     }
10624 #endif /* MBEDTLS_SSL_SRV_C */
10625 
10626 #if defined(MBEDTLS_SSL_CLI_C)
10627     /*
10628      * On client, either start the renegotiation process or,
10629      * if already in progress, continue the handshake
10630      */
10631     if( ssl->renego_status != MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
10632     {
10633         if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
10634             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
10635 
10636         if( ( ret = ssl_start_renegotiation( ssl ) ) != 0 )
10637         {
10638             MBEDTLS_SSL_DEBUG_RET( 1, "ssl_start_renegotiation", ret );
10639             return( ret );
10640         }
10641     }
10642     else
10643     {
10644         if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 )
10645         {
10646             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
10647             return( ret );
10648         }
10649     }
10650 #endif /* MBEDTLS_SSL_CLI_C */
10651 
10652     return( ret );
10653 }
10654 
10655 /*
10656  * Check record counters and renegotiate if they're above the limit.
10657  */
10658 static int ssl_check_ctr_renegotiate( mbedtls_ssl_context *ssl )
10659 {
10660     size_t ep_len = ssl_ep_len( ssl );
10661     int in_ctr_cmp;
10662     int out_ctr_cmp;
10663 
10664     if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ||
10665         ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING ||
10666         ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED )
10667     {
10668         return( 0 );
10669     }
10670 
10671     in_ctr_cmp = memcmp( ssl->in_ctr + ep_len,
10672                         ssl->conf->renego_period + ep_len, 8 - ep_len );
10673     out_ctr_cmp = memcmp( ssl->cur_out_ctr + ep_len,
10674                           ssl->conf->renego_period + ep_len, 8 - ep_len );
10675 
10676     if( in_ctr_cmp <= 0 && out_ctr_cmp <= 0 )
10677     {
10678         return( 0 );
10679     }
10680 
10681     MBEDTLS_SSL_DEBUG_MSG( 1, ( "record counter limit reached: renegotiate" ) );
10682     return( mbedtls_ssl_renegotiate( ssl ) );
10683 }
10684 #endif /* MBEDTLS_SSL_RENEGOTIATION */
10685 
10686 /*
10687  * Receive application data decrypted from the SSL layer
10688  */
10689 int mbedtls_ssl_read( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len )
10690 {
10691     int ret;
10692     size_t n;
10693 
10694     if( ssl == NULL || ssl->conf == NULL )
10695         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
10696 
10697     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> read" ) );
10698 
10699 #if defined(MBEDTLS_SSL_PROTO_DTLS)
10700     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
10701     {
10702         if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
10703             return( ret );
10704 
10705         if( ssl->handshake != NULL &&
10706             ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING )
10707         {
10708             if( ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 )
10709                 return( ret );
10710         }
10711     }
10712 #endif
10713 
10714     /*
10715      * Check if renegotiation is necessary and/or handshake is
10716      * in process. If yes, perform/continue, and fall through
10717      * if an unexpected packet is received while the client
10718      * is waiting for the ServerHello.
10719      *
10720      * (There is no equivalent to the last condition on
10721      *  the server-side as it is not treated as within
10722      *  a handshake while waiting for the ClientHello
10723      *  after a renegotiation request.)
10724      */
10725 
10726 #if defined(MBEDTLS_SSL_RENEGOTIATION)
10727     ret = ssl_check_ctr_renegotiate( ssl );
10728     if( ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO &&
10729         ret != 0 )
10730     {
10731         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_check_ctr_renegotiate", ret );
10732         return( ret );
10733     }
10734 #endif
10735 
10736     if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
10737     {
10738         ret = mbedtls_ssl_handshake( ssl );
10739         if( ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO &&
10740             ret != 0 )
10741         {
10742             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
10743             return( ret );
10744         }
10745     }
10746 
10747     /* Loop as long as no application data record is available */
10748     while( ssl->in_offt == NULL )
10749     {
10750         /* Start timer if not already running */
10751         if( ssl->f_get_timer != NULL &&
10752             ssl->f_get_timer( ssl->p_timer ) == -1 )
10753         {
10754             ssl_set_timer( ssl, ssl->conf->read_timeout );
10755         }
10756 
10757         if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
10758         {
10759             if( ret == MBEDTLS_ERR_SSL_CONN_EOF )
10760                 return( 0 );
10761 
10762             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
10763             return( ret );
10764         }
10765 
10766         if( ssl->in_msglen  == 0 &&
10767             ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA )
10768         {
10769             /*
10770              * OpenSSL sends empty messages to randomize the IV
10771              */
10772             if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
10773             {
10774                 if( ret == MBEDTLS_ERR_SSL_CONN_EOF )
10775                     return( 0 );
10776 
10777                 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
10778                 return( ret );
10779             }
10780         }
10781 
10782         if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE )
10783         {
10784             MBEDTLS_SSL_DEBUG_MSG( 1, ( "received handshake message" ) );
10785 
10786             /*
10787              * - For client-side, expect SERVER_HELLO_REQUEST.
10788              * - For server-side, expect CLIENT_HELLO.
10789              * - Fail (TLS) or silently drop record (DTLS) in other cases.
10790              */
10791 
10792 #if defined(MBEDTLS_SSL_CLI_C)
10793             if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&
10794                 ( ssl->in_msg[0] != MBEDTLS_SSL_HS_HELLO_REQUEST ||
10795                   ssl->in_hslen  != mbedtls_ssl_hs_hdr_len( ssl ) ) )
10796             {
10797                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake received (not HelloRequest)" ) );
10798 
10799                 /* With DTLS, drop the packet (probably from last handshake) */
10800 #if defined(MBEDTLS_SSL_PROTO_DTLS)
10801                 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
10802                 {
10803                     continue;
10804                 }
10805 #endif
10806                 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
10807             }
10808 #endif /* MBEDTLS_SSL_CLI_C */
10809 
10810 #if defined(MBEDTLS_SSL_SRV_C)
10811             if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
10812                 ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_HELLO )
10813             {
10814                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake received (not ClientHello)" ) );
10815 
10816                 /* With DTLS, drop the packet (probably from last handshake) */
10817 #if defined(MBEDTLS_SSL_PROTO_DTLS)
10818                 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
10819                 {
10820                     continue;
10821                 }
10822 #endif
10823                 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
10824             }
10825 #endif /* MBEDTLS_SSL_SRV_C */
10826 
10827 #if defined(MBEDTLS_SSL_RENEGOTIATION)
10828             /* Determine whether renegotiation attempt should be accepted */
10829             if( ! ( ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED ||
10830                     ( ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
10831                       ssl->conf->allow_legacy_renegotiation ==
10832                                                    MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION ) ) )
10833             {
10834                 /*
10835                  * Accept renegotiation request
10836                  */
10837 
10838                 /* DTLS clients need to know renego is server-initiated */
10839 #if defined(MBEDTLS_SSL_PROTO_DTLS)
10840                 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
10841                     ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
10842                 {
10843                     ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_PENDING;
10844                 }
10845 #endif
10846                 ret = ssl_start_renegotiation( ssl );
10847                 if( ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO &&
10848                     ret != 0 )
10849                 {
10850                     MBEDTLS_SSL_DEBUG_RET( 1, "ssl_start_renegotiation", ret );
10851                     return( ret );
10852                 }
10853             }
10854             else
10855 #endif /* MBEDTLS_SSL_RENEGOTIATION */
10856             {
10857                 /*
10858                  * Refuse renegotiation
10859                  */
10860 
10861                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "refusing renegotiation, sending alert" ) );
10862 
10863 #if defined(MBEDTLS_SSL_PROTO_SSL3)
10864                 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
10865                 {
10866                     /* SSLv3 does not have a "no_renegotiation" warning, so
10867                        we send a fatal alert and abort the connection. */
10868                     mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
10869                                                     MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
10870                     return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
10871                 }
10872                 else
10873 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
10874 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
10875     defined(MBEDTLS_SSL_PROTO_TLS1_2)
10876                 if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 )
10877                 {
10878                     if( ( ret = mbedtls_ssl_send_alert_message( ssl,
10879                                     MBEDTLS_SSL_ALERT_LEVEL_WARNING,
10880                                     MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION ) ) != 0 )
10881                     {
10882                         return( ret );
10883                     }
10884                 }
10885                 else
10886 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 ||
10887           MBEDTLS_SSL_PROTO_TLS1_2 */
10888                 {
10889                     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
10890                     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
10891                 }
10892             }
10893 
10894             /* At this point, we don't know whether the renegotiation has been
10895              * completed or not. The cases to consider are the following:
10896              * 1) The renegotiation is complete. In this case, no new record
10897              *    has been read yet.
10898              * 2) The renegotiation is incomplete because the client received
10899              *    an application data record while awaiting the ServerHello.
10900              * 3) The renegotiation is incomplete because the client received
10901              *    a non-handshake, non-application data message while awaiting
10902              *    the ServerHello.
10903              * In each of these case, looping will be the proper action:
10904              * - For 1), the next iteration will read a new record and check
10905              *   if it's application data.
10906              * - For 2), the loop condition isn't satisfied as application data
10907              *   is present, hence continue is the same as break
10908              * - For 3), the loop condition is satisfied and read_record
10909              *   will re-deliver the message that was held back by the client
10910              *   when expecting the ServerHello.
10911              */
10912             continue;
10913         }
10914 #if defined(MBEDTLS_SSL_RENEGOTIATION)
10915         else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
10916         {
10917             if( ssl->conf->renego_max_records >= 0 )
10918             {
10919                 if( ++ssl->renego_records_seen > ssl->conf->renego_max_records )
10920                 {
10921                     MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation requested, "
10922                                         "but not honored by client" ) );
10923                     return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
10924                 }
10925             }
10926         }
10927 #endif /* MBEDTLS_SSL_RENEGOTIATION */
10928 
10929         /* Fatal and closure alerts handled by mbedtls_ssl_read_record() */
10930         if( ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT )
10931         {
10932             MBEDTLS_SSL_DEBUG_MSG( 2, ( "ignoring non-fatal non-closure alert" ) );
10933             return( MBEDTLS_ERR_SSL_WANT_READ );
10934         }
10935 
10936         if( ssl->in_msgtype != MBEDTLS_SSL_MSG_APPLICATION_DATA )
10937         {
10938             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad application data message" ) );
10939             return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
10940         }
10941 
10942         ssl->in_offt = ssl->in_msg;
10943 
10944         /* We're going to return something now, cancel timer,
10945          * except if handshake (renegotiation) is in progress */
10946         if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )
10947             ssl_set_timer( ssl, 0 );
10948 
10949 #if defined(MBEDTLS_SSL_PROTO_DTLS)
10950         /* If we requested renego but received AppData, resend HelloRequest.
10951          * Do it now, after setting in_offt, to avoid taking this branch
10952          * again if ssl_write_hello_request() returns WANT_WRITE */
10953 #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
10954         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
10955             ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
10956         {
10957             if( ( ret = ssl_resend_hello_request( ssl ) ) != 0 )
10958             {
10959                 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_resend_hello_request", ret );
10960                 return( ret );
10961             }
10962         }
10963 #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
10964 #endif /* MBEDTLS_SSL_PROTO_DTLS */
10965     }
10966 
10967     n = ( len < ssl->in_msglen )
10968         ? len : ssl->in_msglen;
10969 
10970     memcpy( buf, ssl->in_offt, n );
10971     ssl->in_msglen -= n;
10972 
10973     if( ssl->in_msglen == 0 )
10974     {
10975         /* all bytes consumed */
10976         ssl->in_offt = NULL;
10977         ssl->keep_current_message = 0;
10978     }
10979     else
10980     {
10981         /* more data available */
10982         ssl->in_offt += n;
10983     }
10984 
10985     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= read" ) );
10986 
10987     return( (int) n );
10988 }
10989 
10990 /*
10991  * Send application data to be encrypted by the SSL layer, taking care of max
10992  * fragment length and buffer size.
10993  *
10994  * According to RFC 5246 Section 6.2.1:
10995  *
10996  *      Zero-length fragments of Application data MAY be sent as they are
10997  *      potentially useful as a traffic analysis countermeasure.
10998  *
10999  * Therefore, it is possible that the input message length is 0 and the
11000  * corresponding return code is 0 on success.
11001  */
11002 static int ssl_write_real( mbedtls_ssl_context *ssl,
11003                            const unsigned char *buf, size_t len )
11004 {
11005     int ret = mbedtls_ssl_get_max_out_record_payload( ssl );
11006     const size_t max_len = (size_t) ret;
11007 
11008     if( ret < 0 )
11009     {
11010         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_get_max_out_record_payload", ret );
11011         return( ret );
11012     }
11013 
11014     if( len > max_len )
11015     {
11016 #if defined(MBEDTLS_SSL_PROTO_DTLS)
11017         if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
11018         {
11019             MBEDTLS_SSL_DEBUG_MSG( 1, ( "fragment larger than the (negotiated) "
11020                                 "maximum fragment length: %d > %d",
11021                                 len, max_len ) );
11022             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
11023         }
11024         else
11025 #endif
11026             len = max_len;
11027     }
11028 
11029     if( ssl->out_left != 0 )
11030     {
11031         /*
11032          * The user has previously tried to send the data and
11033          * MBEDTLS_ERR_SSL_WANT_WRITE or the message was only partially
11034          * written. In this case, we expect the high-level write function
11035          * (e.g. mbedtls_ssl_write()) to be called with the same parameters
11036          */
11037         if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
11038         {
11039             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flush_output", ret );
11040             return( ret );
11041         }
11042     }
11043     else
11044     {
11045         /*
11046          * The user is trying to send a message the first time, so we need to
11047          * copy the data into the internal buffers and setup the data structure
11048          * to keep track of partial writes
11049          */
11050         ssl->out_msglen  = len;
11051         ssl->out_msgtype = MBEDTLS_SSL_MSG_APPLICATION_DATA;
11052         memcpy( ssl->out_msg, buf, len );
11053 
11054         if( ( ret = mbedtls_ssl_write_record( ssl, SSL_FORCE_FLUSH ) ) != 0 )
11055         {
11056             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
11057             return( ret );
11058         }
11059     }
11060 
11061     return( (int) len );
11062 }
11063 
11064 /*
11065  * Write application data, doing 1/n-1 splitting if necessary.
11066  *
11067  * With non-blocking I/O, ssl_write_real() may return WANT_WRITE,
11068  * then the caller will call us again with the same arguments, so
11069  * remember whether we already did the split or not.
11070  */
11071 #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
11072 static int ssl_write_split( mbedtls_ssl_context *ssl,
11073                             const unsigned char *buf, size_t len )
11074 {
11075     int ret;
11076 
11077     if( ssl->conf->cbc_record_splitting ==
11078             MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED ||
11079         len <= 1 ||
11080         ssl->minor_ver > MBEDTLS_SSL_MINOR_VERSION_1 ||
11081         mbedtls_cipher_get_cipher_mode( &ssl->transform_out->cipher_ctx_enc )
11082                                 != MBEDTLS_MODE_CBC )
11083     {
11084         return( ssl_write_real( ssl, buf, len ) );
11085     }
11086 
11087     if( ssl->split_done == 0 )
11088     {
11089         if( ( ret = ssl_write_real( ssl, buf, 1 ) ) <= 0 )
11090             return( ret );
11091         ssl->split_done = 1;
11092     }
11093 
11094     if( ( ret = ssl_write_real( ssl, buf + 1, len - 1 ) ) <= 0 )
11095         return( ret );
11096     ssl->split_done = 0;
11097 
11098     return( ret + 1 );
11099 }
11100 #endif /* MBEDTLS_SSL_CBC_RECORD_SPLITTING */
11101 
11102 /*
11103  * Write application data (public-facing wrapper)
11104  */
11105 int mbedtls_ssl_write( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len )
11106 {
11107     int ret;
11108 
11109     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write" ) );
11110 
11111     if( ssl == NULL || ssl->conf == NULL )
11112         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
11113 
11114 #if defined(MBEDTLS_SSL_RENEGOTIATION)
11115     if( ( ret = ssl_check_ctr_renegotiate( ssl ) ) != 0 )
11116     {
11117         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_check_ctr_renegotiate", ret );
11118         return( ret );
11119     }
11120 #endif
11121 
11122     if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
11123     {
11124         if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 )
11125         {
11126             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
11127             return( ret );
11128         }
11129     }
11130 
11131 #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
11132     ret = ssl_write_split( ssl, buf, len );
11133 #else
11134     ret = ssl_write_real( ssl, buf, len );
11135 #endif
11136 
11137     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write" ) );
11138 
11139     return( ret );
11140 }
11141 
11142 /*
11143  * Notify the peer that the connection is being closed
11144  */
11145 int mbedtls_ssl_close_notify( mbedtls_ssl_context *ssl )
11146 {
11147     int ret;
11148 
11149     if( ssl == NULL || ssl->conf == NULL )
11150         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
11151 
11152     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write close notify" ) );
11153 
11154     if( ssl->out_left != 0 )
11155         return( mbedtls_ssl_flush_output( ssl ) );
11156 
11157     if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )
11158     {
11159         if( ( ret = mbedtls_ssl_send_alert_message( ssl,
11160                         MBEDTLS_SSL_ALERT_LEVEL_WARNING,
11161                         MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY ) ) != 0 )
11162         {
11163             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_send_alert_message", ret );
11164             return( ret );
11165         }
11166     }
11167 
11168     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write close notify" ) );
11169 
11170     return( 0 );
11171 }
11172 
11173 void mbedtls_ssl_transform_free( mbedtls_ssl_transform *transform )
11174 {
11175     if( transform == NULL )
11176         return;
11177 
11178 #if defined(MBEDTLS_ZLIB_SUPPORT)
11179     deflateEnd( &transform->ctx_deflate );
11180     inflateEnd( &transform->ctx_inflate );
11181 #endif
11182 
11183     mbedtls_cipher_free( &transform->cipher_ctx_enc );
11184     mbedtls_cipher_free( &transform->cipher_ctx_dec );
11185 
11186 #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
11187     mbedtls_md_free( &transform->md_ctx_enc );
11188     mbedtls_md_free( &transform->md_ctx_dec );
11189 #endif
11190 
11191     mbedtls_platform_zeroize( transform, sizeof( mbedtls_ssl_transform ) );
11192 }
11193 
11194 #if defined(MBEDTLS_X509_CRT_PARSE_C)
11195 static void ssl_key_cert_free( mbedtls_ssl_key_cert *key_cert )
11196 {
11197     mbedtls_ssl_key_cert *cur = key_cert, *next;
11198 
11199     while( cur != NULL )
11200     {
11201         next = cur->next;
11202         mbedtls_free( cur );
11203         cur = next;
11204     }
11205 }
11206 #endif /* MBEDTLS_X509_CRT_PARSE_C */
11207 
11208 #if defined(MBEDTLS_SSL_PROTO_DTLS)
11209 
11210 static void ssl_buffering_free( mbedtls_ssl_context *ssl )
11211 {
11212     unsigned offset;
11213     mbedtls_ssl_handshake_params * const hs = ssl->handshake;
11214 
11215     if( hs == NULL )
11216         return;
11217 
11218     ssl_free_buffered_record( ssl );
11219 
11220     for( offset = 0; offset < MBEDTLS_SSL_MAX_BUFFERED_HS; offset++ )
11221         ssl_buffering_free_slot( ssl, offset );
11222 }
11223 
11224 static void ssl_buffering_free_slot( mbedtls_ssl_context *ssl,
11225                                      uint8_t slot )
11226 {
11227     mbedtls_ssl_handshake_params * const hs = ssl->handshake;
11228     mbedtls_ssl_hs_buffer * const hs_buf = &hs->buffering.hs[slot];
11229 
11230     if( slot >= MBEDTLS_SSL_MAX_BUFFERED_HS )
11231         return;
11232 
11233     if( hs_buf->is_valid == 1 )
11234     {
11235         hs->buffering.total_bytes_buffered -= hs_buf->data_len;
11236         mbedtls_platform_zeroize( hs_buf->data, hs_buf->data_len );
11237         mbedtls_free( hs_buf->data );
11238         memset( hs_buf, 0, sizeof( mbedtls_ssl_hs_buffer ) );
11239     }
11240 }
11241 
11242 #endif /* MBEDTLS_SSL_PROTO_DTLS */
11243 
11244 void mbedtls_ssl_handshake_free( mbedtls_ssl_context *ssl )
11245 {
11246     mbedtls_ssl_handshake_params *handshake = ssl->handshake;
11247 
11248     if( handshake == NULL )
11249         return;
11250 
11251 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
11252     if( ssl->conf->f_async_cancel != NULL && handshake->async_in_progress != 0 )
11253     {
11254         ssl->conf->f_async_cancel( ssl );
11255         handshake->async_in_progress = 0;
11256     }
11257 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
11258 
11259 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
11260     defined(MBEDTLS_SSL_PROTO_TLS1_1)
11261     mbedtls_md5_free(    &handshake->fin_md5  );
11262     mbedtls_sha1_free(   &handshake->fin_sha1 );
11263 #endif
11264 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
11265 #if defined(MBEDTLS_SHA256_C)
11266 #if defined(MBEDTLS_USE_PSA_CRYPTO)
11267     psa_hash_abort( &handshake->fin_sha256_psa );
11268 #else
11269     mbedtls_sha256_free(   &handshake->fin_sha256    );
11270 #endif
11271 #endif
11272 #if defined(MBEDTLS_SHA512_C)
11273 #if defined(MBEDTLS_USE_PSA_CRYPTO)
11274     psa_hash_abort( &handshake->fin_sha384_psa );
11275 #else
11276     mbedtls_sha512_free(   &handshake->fin_sha512    );
11277 #endif
11278 #endif
11279 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
11280 
11281 #if defined(MBEDTLS_DHM_C)
11282     mbedtls_dhm_free( &handshake->dhm_ctx );
11283 #endif
11284 #if defined(MBEDTLS_ECDH_C)
11285     mbedtls_ecdh_free( &handshake->ecdh_ctx );
11286 #endif
11287 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
11288     mbedtls_ecjpake_free( &handshake->ecjpake_ctx );
11289 #if defined(MBEDTLS_SSL_CLI_C)
11290     mbedtls_free( handshake->ecjpake_cache );
11291     handshake->ecjpake_cache = NULL;
11292     handshake->ecjpake_cache_len = 0;
11293 #endif
11294 #endif
11295 
11296 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
11297     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
11298     /* explicit void pointer cast for buggy MS compiler */
11299     mbedtls_free( (void *) handshake->curves );
11300 #endif
11301 
11302 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
11303     if( handshake->psk != NULL )
11304     {
11305         mbedtls_platform_zeroize( handshake->psk, handshake->psk_len );
11306         mbedtls_free( handshake->psk );
11307     }
11308 #endif
11309 
11310 #if defined(MBEDTLS_X509_CRT_PARSE_C) && \
11311     defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
11312     /*
11313      * Free only the linked list wrapper, not the keys themselves
11314      * since the belong to the SNI callback
11315      */
11316     if( handshake->sni_key_cert != NULL )
11317     {
11318         mbedtls_ssl_key_cert *cur = handshake->sni_key_cert, *next;
11319 
11320         while( cur != NULL )
11321         {
11322             next = cur->next;
11323             mbedtls_free( cur );
11324             cur = next;
11325         }
11326     }
11327 #endif /* MBEDTLS_X509_CRT_PARSE_C && MBEDTLS_SSL_SERVER_NAME_INDICATION */
11328 
11329 #if defined(MBEDTLS_SSL__ECP_RESTARTABLE)
11330     mbedtls_x509_crt_restart_free( &handshake->ecrs_ctx );
11331     if( handshake->ecrs_peer_cert != NULL )
11332     {
11333         mbedtls_x509_crt_free( handshake->ecrs_peer_cert );
11334         mbedtls_free( handshake->ecrs_peer_cert );
11335     }
11336 #endif
11337 
11338 #if defined(MBEDTLS_X509_CRT_PARSE_C) &&        \
11339     !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
11340     mbedtls_pk_free( &handshake->peer_pubkey );
11341 #endif /* MBEDTLS_X509_CRT_PARSE_C && !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
11342 
11343 #if defined(MBEDTLS_SSL_PROTO_DTLS)
11344     mbedtls_free( handshake->verify_cookie );
11345     ssl_flight_free( handshake->flight );
11346     ssl_buffering_free( ssl );
11347 #endif
11348 
11349 #if defined(MBEDTLS_ECDH_C) &&                  \
11350     defined(MBEDTLS_USE_PSA_CRYPTO)
11351     psa_destroy_key( handshake->ecdh_psa_privkey );
11352 #endif /* MBEDTLS_ECDH_C && MBEDTLS_USE_PSA_CRYPTO */
11353 
11354     mbedtls_platform_zeroize( handshake,
11355                               sizeof( mbedtls_ssl_handshake_params ) );
11356 }
11357 
11358 void mbedtls_ssl_session_free( mbedtls_ssl_session *session )
11359 {
11360     if( session == NULL )
11361         return;
11362 
11363 #if defined(MBEDTLS_X509_CRT_PARSE_C)
11364     ssl_clear_peer_cert( session );
11365 #endif
11366 
11367 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
11368     mbedtls_free( session->ticket );
11369 #endif
11370 
11371     mbedtls_platform_zeroize( session, sizeof( mbedtls_ssl_session ) );
11372 }
11373 
11374 #if defined(MBEDTLS_SSL_CONTEXT_SERIALIZATION)
11375 
11376 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
11377 #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_CONNECTION_ID 1u
11378 #else
11379 #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_CONNECTION_ID 0u
11380 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
11381 
11382 #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT)
11383 #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_BADMAC_LIMIT 1u
11384 #else
11385 #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_BADMAC_LIMIT 0u
11386 #endif /* MBEDTLS_SSL_DTLS_BADMAC_LIMIT */
11387 
11388 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
11389 #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_ANTI_REPLAY 1u
11390 #else
11391 #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_ANTI_REPLAY 0u
11392 #endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */
11393 
11394 #if defined(MBEDTLS_SSL_ALPN)
11395 #define SSL_SERIALIZED_CONTEXT_CONFIG_ALPN 1u
11396 #else
11397 #define SSL_SERIALIZED_CONTEXT_CONFIG_ALPN 0u
11398 #endif /* MBEDTLS_SSL_ALPN */
11399 
11400 #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_CONNECTION_ID_BIT    0
11401 #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_BADMAC_LIMIT_BIT     1
11402 #define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_ANTI_REPLAY_BIT      2
11403 #define SSL_SERIALIZED_CONTEXT_CONFIG_ALPN_BIT                  3
11404 
11405 #define SSL_SERIALIZED_CONTEXT_CONFIG_BITFLAG   \
11406     ( (uint32_t) (                              \
11407         ( SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_CONNECTION_ID     << SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_CONNECTION_ID_BIT     ) | \
11408         ( SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_BADMAC_LIMIT      << SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_BADMAC_LIMIT_BIT      ) | \
11409         ( SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_ANTI_REPLAY       << SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_ANTI_REPLAY_BIT       ) | \
11410         ( SSL_SERIALIZED_CONTEXT_CONFIG_ALPN                   << SSL_SERIALIZED_CONTEXT_CONFIG_ALPN_BIT                   ) | \
11411         0u ) )
11412 
11413 static unsigned char ssl_serialized_context_header[] = {
11414     MBEDTLS_VERSION_MAJOR,
11415     MBEDTLS_VERSION_MINOR,
11416     MBEDTLS_VERSION_PATCH,
11417     ( SSL_SERIALIZED_SESSION_CONFIG_BITFLAG >> 8 ) & 0xFF,
11418     ( SSL_SERIALIZED_SESSION_CONFIG_BITFLAG >> 0 ) & 0xFF,
11419     ( SSL_SERIALIZED_CONTEXT_CONFIG_BITFLAG >> 16 ) & 0xFF,
11420     ( SSL_SERIALIZED_CONTEXT_CONFIG_BITFLAG >>  8 ) & 0xFF,
11421     ( SSL_SERIALIZED_CONTEXT_CONFIG_BITFLAG >>  0 ) & 0xFF,
11422 };
11423 
11424 /*
11425  * Serialize a full SSL context
11426  *
11427  * The format of the serialized data is:
11428  * (in the presentation language of TLS, RFC 8446 section 3)
11429  *
11430  *  // header
11431  *  opaque mbedtls_version[3];   // major, minor, patch
11432  *  opaque context_format[5];    // version-specific field determining
11433  *                               // the format of the remaining
11434  *                               // serialized data.
11435  *  Note: When updating the format, remember to keep these
11436  *        version+format bytes. (We may make their size part of the API.)
11437  *
11438  *  // session sub-structure
11439  *  opaque session<1..2^32-1>;  // see mbedtls_ssl_session_save()
11440  *  // transform sub-structure
11441  *  uint8 random[64];           // ServerHello.random+ClientHello.random
11442  *  uint8 in_cid<0..2^8-1>      // Connection ID: expected incoming value
11443  *  uint8 out_cid<0..2^8-1>     // Connection ID: outgoing value to use
11444  *  // fields from ssl_context
11445  *  uint32 badmac_seen;         // DTLS: number of records with failing MAC
11446  *  uint64 in_window_top;       // DTLS: last validated record seq_num
11447  *  uint64 in_window;           // DTLS: bitmask for replay protection
11448  *  uint8 disable_datagram_packing; // DTLS: only one record per datagram
11449  *  uint64 cur_out_ctr;         // Record layer: outgoing sequence number
11450  *  uint16 mtu;                 // DTLS: path mtu (max outgoing fragment size)
11451  *  uint8 alpn_chosen<0..2^8-1> // ALPN: negotiated application protocol
11452  *
11453  * Note that many fields of the ssl_context or sub-structures are not
11454  * serialized, as they fall in one of the following categories:
11455  *
11456  *  1. forced value (eg in_left must be 0)
11457  *  2. pointer to dynamically-allocated memory (eg session, transform)
11458  *  3. value can be re-derived from other data (eg session keys from MS)
11459  *  4. value was temporary (eg content of input buffer)
11460  *  5. value will be provided by the user again (eg I/O callbacks and context)
11461  */
11462 int mbedtls_ssl_context_save( mbedtls_ssl_context *ssl,
11463                               unsigned char *buf,
11464                               size_t buf_len,
11465                               size_t *olen )
11466 {
11467     unsigned char *p = buf;
11468     size_t used = 0;
11469     size_t session_len;
11470     int ret = 0;
11471 
11472     /*
11473      * Enforce usage restrictions, see "return BAD_INPUT_DATA" in
11474      * this function's documentation.
11475      *
11476      * These are due to assumptions/limitations in the implementation. Some of
11477      * them are likely to stay (no handshake in progress) some might go away
11478      * (only DTLS) but are currently used to simplify the implementation.
11479      */
11480     /* The initial handshake must be over */
11481     if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
11482     {
11483         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Initial handshake isn't over" ) );
11484         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
11485     }
11486     if( ssl->handshake != NULL )
11487     {
11488         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Handshake isn't completed" ) );
11489         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
11490     }
11491     /* Double-check that sub-structures are indeed ready */
11492     if( ssl->transform == NULL || ssl->session == NULL )
11493     {
11494         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Serialised structures aren't ready" ) );
11495         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
11496     }
11497     /* There must be no pending incoming or outgoing data */
11498     if( mbedtls_ssl_check_pending( ssl ) != 0 )
11499     {
11500         MBEDTLS_SSL_DEBUG_MSG( 1, ( "There is pending incoming data" ) );
11501         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
11502     }
11503     if( ssl->out_left != 0 )
11504     {
11505         MBEDTLS_SSL_DEBUG_MSG( 1, ( "There is pending outgoing data" ) );
11506         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
11507     }
11508     /* Protocol must be DLTS, not TLS */
11509     if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM )
11510     {
11511         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Only DTLS is supported" ) );
11512         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
11513     }
11514     /* Version must be 1.2 */
11515     if( ssl->major_ver != MBEDTLS_SSL_MAJOR_VERSION_3 )
11516     {
11517         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Only version 1.2 supported" ) );
11518         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
11519     }
11520     if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
11521     {
11522         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Only version 1.2 supported" ) );
11523         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
11524     }
11525     /* We must be using an AEAD ciphersuite */
11526     if( mbedtls_ssl_transform_uses_aead( ssl->transform ) != 1 )
11527     {
11528         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Only AEAD ciphersuites supported" ) );
11529         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
11530     }
11531     /* Renegotiation must not be enabled */
11532 #if defined(MBEDTLS_SSL_RENEGOTIATION)
11533     if( ssl->conf->disable_renegotiation != MBEDTLS_SSL_RENEGOTIATION_DISABLED )
11534     {
11535         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Renegotiation must not be enabled" ) );
11536         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
11537     }
11538 #endif
11539 
11540     /*
11541      * Version and format identifier
11542      */
11543     used += sizeof( ssl_serialized_context_header );
11544 
11545     if( used <= buf_len )
11546     {
11547         memcpy( p, ssl_serialized_context_header,
11548                 sizeof( ssl_serialized_context_header ) );
11549         p += sizeof( ssl_serialized_context_header );
11550     }
11551 
11552     /*
11553      * Session (length + data)
11554      */
11555     ret = ssl_session_save( ssl->session, 1, NULL, 0, &session_len );
11556     if( ret != MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL )
11557         return( ret );
11558 
11559     used += 4 + session_len;
11560     if( used <= buf_len )
11561     {
11562         *p++ = (unsigned char)( ( session_len >> 24 ) & 0xFF );
11563         *p++ = (unsigned char)( ( session_len >> 16 ) & 0xFF );
11564         *p++ = (unsigned char)( ( session_len >>  8 ) & 0xFF );
11565         *p++ = (unsigned char)( ( session_len       ) & 0xFF );
11566 
11567         ret = ssl_session_save( ssl->session, 1,
11568                                 p, session_len, &session_len );
11569         if( ret != 0 )
11570             return( ret );
11571 
11572         p += session_len;
11573     }
11574 
11575     /*
11576      * Transform
11577      */
11578     used += sizeof( ssl->transform->randbytes );
11579     if( used <= buf_len )
11580     {
11581         memcpy( p, ssl->transform->randbytes,
11582            sizeof( ssl->transform->randbytes ) );
11583         p += sizeof( ssl->transform->randbytes );
11584     }
11585 
11586 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
11587     used += 2 + ssl->transform->in_cid_len + ssl->transform->out_cid_len;
11588     if( used <= buf_len )
11589     {
11590         *p++ = ssl->transform->in_cid_len;
11591         memcpy( p, ssl->transform->in_cid, ssl->transform->in_cid_len );
11592         p += ssl->transform->in_cid_len;
11593 
11594         *p++ = ssl->transform->out_cid_len;
11595         memcpy( p, ssl->transform->out_cid, ssl->transform->out_cid_len );
11596         p += ssl->transform->out_cid_len;
11597     }
11598 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
11599 
11600     /*
11601      * Saved fields from top-level ssl_context structure
11602      */
11603 #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT)
11604     used += 4;
11605     if( used <= buf_len )
11606     {
11607         *p++ = (unsigned char)( ( ssl->badmac_seen >> 24 ) & 0xFF );
11608         *p++ = (unsigned char)( ( ssl->badmac_seen >> 16 ) & 0xFF );
11609         *p++ = (unsigned char)( ( ssl->badmac_seen >>  8 ) & 0xFF );
11610         *p++ = (unsigned char)( ( ssl->badmac_seen       ) & 0xFF );
11611     }
11612 #endif /* MBEDTLS_SSL_DTLS_BADMAC_LIMIT */
11613 
11614 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
11615     used += 16;
11616     if( used <= buf_len )
11617     {
11618         *p++ = (unsigned char)( ( ssl->in_window_top >> 56 ) & 0xFF );
11619         *p++ = (unsigned char)( ( ssl->in_window_top >> 48 ) & 0xFF );
11620         *p++ = (unsigned char)( ( ssl->in_window_top >> 40 ) & 0xFF );
11621         *p++ = (unsigned char)( ( ssl->in_window_top >> 32 ) & 0xFF );
11622         *p++ = (unsigned char)( ( ssl->in_window_top >> 24 ) & 0xFF );
11623         *p++ = (unsigned char)( ( ssl->in_window_top >> 16 ) & 0xFF );
11624         *p++ = (unsigned char)( ( ssl->in_window_top >>  8 ) & 0xFF );
11625         *p++ = (unsigned char)( ( ssl->in_window_top       ) & 0xFF );
11626 
11627         *p++ = (unsigned char)( ( ssl->in_window >> 56 ) & 0xFF );
11628         *p++ = (unsigned char)( ( ssl->in_window >> 48 ) & 0xFF );
11629         *p++ = (unsigned char)( ( ssl->in_window >> 40 ) & 0xFF );
11630         *p++ = (unsigned char)( ( ssl->in_window >> 32 ) & 0xFF );
11631         *p++ = (unsigned char)( ( ssl->in_window >> 24 ) & 0xFF );
11632         *p++ = (unsigned char)( ( ssl->in_window >> 16 ) & 0xFF );
11633         *p++ = (unsigned char)( ( ssl->in_window >>  8 ) & 0xFF );
11634         *p++ = (unsigned char)( ( ssl->in_window       ) & 0xFF );
11635     }
11636 #endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */
11637 
11638 #if defined(MBEDTLS_SSL_PROTO_DTLS)
11639     used += 1;
11640     if( used <= buf_len )
11641     {
11642         *p++ = ssl->disable_datagram_packing;
11643     }
11644 #endif /* MBEDTLS_SSL_PROTO_DTLS */
11645 
11646     used += 8;
11647     if( used <= buf_len )
11648     {
11649         memcpy( p, ssl->cur_out_ctr, 8 );
11650         p += 8;
11651     }
11652 
11653 #if defined(MBEDTLS_SSL_PROTO_DTLS)
11654     used += 2;
11655     if( used <= buf_len )
11656     {
11657         *p++ = (unsigned char)( ( ssl->mtu >>  8 ) & 0xFF );
11658         *p++ = (unsigned char)( ( ssl->mtu       ) & 0xFF );
11659     }
11660 #endif /* MBEDTLS_SSL_PROTO_DTLS */
11661 
11662 #if defined(MBEDTLS_SSL_ALPN)
11663     {
11664         const uint8_t alpn_len = ssl->alpn_chosen
11665                                ? (uint8_t) strlen( ssl->alpn_chosen )
11666                                : 0;
11667 
11668         used += 1 + alpn_len;
11669         if( used <= buf_len )
11670         {
11671             *p++ = alpn_len;
11672 
11673             if( ssl->alpn_chosen != NULL )
11674             {
11675                 memcpy( p, ssl->alpn_chosen, alpn_len );
11676                 p += alpn_len;
11677             }
11678         }
11679     }
11680 #endif /* MBEDTLS_SSL_ALPN */
11681 
11682     /*
11683      * Done
11684      */
11685     *olen = used;
11686 
11687     if( used > buf_len )
11688         return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
11689 
11690     MBEDTLS_SSL_DEBUG_BUF( 4, "saved context", buf, used );
11691 
11692     return( ssl_session_reset_int( ssl, 0 ) );
11693 }
11694 
11695 /*
11696  * Helper to get TLS 1.2 PRF from ciphersuite
11697  * (Duplicates bits of logic from ssl_set_handshake_prfs().)
11698  */
11699 typedef int (*tls_prf_fn)( const unsigned char *secret, size_t slen,
11700                            const char *label,
11701                            const unsigned char *random, size_t rlen,
11702                            unsigned char *dstbuf, size_t dlen );
11703 static tls_prf_fn ssl_tls12prf_from_cs( int ciphersuite_id )
11704 {
11705 #if defined(MBEDTLS_SHA512_C)
11706     const mbedtls_ssl_ciphersuite_t * const ciphersuite_info =
11707          mbedtls_ssl_ciphersuite_from_id( ciphersuite_id );
11708 
11709     if( ciphersuite_info->mac == MBEDTLS_MD_SHA384 )
11710         return( tls_prf_sha384 );
11711 #else
11712     (void) ciphersuite_id;
11713 #endif
11714     return( tls_prf_sha256 );
11715 }
11716 
11717 /*
11718  * Deserialize context, see mbedtls_ssl_context_save() for format.
11719  *
11720  * This internal version is wrapped by a public function that cleans up in
11721  * case of error.
11722  */
11723 static int ssl_context_load( mbedtls_ssl_context *ssl,
11724                              const unsigned char *buf,
11725                              size_t len )
11726 {
11727     const unsigned char *p = buf;
11728     const unsigned char * const end = buf + len;
11729     size_t session_len;
11730     int ret;
11731 
11732     /*
11733      * The context should have been freshly setup or reset.
11734      * Give the user an error in case of obvious misuse.
11735      * (Checking session is useful because it won't be NULL if we're
11736      * renegotiating, or if the user mistakenly loaded a session first.)
11737      */
11738     if( ssl->state != MBEDTLS_SSL_HELLO_REQUEST ||
11739         ssl->session != NULL )
11740     {
11741         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
11742     }
11743 
11744     /*
11745      * We can't check that the config matches the initial one, but we can at
11746      * least check it matches the requirements for serializing.
11747      */
11748     if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM ||
11749         ssl->conf->max_major_ver < MBEDTLS_SSL_MAJOR_VERSION_3 ||
11750         ssl->conf->min_major_ver > MBEDTLS_SSL_MAJOR_VERSION_3 ||
11751         ssl->conf->max_minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 ||
11752         ssl->conf->min_minor_ver > MBEDTLS_SSL_MINOR_VERSION_3 ||
11753 #if defined(MBEDTLS_SSL_RENEGOTIATION)
11754         ssl->conf->disable_renegotiation != MBEDTLS_SSL_RENEGOTIATION_DISABLED ||
11755 #endif
11756         0 )
11757     {
11758         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
11759     }
11760 
11761     MBEDTLS_SSL_DEBUG_BUF( 4, "context to load", buf, len );
11762 
11763     /*
11764      * Check version identifier
11765      */
11766     if( (size_t)( end - p ) < sizeof( ssl_serialized_context_header ) )
11767         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
11768 
11769     if( memcmp( p, ssl_serialized_context_header,
11770                 sizeof( ssl_serialized_context_header ) ) != 0 )
11771     {
11772         return( MBEDTLS_ERR_SSL_VERSION_MISMATCH );
11773     }
11774     p += sizeof( ssl_serialized_context_header );
11775 
11776     /*
11777      * Session
11778      */
11779     if( (size_t)( end - p ) < 4 )
11780         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
11781 
11782     session_len = ( (size_t) p[0] << 24 ) |
11783                   ( (size_t) p[1] << 16 ) |
11784                   ( (size_t) p[2] <<  8 ) |
11785                   ( (size_t) p[3]       );
11786     p += 4;
11787 
11788     /* This has been allocated by ssl_handshake_init(), called by
11789      * by either ssl_session_reset_int() or mbedtls_ssl_setup(). */
11790     ssl->session = ssl->session_negotiate;
11791     ssl->session_in = ssl->session;
11792     ssl->session_out = ssl->session;
11793     ssl->session_negotiate = NULL;
11794 
11795     if( (size_t)( end - p ) < session_len )
11796         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
11797 
11798     ret = ssl_session_load( ssl->session, 1, p, session_len );
11799     if( ret != 0 )
11800     {
11801         mbedtls_ssl_session_free( ssl->session );
11802         return( ret );
11803     }
11804 
11805     p += session_len;
11806 
11807     /*
11808      * Transform
11809      */
11810 
11811     /* This has been allocated by ssl_handshake_init(), called by
11812      * by either ssl_session_reset_int() or mbedtls_ssl_setup(). */
11813     ssl->transform = ssl->transform_negotiate;
11814     ssl->transform_in = ssl->transform;
11815     ssl->transform_out = ssl->transform;
11816     ssl->transform_negotiate = NULL;
11817 
11818     /* Read random bytes and populate structure */
11819     if( (size_t)( end - p ) < sizeof( ssl->transform->randbytes ) )
11820         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
11821 
11822     ret = ssl_populate_transform( ssl->transform,
11823                   ssl->session->ciphersuite,
11824                   ssl->session->master,
11825 #if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
11826 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
11827                   ssl->session->encrypt_then_mac,
11828 #endif
11829 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
11830                   ssl->session->trunc_hmac,
11831 #endif
11832 #endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */
11833 #if defined(MBEDTLS_ZLIB_SUPPORT)
11834                   ssl->session->compression,
11835 #endif
11836                   ssl_tls12prf_from_cs( ssl->session->ciphersuite ),
11837                   p, /* currently pointing to randbytes */
11838                   MBEDTLS_SSL_MINOR_VERSION_3, /* (D)TLS 1.2 is forced */
11839                   ssl->conf->endpoint,
11840                   ssl );
11841     if( ret != 0 )
11842         return( ret );
11843 
11844     p += sizeof( ssl->transform->randbytes );
11845 
11846 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
11847     /* Read connection IDs and store them */
11848     if( (size_t)( end - p ) < 1 )
11849         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
11850 
11851     ssl->transform->in_cid_len = *p++;
11852 
11853     if( (size_t)( end - p ) < ssl->transform->in_cid_len + 1u )
11854         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
11855 
11856     memcpy( ssl->transform->in_cid, p, ssl->transform->in_cid_len );
11857     p += ssl->transform->in_cid_len;
11858 
11859     ssl->transform->out_cid_len = *p++;
11860 
11861     if( (size_t)( end - p ) < ssl->transform->out_cid_len )
11862         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
11863 
11864     memcpy( ssl->transform->out_cid, p, ssl->transform->out_cid_len );
11865     p += ssl->transform->out_cid_len;
11866 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
11867 
11868     /*
11869      * Saved fields from top-level ssl_context structure
11870      */
11871 #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT)
11872     if( (size_t)( end - p ) < 4 )
11873         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
11874 
11875     ssl->badmac_seen = ( (uint32_t) p[0] << 24 ) |
11876                        ( (uint32_t) p[1] << 16 ) |
11877                        ( (uint32_t) p[2] <<  8 ) |
11878                        ( (uint32_t) p[3]       );
11879     p += 4;
11880 #endif /* MBEDTLS_SSL_DTLS_BADMAC_LIMIT */
11881 
11882 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
11883     if( (size_t)( end - p ) < 16 )
11884         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
11885 
11886     ssl->in_window_top = ( (uint64_t) p[0] << 56 ) |
11887                          ( (uint64_t) p[1] << 48 ) |
11888                          ( (uint64_t) p[2] << 40 ) |
11889                          ( (uint64_t) p[3] << 32 ) |
11890                          ( (uint64_t) p[4] << 24 ) |
11891                          ( (uint64_t) p[5] << 16 ) |
11892                          ( (uint64_t) p[6] <<  8 ) |
11893                          ( (uint64_t) p[7]       );
11894     p += 8;
11895 
11896     ssl->in_window = ( (uint64_t) p[0] << 56 ) |
11897                      ( (uint64_t) p[1] << 48 ) |
11898                      ( (uint64_t) p[2] << 40 ) |
11899                      ( (uint64_t) p[3] << 32 ) |
11900                      ( (uint64_t) p[4] << 24 ) |
11901                      ( (uint64_t) p[5] << 16 ) |
11902                      ( (uint64_t) p[6] <<  8 ) |
11903                      ( (uint64_t) p[7]       );
11904     p += 8;
11905 #endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */
11906 
11907 #if defined(MBEDTLS_SSL_PROTO_DTLS)
11908     if( (size_t)( end - p ) < 1 )
11909         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
11910 
11911     ssl->disable_datagram_packing = *p++;
11912 #endif /* MBEDTLS_SSL_PROTO_DTLS */
11913 
11914     if( (size_t)( end - p ) < 8 )
11915         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
11916 
11917     memcpy( ssl->cur_out_ctr, p, 8 );
11918     p += 8;
11919 
11920 #if defined(MBEDTLS_SSL_PROTO_DTLS)
11921     if( (size_t)( end - p ) < 2 )
11922         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
11923 
11924     ssl->mtu = ( p[0] << 8 ) | p[1];
11925     p += 2;
11926 #endif /* MBEDTLS_SSL_PROTO_DTLS */
11927 
11928 #if defined(MBEDTLS_SSL_ALPN)
11929     {
11930         uint8_t alpn_len;
11931         const char **cur;
11932 
11933         if( (size_t)( end - p ) < 1 )
11934             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
11935 
11936         alpn_len = *p++;
11937 
11938         if( alpn_len != 0 && ssl->conf->alpn_list != NULL )
11939         {
11940             /* alpn_chosen should point to an item in the configured list */
11941             for( cur = ssl->conf->alpn_list; *cur != NULL; cur++ )
11942             {
11943                 if( strlen( *cur ) == alpn_len &&
11944                     memcmp( p, cur, alpn_len ) == 0 )
11945                 {
11946                     ssl->alpn_chosen = *cur;
11947                     break;
11948                 }
11949             }
11950         }
11951 
11952         /* can only happen on conf mismatch */
11953         if( alpn_len != 0 && ssl->alpn_chosen == NULL )
11954             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
11955 
11956         p += alpn_len;
11957     }
11958 #endif /* MBEDTLS_SSL_ALPN */
11959 
11960     /*
11961      * Forced fields from top-level ssl_context structure
11962      *
11963      * Most of them already set to the correct value by mbedtls_ssl_init() and
11964      * mbedtls_ssl_reset(), so we only need to set the remaining ones.
11965      */
11966     ssl->state = MBEDTLS_SSL_HANDSHAKE_OVER;
11967 
11968     ssl->major_ver = MBEDTLS_SSL_MAJOR_VERSION_3;
11969     ssl->minor_ver = MBEDTLS_SSL_MINOR_VERSION_3;
11970 
11971     /* Adjust pointers for header fields of outgoing records to
11972      * the given transform, accounting for explicit IV and CID. */
11973     ssl_update_out_pointers( ssl, ssl->transform );
11974 
11975 #if defined(MBEDTLS_SSL_PROTO_DTLS)
11976     ssl->in_epoch = 1;
11977 #endif
11978 
11979     /* mbedtls_ssl_reset() leaves the handshake sub-structure allocated,
11980      * which we don't want - otherwise we'd end up freeing the wrong transform
11981      * by calling ssl_handshake_wrapup_free_hs_transform() inappropriately. */
11982     if( ssl->handshake != NULL )
11983     {
11984         mbedtls_ssl_handshake_free( ssl );
11985         mbedtls_free( ssl->handshake );
11986         ssl->handshake = NULL;
11987     }
11988 
11989     /*
11990      * Done - should have consumed entire buffer
11991      */
11992     if( p != end )
11993         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
11994 
11995     return( 0 );
11996 }
11997 
11998 /*
11999  * Deserialize context: public wrapper for error cleaning
12000  */
12001 int mbedtls_ssl_context_load( mbedtls_ssl_context *context,
12002                               const unsigned char *buf,
12003                               size_t len )
12004 {
12005     int ret = ssl_context_load( context, buf, len );
12006 
12007     if( ret != 0 )
12008         mbedtls_ssl_free( context );
12009 
12010     return( ret );
12011 }
12012 #endif /* MBEDTLS_SSL_CONTEXT_SERIALIZATION */
12013 
12014 /*
12015  * Free an SSL context
12016  */
12017 void mbedtls_ssl_free( mbedtls_ssl_context *ssl )
12018 {
12019     if( ssl == NULL )
12020         return;
12021 
12022     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> free" ) );
12023 
12024     if( ssl->out_buf != NULL )
12025     {
12026         mbedtls_platform_zeroize( ssl->out_buf, MBEDTLS_SSL_OUT_BUFFER_LEN );
12027         mbedtls_free( ssl->out_buf );
12028     }
12029 
12030     if( ssl->in_buf != NULL )
12031     {
12032         mbedtls_platform_zeroize( ssl->in_buf, MBEDTLS_SSL_IN_BUFFER_LEN );
12033         mbedtls_free( ssl->in_buf );
12034     }
12035 
12036 #if defined(MBEDTLS_ZLIB_SUPPORT)
12037     if( ssl->compress_buf != NULL )
12038     {
12039         mbedtls_platform_zeroize( ssl->compress_buf, MBEDTLS_SSL_COMPRESS_BUFFER_LEN );
12040         mbedtls_free( ssl->compress_buf );
12041     }
12042 #endif
12043 
12044     if( ssl->transform )
12045     {
12046         mbedtls_ssl_transform_free( ssl->transform );
12047         mbedtls_free( ssl->transform );
12048     }
12049 
12050     if( ssl->handshake )
12051     {
12052         mbedtls_ssl_handshake_free( ssl );
12053         mbedtls_ssl_transform_free( ssl->transform_negotiate );
12054         mbedtls_ssl_session_free( ssl->session_negotiate );
12055 
12056         mbedtls_free( ssl->handshake );
12057         mbedtls_free( ssl->transform_negotiate );
12058         mbedtls_free( ssl->session_negotiate );
12059     }
12060 
12061     if( ssl->session )
12062     {
12063         mbedtls_ssl_session_free( ssl->session );
12064         mbedtls_free( ssl->session );
12065     }
12066 
12067 #if defined(MBEDTLS_X509_CRT_PARSE_C)
12068     if( ssl->hostname != NULL )
12069     {
12070         mbedtls_platform_zeroize( ssl->hostname, strlen( ssl->hostname ) );
12071         mbedtls_free( ssl->hostname );
12072     }
12073 #endif
12074 
12075 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
12076     if( mbedtls_ssl_hw_record_finish != NULL )
12077     {
12078         MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_finish()" ) );
12079         mbedtls_ssl_hw_record_finish( ssl );
12080     }
12081 #endif
12082 
12083 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
12084     mbedtls_free( ssl->cli_id );
12085 #endif
12086 
12087     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= free" ) );
12088 
12089     /* Actually clear after last debug message */
12090     mbedtls_platform_zeroize( ssl, sizeof( mbedtls_ssl_context ) );
12091 }
12092 
12093 /*
12094  * Initialze mbedtls_ssl_config
12095  */
12096 void mbedtls_ssl_config_init( mbedtls_ssl_config *conf )
12097 {
12098     memset( conf, 0, sizeof( mbedtls_ssl_config ) );
12099 }
12100 
12101 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
12102 static int ssl_preset_default_hashes[] = {
12103 #if defined(MBEDTLS_SHA512_C)
12104     MBEDTLS_MD_SHA512,
12105     MBEDTLS_MD_SHA384,
12106 #endif
12107 #if defined(MBEDTLS_SHA256_C)
12108     MBEDTLS_MD_SHA256,
12109     MBEDTLS_MD_SHA224,
12110 #endif
12111 #if defined(MBEDTLS_SHA1_C) && defined(MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_KEY_EXCHANGE)
12112     MBEDTLS_MD_SHA1,
12113 #endif
12114     MBEDTLS_MD_NONE
12115 };
12116 #endif
12117 
12118 static int ssl_preset_suiteb_ciphersuites[] = {
12119     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
12120     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
12121     0
12122 };
12123 
12124 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
12125 static int ssl_preset_suiteb_hashes[] = {
12126     MBEDTLS_MD_SHA256,
12127     MBEDTLS_MD_SHA384,
12128     MBEDTLS_MD_NONE
12129 };
12130 #endif
12131 
12132 #if defined(MBEDTLS_ECP_C)
12133 static mbedtls_ecp_group_id ssl_preset_suiteb_curves[] = {
12134 #if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED)
12135     MBEDTLS_ECP_DP_SECP256R1,
12136 #endif
12137 #if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)
12138     MBEDTLS_ECP_DP_SECP384R1,
12139 #endif
12140     MBEDTLS_ECP_DP_NONE
12141 };
12142 #endif
12143 
12144 /*
12145  * Load default in mbedtls_ssl_config
12146  */
12147 int mbedtls_ssl_config_defaults( mbedtls_ssl_config *conf,
12148                                  int endpoint, int transport, int preset )
12149 {
12150 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
12151     int ret;
12152 #endif
12153 
12154     /* Use the functions here so that they are covered in tests,
12155      * but otherwise access member directly for efficiency */
12156     mbedtls_ssl_conf_endpoint( conf, endpoint );
12157     mbedtls_ssl_conf_transport( conf, transport );
12158 
12159     /*
12160      * Things that are common to all presets
12161      */
12162 #if defined(MBEDTLS_SSL_CLI_C)
12163     if( endpoint == MBEDTLS_SSL_IS_CLIENT )
12164     {
12165         conf->authmode  = MBEDTLS_SSL_VERIFY_REQUIRED;
12166 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
12167         conf->session_tickets  = MBEDTLS_SSL_SESSION_TICKETS_ENABLED;
12168 #endif
12169     }
12170 #endif
12171 
12172 #if defined(MBEDTLS_ARC4_C)
12173     conf->arc4_disabled  = MBEDTLS_SSL_ARC4_DISABLED;
12174 #endif
12175 
12176 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
12177     conf->encrypt_then_mac  = MBEDTLS_SSL_ETM_ENABLED;
12178 #endif
12179 
12180 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
12181     conf->extended_ms  = MBEDTLS_SSL_EXTENDED_MS_ENABLED;
12182 #endif
12183 
12184 #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
12185     conf->cbc_record_splitting  = MBEDTLS_SSL_CBC_RECORD_SPLITTING_ENABLED;
12186 #endif
12187 
12188 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
12189     conf->f_cookie_write = ssl_cookie_write_dummy;
12190     conf->f_cookie_check = ssl_cookie_check_dummy;
12191 #endif
12192 
12193 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
12194     conf->anti_replay  = MBEDTLS_SSL_ANTI_REPLAY_ENABLED;
12195 #endif
12196 
12197 #if defined(MBEDTLS_SSL_SRV_C)
12198     conf->cert_req_ca_list  = MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED;
12199 #endif
12200 
12201 #if defined(MBEDTLS_SSL_PROTO_DTLS)
12202     conf->hs_timeout_min  = MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MIN;
12203     conf->hs_timeout_max  = MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MAX;
12204 #endif
12205 
12206 #if defined(MBEDTLS_SSL_RENEGOTIATION)
12207     conf->renego_max_records  = MBEDTLS_SSL_RENEGO_MAX_RECORDS_DEFAULT;
12208     memset( conf->renego_period ,     0x00, 2 );
12209     memset( conf->renego_period  + 2, 0xFF, 6 );
12210 #endif
12211 
12212 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
12213             if( endpoint == MBEDTLS_SSL_IS_SERVER )
12214             {
12215                 const unsigned char dhm_p[] =
12216                     MBEDTLS_DHM_RFC3526_MODP_2048_P_BIN;
12217                 const unsigned char dhm_g[] =
12218                     MBEDTLS_DHM_RFC3526_MODP_2048_G_BIN;
12219 
12220                 if ( ( ret = mbedtls_ssl_conf_dh_param_bin( conf,
12221                                                dhm_p, sizeof( dhm_p ),
12222                                                dhm_g, sizeof( dhm_g ) ) ) != 0 )
12223                 {
12224                     return( ret );
12225                 }
12226             }
12227 #endif
12228 
12229     /*
12230      * Preset-specific defaults
12231      */
12232     switch( preset )
12233     {
12234         /*
12235          * NSA Suite B
12236          */
12237         case MBEDTLS_SSL_PRESET_SUITEB:
12238             conf->min_major_ver  = MBEDTLS_SSL_MAJOR_VERSION_3;
12239             conf->min_minor_ver  = MBEDTLS_SSL_MINOR_VERSION_3; /* TLS 1.2 */
12240             conf->max_major_ver  = MBEDTLS_SSL_MAX_MAJOR_VERSION;
12241             conf->max_minor_ver  = MBEDTLS_SSL_MAX_MINOR_VERSION;
12242 
12243             conf->ciphersuite_list [MBEDTLS_SSL_MINOR_VERSION_0] =
12244             conf->ciphersuite_list [MBEDTLS_SSL_MINOR_VERSION_1] =
12245             conf->ciphersuite_list [MBEDTLS_SSL_MINOR_VERSION_2] =
12246             conf->ciphersuite_list [MBEDTLS_SSL_MINOR_VERSION_3] =
12247                                    ssl_preset_suiteb_ciphersuites;
12248 
12249 #if defined(MBEDTLS_X509_CRT_PARSE_C)
12250             conf->cert_profile  = &mbedtls_x509_crt_profile_suiteb;
12251 #endif
12252 
12253 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
12254             conf->sig_hashes  = ssl_preset_suiteb_hashes;
12255 #endif
12256 
12257 #if defined(MBEDTLS_ECP_C)
12258             conf->curve_list  = ssl_preset_suiteb_curves;
12259 #endif
12260             break;
12261 
12262         /*
12263          * Default
12264          */
12265         default:
12266             conf->min_major_ver  = ( MBEDTLS_SSL_MIN_MAJOR_VERSION >
12267                                     MBEDTLS_SSL_MIN_VALID_MAJOR_VERSION ) ?
12268                                     MBEDTLS_SSL_MIN_MAJOR_VERSION :
12269                                     MBEDTLS_SSL_MIN_VALID_MAJOR_VERSION;
12270             conf->min_minor_ver  = ( MBEDTLS_SSL_MIN_MINOR_VERSION >
12271                                     MBEDTLS_SSL_MIN_VALID_MINOR_VERSION ) ?
12272                                     MBEDTLS_SSL_MIN_MINOR_VERSION :
12273                                     MBEDTLS_SSL_MIN_VALID_MINOR_VERSION;
12274             conf->max_major_ver  = MBEDTLS_SSL_MAX_MAJOR_VERSION;
12275             conf->max_minor_ver  = MBEDTLS_SSL_MAX_MINOR_VERSION;
12276 
12277 #if defined(MBEDTLS_SSL_PROTO_DTLS)
12278             if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
12279                 conf->min_minor_ver  = MBEDTLS_SSL_MINOR_VERSION_2;
12280 #endif
12281 
12282             conf->ciphersuite_list [MBEDTLS_SSL_MINOR_VERSION_0] =
12283             conf->ciphersuite_list [MBEDTLS_SSL_MINOR_VERSION_1] =
12284             conf->ciphersuite_list [MBEDTLS_SSL_MINOR_VERSION_2] =
12285             conf->ciphersuite_list [MBEDTLS_SSL_MINOR_VERSION_3] =
12286                                    mbedtls_ssl_list_ciphersuites();
12287 
12288 #if defined(MBEDTLS_X509_CRT_PARSE_C)
12289             conf->cert_profile  = &mbedtls_x509_crt_profile_default;
12290 #endif
12291 
12292 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
12293             conf->sig_hashes  = ssl_preset_default_hashes;
12294 #endif
12295 
12296 #if defined(MBEDTLS_ECP_C)
12297             conf->curve_list  = mbedtls_ecp_grp_id_list();
12298 #endif
12299 
12300 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C)
12301             conf->dhm_min_bitlen  = 1024;
12302 #endif
12303     }
12304 
12305     return( 0 );
12306 }
12307 
12308 /*
12309  * Free mbedtls_ssl_config
12310  */
12311 void mbedtls_ssl_config_free( mbedtls_ssl_config *conf )
12312 {
12313 #if defined(MBEDTLS_DHM_C)
12314     mbedtls_mpi_free( &conf->dhm_P  );
12315     mbedtls_mpi_free( &conf->dhm_G  );
12316 #endif
12317 
12318 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
12319     if( conf->psk  != NULL )
12320     {
12321         mbedtls_platform_zeroize( conf->psk , conf->psk_len  );
12322         mbedtls_free( conf->psk  );
12323         conf->psk  = NULL;
12324         conf->psk_len  = 0;
12325     }
12326 
12327     if( conf->psk_identity  != NULL )
12328     {
12329         mbedtls_platform_zeroize( conf->psk_identity , conf->psk_identity_len  );
12330         mbedtls_free( conf->psk_identity  );
12331         conf->psk_identity  = NULL;
12332         conf->psk_identity_len  = 0;
12333     }
12334 #endif
12335 
12336 #if defined(MBEDTLS_X509_CRT_PARSE_C)
12337     ssl_key_cert_free( conf->key_cert  );
12338 #endif
12339 
12340     mbedtls_platform_zeroize( conf, sizeof( mbedtls_ssl_config ) );
12341 }
12342 
12343 #if defined(MBEDTLS_PK_C) && \
12344     ( defined(MBEDTLS_RSA_C) || defined(MBEDTLS_ECDSA_C) )
12345 /*
12346  * Convert between MBEDTLS_PK_XXX and SSL_SIG_XXX
12347  */
12348 unsigned char mbedtls_ssl_sig_from_pk( mbedtls_pk_context *pk )
12349 {
12350 #if defined(MBEDTLS_RSA_C)
12351     if( mbedtls_pk_can_do( pk, MBEDTLS_PK_RSA ) )
12352         return( MBEDTLS_SSL_SIG_RSA );
12353 #endif
12354 #if defined(MBEDTLS_ECDSA_C)
12355     if( mbedtls_pk_can_do( pk, MBEDTLS_PK_ECDSA ) )
12356         return( MBEDTLS_SSL_SIG_ECDSA );
12357 #endif
12358     return( MBEDTLS_SSL_SIG_ANON );
12359 }
12360 
12361 unsigned char mbedtls_ssl_sig_from_pk_alg( mbedtls_pk_type_t type )
12362 {
12363     switch( type ) {
12364         case MBEDTLS_PK_RSA:
12365             return( MBEDTLS_SSL_SIG_RSA );
12366         case MBEDTLS_PK_ECDSA:
12367         case MBEDTLS_PK_ECKEY:
12368             return( MBEDTLS_SSL_SIG_ECDSA );
12369         default:
12370             return( MBEDTLS_SSL_SIG_ANON );
12371     }
12372 }
12373 
12374 mbedtls_pk_type_t mbedtls_ssl_pk_alg_from_sig( unsigned char sig )
12375 {
12376     switch( sig )
12377     {
12378 #if defined(MBEDTLS_RSA_C)
12379         case MBEDTLS_SSL_SIG_RSA:
12380             return( MBEDTLS_PK_RSA );
12381 #endif
12382 #if defined(MBEDTLS_ECDSA_C)
12383         case MBEDTLS_SSL_SIG_ECDSA:
12384             return( MBEDTLS_PK_ECDSA );
12385 #endif
12386         default:
12387             return( MBEDTLS_PK_NONE );
12388     }
12389 }
12390 #endif /* MBEDTLS_PK_C && ( MBEDTLS_RSA_C || MBEDTLS_ECDSA_C ) */
12391 
12392 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
12393     defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
12394 
12395 /* Find an entry in a signature-hash set matching a given hash algorithm. */
12396 mbedtls_md_type_t mbedtls_ssl_sig_hash_set_find( mbedtls_ssl_sig_hash_set_t *set,
12397                                                  mbedtls_pk_type_t sig_alg )
12398 {
12399     switch( sig_alg )
12400     {
12401         case MBEDTLS_PK_RSA:
12402             return( set->rsa );
12403         case MBEDTLS_PK_ECDSA:
12404             return( set->ecdsa );
12405         default:
12406             return( MBEDTLS_MD_NONE );
12407     }
12408 }
12409 
12410 /* Add a signature-hash-pair to a signature-hash set */
12411 void mbedtls_ssl_sig_hash_set_add( mbedtls_ssl_sig_hash_set_t *set,
12412                                    mbedtls_pk_type_t sig_alg,
12413                                    mbedtls_md_type_t md_alg )
12414 {
12415     switch( sig_alg )
12416     {
12417         case MBEDTLS_PK_RSA:
12418             if( set->rsa == MBEDTLS_MD_NONE )
12419                 set->rsa = md_alg;
12420             break;
12421 
12422         case MBEDTLS_PK_ECDSA:
12423             if( set->ecdsa == MBEDTLS_MD_NONE )
12424                 set->ecdsa = md_alg;
12425             break;
12426 
12427         default:
12428             break;
12429     }
12430 }
12431 
12432 /* Allow exactly one hash algorithm for each signature. */
12433 void mbedtls_ssl_sig_hash_set_const_hash( mbedtls_ssl_sig_hash_set_t *set,
12434                                           mbedtls_md_type_t md_alg )
12435 {
12436     set->rsa   = md_alg;
12437     set->ecdsa = md_alg;
12438 }
12439 
12440 #endif /* MBEDTLS_SSL_PROTO_TLS1_2) &&
12441           MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
12442 
12443 /*
12444  * Convert from MBEDTLS_SSL_HASH_XXX to MBEDTLS_MD_XXX
12445  */
12446 mbedtls_md_type_t mbedtls_ssl_md_alg_from_hash( unsigned char hash )
12447 {
12448     switch( hash )
12449     {
12450 #if defined(MBEDTLS_MD5_C)
12451         case MBEDTLS_SSL_HASH_MD5:
12452             return( MBEDTLS_MD_MD5 );
12453 #endif
12454 #if defined(MBEDTLS_SHA1_C)
12455         case MBEDTLS_SSL_HASH_SHA1:
12456             return( MBEDTLS_MD_SHA1 );
12457 #endif
12458 #if defined(MBEDTLS_SHA256_C)
12459         case MBEDTLS_SSL_HASH_SHA224:
12460             return( MBEDTLS_MD_SHA224 );
12461         case MBEDTLS_SSL_HASH_SHA256:
12462             return( MBEDTLS_MD_SHA256 );
12463 #endif
12464 #if defined(MBEDTLS_SHA512_C)
12465         case MBEDTLS_SSL_HASH_SHA384:
12466             return( MBEDTLS_MD_SHA384 );
12467         case MBEDTLS_SSL_HASH_SHA512:
12468             return( MBEDTLS_MD_SHA512 );
12469 #endif
12470         default:
12471             return( MBEDTLS_MD_NONE );
12472     }
12473 }
12474 
12475 /*
12476  * Convert from MBEDTLS_MD_XXX to MBEDTLS_SSL_HASH_XXX
12477  */
12478 unsigned char mbedtls_ssl_hash_from_md_alg( int md )
12479 {
12480     switch( md )
12481     {
12482 #if defined(MBEDTLS_MD5_C)
12483         case MBEDTLS_MD_MD5:
12484             return( MBEDTLS_SSL_HASH_MD5 );
12485 #endif
12486 #if defined(MBEDTLS_SHA1_C)
12487         case MBEDTLS_MD_SHA1:
12488             return( MBEDTLS_SSL_HASH_SHA1 );
12489 #endif
12490 #if defined(MBEDTLS_SHA256_C)
12491         case MBEDTLS_MD_SHA224:
12492             return( MBEDTLS_SSL_HASH_SHA224 );
12493         case MBEDTLS_MD_SHA256:
12494             return( MBEDTLS_SSL_HASH_SHA256 );
12495 #endif
12496 #if defined(MBEDTLS_SHA512_C)
12497         case MBEDTLS_MD_SHA384:
12498             return( MBEDTLS_SSL_HASH_SHA384 );
12499         case MBEDTLS_MD_SHA512:
12500             return( MBEDTLS_SSL_HASH_SHA512 );
12501 #endif
12502         default:
12503             return( MBEDTLS_SSL_HASH_NONE );
12504     }
12505 }
12506 
12507 #if defined(MBEDTLS_ECP_C)
12508 /*
12509  * Check if a curve proposed by the peer is in our list.
12510  * Return 0 if we're willing to use it, -1 otherwise.
12511  */
12512 int mbedtls_ssl_check_curve( const mbedtls_ssl_context *ssl, mbedtls_ecp_group_id grp_id )
12513 {
12514     const mbedtls_ecp_group_id *gid;
12515 
12516     if( ssl->conf->curve_list == NULL )
12517         return( -1 );
12518 
12519     for( gid = ssl->conf->curve_list; *gid != MBEDTLS_ECP_DP_NONE; gid++ )
12520         if( *gid == grp_id )
12521             return( 0 );
12522 
12523     return( -1 );
12524 }
12525 #endif /* MBEDTLS_ECP_C */
12526 
12527 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
12528 /*
12529  * Check if a hash proposed by the peer is in our list.
12530  * Return 0 if we're willing to use it, -1 otherwise.
12531  */
12532 int mbedtls_ssl_check_sig_hash( const mbedtls_ssl_context *ssl,
12533                                 mbedtls_md_type_t md )
12534 {
12535     const int *cur;
12536 
12537     if( ssl->conf->sig_hashes == NULL )
12538         return( -1 );
12539 
12540     for( cur = ssl->conf->sig_hashes; *cur != MBEDTLS_MD_NONE; cur++ )
12541         if( *cur == (int) md )
12542             return( 0 );
12543 
12544     return( -1 );
12545 }
12546 #endif /* MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
12547 
12548 #if defined(MBEDTLS_X509_CRT_PARSE_C)
12549 int mbedtls_ssl_check_cert_usage( const mbedtls_x509_crt *cert,
12550                           const mbedtls_ssl_ciphersuite_t *ciphersuite,
12551                           int cert_endpoint,
12552                           uint32_t *flags )
12553 {
12554     int ret = 0;
12555 #if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
12556     int usage = 0;
12557 #endif
12558 #if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
12559     const char *ext_oid;
12560     size_t ext_len;
12561 #endif
12562 
12563 #if !defined(MBEDTLS_X509_CHECK_KEY_USAGE) &&          \
12564     !defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
12565     ((void) cert);
12566     ((void) cert_endpoint);
12567     ((void) flags);
12568 #endif
12569 
12570 #if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
12571     if( cert_endpoint == MBEDTLS_SSL_IS_SERVER )
12572     {
12573         /* Server part of the key exchange */
12574         switch( ciphersuite->key_exchange )
12575         {
12576             case MBEDTLS_KEY_EXCHANGE_RSA:
12577             case MBEDTLS_KEY_EXCHANGE_RSA_PSK:
12578                 usage = MBEDTLS_X509_KU_KEY_ENCIPHERMENT;
12579                 break;
12580 
12581             case MBEDTLS_KEY_EXCHANGE_DHE_RSA:
12582             case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
12583             case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
12584                 usage = MBEDTLS_X509_KU_DIGITAL_SIGNATURE;
12585                 break;
12586 
12587             case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:
12588             case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:
12589                 usage = MBEDTLS_X509_KU_KEY_AGREEMENT;
12590                 break;
12591 
12592             /* Don't use default: we want warnings when adding new values */
12593             case MBEDTLS_KEY_EXCHANGE_NONE:
12594             case MBEDTLS_KEY_EXCHANGE_PSK:
12595             case MBEDTLS_KEY_EXCHANGE_DHE_PSK:
12596             case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK:
12597             case MBEDTLS_KEY_EXCHANGE_ECJPAKE:
12598                 usage = 0;
12599         }
12600     }
12601     else
12602     {
12603         /* Client auth: we only implement rsa_sign and mbedtls_ecdsa_sign for now */
12604         usage = MBEDTLS_X509_KU_DIGITAL_SIGNATURE;
12605     }
12606 
12607     if( mbedtls_x509_crt_check_key_usage( cert, usage ) != 0 )
12608     {
12609         *flags |= MBEDTLS_X509_BADCERT_KEY_USAGE;
12610         ret = -1;
12611     }
12612 #else
12613     ((void) ciphersuite);
12614 #endif /* MBEDTLS_X509_CHECK_KEY_USAGE */
12615 
12616 #if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
12617     if( cert_endpoint == MBEDTLS_SSL_IS_SERVER )
12618     {
12619         ext_oid = MBEDTLS_OID_SERVER_AUTH;
12620         ext_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_SERVER_AUTH );
12621     }
12622     else
12623     {
12624         ext_oid = MBEDTLS_OID_CLIENT_AUTH;
12625         ext_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_CLIENT_AUTH );
12626     }
12627 
12628     if( mbedtls_x509_crt_check_extended_key_usage( cert, ext_oid, ext_len ) != 0 )
12629     {
12630         *flags |= MBEDTLS_X509_BADCERT_EXT_KEY_USAGE;
12631         ret = -1;
12632     }
12633 #endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE */
12634 
12635     return( ret );
12636 }
12637 #endif /* MBEDTLS_X509_CRT_PARSE_C */
12638 
12639 /*
12640  * Convert version numbers to/from wire format
12641  * and, for DTLS, to/from TLS equivalent.
12642  *
12643  * For TLS this is the identity.
12644  * For DTLS, use 1's complement (v -> 255 - v, and then map as follows:
12645  * 1.0 <-> 3.2      (DTLS 1.0 is based on TLS 1.1)
12646  * 1.x <-> 3.x+1    for x != 0 (DTLS 1.2 based on TLS 1.2)
12647  */
12648 void mbedtls_ssl_write_version( int major, int minor, int transport,
12649                         unsigned char ver[2] )
12650 {
12651 #if defined(MBEDTLS_SSL_PROTO_DTLS)
12652     if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
12653     {
12654         if( minor == MBEDTLS_SSL_MINOR_VERSION_2 )
12655             --minor; /* DTLS 1.0 stored as TLS 1.1 internally */
12656 
12657         ver[0] = (unsigned char)( 255 - ( major - 2 ) );
12658         ver[1] = (unsigned char)( 255 - ( minor - 1 ) );
12659     }
12660     else
12661 #else
12662     ((void) transport);
12663 #endif
12664     {
12665         ver[0] = (unsigned char) major;
12666         ver[1] = (unsigned char) minor;
12667     }
12668 }
12669 
12670 void mbedtls_ssl_read_version( int *major, int *minor, int transport,
12671                        const unsigned char ver[2] )
12672 {
12673 #if defined(MBEDTLS_SSL_PROTO_DTLS)
12674     if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
12675     {
12676         *major = 255 - ver[0] + 2;
12677         *minor = 255 - ver[1] + 1;
12678 
12679         if( *minor == MBEDTLS_SSL_MINOR_VERSION_1 )
12680             ++*minor; /* DTLS 1.0 stored as TLS 1.1 internally */
12681     }
12682     else
12683 #else
12684     ((void) transport);
12685 #endif
12686     {
12687         *major = ver[0];
12688         *minor = ver[1];
12689     }
12690 }
12691 
12692 int mbedtls_ssl_set_calc_verify_md( mbedtls_ssl_context *ssl, int md )
12693 {
12694 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
12695     if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
12696         return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
12697 
12698     switch( md )
12699     {
12700 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
12701 #if defined(MBEDTLS_MD5_C)
12702         case MBEDTLS_SSL_HASH_MD5:
12703             return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
12704 #endif
12705 #if defined(MBEDTLS_SHA1_C)
12706         case MBEDTLS_SSL_HASH_SHA1:
12707             ssl->handshake->calc_verify = ssl_calc_verify_tls;
12708             break;
12709 #endif
12710 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
12711 #if defined(MBEDTLS_SHA512_C)
12712         case MBEDTLS_SSL_HASH_SHA384:
12713             ssl->handshake->calc_verify = ssl_calc_verify_tls_sha384;
12714             break;
12715 #endif
12716 #if defined(MBEDTLS_SHA256_C)
12717         case MBEDTLS_SSL_HASH_SHA256:
12718             ssl->handshake->calc_verify = ssl_calc_verify_tls_sha256;
12719             break;
12720 #endif
12721         default:
12722             return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
12723     }
12724 
12725     return 0;
12726 #else /* !MBEDTLS_SSL_PROTO_TLS1_2 */
12727     (void) ssl;
12728     (void) md;
12729 
12730     return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
12731 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
12732 }
12733 
12734 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
12735     defined(MBEDTLS_SSL_PROTO_TLS1_1)
12736 int mbedtls_ssl_get_key_exchange_md_ssl_tls( mbedtls_ssl_context *ssl,
12737                                         unsigned char *output,
12738                                         unsigned char *data, size_t data_len )
12739 {
12740     int ret = 0;
12741     mbedtls_md5_context mbedtls_md5;
12742     mbedtls_sha1_context mbedtls_sha1;
12743 
12744     mbedtls_md5_init( &mbedtls_md5 );
12745     mbedtls_sha1_init( &mbedtls_sha1 );
12746 
12747     /*
12748      * digitally-signed struct {
12749      *     opaque md5_hash[16];
12750      *     opaque sha_hash[20];
12751      * };
12752      *
12753      * md5_hash
12754      *     MD5(ClientHello.random + ServerHello.random
12755      *                            + ServerParams);
12756      * sha_hash
12757      *     SHA(ClientHello.random + ServerHello.random
12758      *                            + ServerParams);
12759      */
12760     if( ( ret = mbedtls_md5_starts_ret( &mbedtls_md5 ) ) != 0 )
12761     {
12762         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md5_starts_ret", ret );
12763         goto exit;
12764     }
12765     if( ( ret = mbedtls_md5_update_ret( &mbedtls_md5,
12766                                         ssl->handshake->randbytes, 64 ) ) != 0 )
12767     {
12768         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md5_update_ret", ret );
12769         goto exit;
12770     }
12771     if( ( ret = mbedtls_md5_update_ret( &mbedtls_md5, data, data_len ) ) != 0 )
12772     {
12773         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md5_update_ret", ret );
12774         goto exit;
12775     }
12776     if( ( ret = mbedtls_md5_finish_ret( &mbedtls_md5, output ) ) != 0 )
12777     {
12778         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md5_finish_ret", ret );
12779         goto exit;
12780     }
12781 
12782     if( ( ret = mbedtls_sha1_starts_ret( &mbedtls_sha1 ) ) != 0 )
12783     {
12784         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha1_starts_ret", ret );
12785         goto exit;
12786     }
12787     if( ( ret = mbedtls_sha1_update_ret( &mbedtls_sha1,
12788                                          ssl->handshake->randbytes, 64 ) ) != 0 )
12789     {
12790         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha1_update_ret", ret );
12791         goto exit;
12792     }
12793     if( ( ret = mbedtls_sha1_update_ret( &mbedtls_sha1, data,
12794                                          data_len ) ) != 0 )
12795     {
12796         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha1_update_ret", ret );
12797         goto exit;
12798     }
12799     if( ( ret = mbedtls_sha1_finish_ret( &mbedtls_sha1,
12800                                          output + 16 ) ) != 0 )
12801     {
12802         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha1_finish_ret", ret );
12803         goto exit;
12804     }
12805 
12806 exit:
12807     mbedtls_md5_free( &mbedtls_md5 );
12808     mbedtls_sha1_free( &mbedtls_sha1 );
12809 
12810     if( ret != 0 )
12811         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
12812                                         MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
12813 
12814     return( ret );
12815 
12816 }
12817 #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
12818           MBEDTLS_SSL_PROTO_TLS1_1 */
12819 
12820 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
12821     defined(MBEDTLS_SSL_PROTO_TLS1_2)
12822 
12823 #if defined(MBEDTLS_USE_PSA_CRYPTO)
12824 int mbedtls_ssl_get_key_exchange_md_tls1_2( mbedtls_ssl_context *ssl,
12825                                             unsigned char *hash, size_t *hashlen,
12826                                             unsigned char *data, size_t data_len,
12827                                             mbedtls_md_type_t md_alg )
12828 {
12829     psa_status_t status;
12830     psa_hash_operation_t hash_operation = PSA_HASH_OPERATION_INIT;
12831     psa_algorithm_t hash_alg = mbedtls_psa_translate_md( md_alg );
12832 
12833     MBEDTLS_SSL_DEBUG_MSG( 3, ( "Perform PSA-based computation of digest of ServerKeyExchange" ) );
12834 
12835     if( ( status = psa_hash_setup( &hash_operation,
12836                                    hash_alg ) ) != PSA_SUCCESS )
12837     {
12838         MBEDTLS_SSL_DEBUG_RET( 1, "psa_hash_setup", status );
12839         goto exit;
12840     }
12841 
12842     if( ( status = psa_hash_update( &hash_operation, ssl->handshake->randbytes,
12843                                     64 ) ) != PSA_SUCCESS )
12844     {
12845         MBEDTLS_SSL_DEBUG_RET( 1, "psa_hash_update", status );
12846         goto exit;
12847     }
12848 
12849     if( ( status = psa_hash_update( &hash_operation,
12850                                     data, data_len ) ) != PSA_SUCCESS )
12851     {
12852         MBEDTLS_SSL_DEBUG_RET( 1, "psa_hash_update", status );
12853         goto exit;
12854     }
12855 
12856     if( ( status = psa_hash_finish( &hash_operation, hash, MBEDTLS_MD_MAX_SIZE,
12857                                     hashlen ) ) != PSA_SUCCESS )
12858     {
12859          MBEDTLS_SSL_DEBUG_RET( 1, "psa_hash_finish", status );
12860          goto exit;
12861     }
12862 
12863 exit:
12864     if( status != PSA_SUCCESS )
12865     {
12866         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
12867                                         MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
12868         switch( status )
12869         {
12870             case PSA_ERROR_NOT_SUPPORTED:
12871                 return( MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE );
12872             case PSA_ERROR_BAD_STATE: /* Intentional fallthrough */
12873             case PSA_ERROR_BUFFER_TOO_SMALL:
12874                 return( MBEDTLS_ERR_MD_BAD_INPUT_DATA );
12875             case PSA_ERROR_INSUFFICIENT_MEMORY:
12876                 return( MBEDTLS_ERR_MD_ALLOC_FAILED );
12877             default:
12878                 return( MBEDTLS_ERR_MD_HW_ACCEL_FAILED );
12879         }
12880     }
12881     return( 0 );
12882 }
12883 
12884 #else
12885 
12886 int mbedtls_ssl_get_key_exchange_md_tls1_2( mbedtls_ssl_context *ssl,
12887                                             unsigned char *hash, size_t *hashlen,
12888                                             unsigned char *data, size_t data_len,
12889                                             mbedtls_md_type_t md_alg )
12890 {
12891     int ret = 0;
12892     mbedtls_md_context_t ctx;
12893     const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type( md_alg );
12894     *hashlen = mbedtls_md_get_size( md_info );
12895 
12896     MBEDTLS_SSL_DEBUG_MSG( 3, ( "Perform mbedtls-based computation of digest of ServerKeyExchange" ) );
12897 
12898     mbedtls_md_init( &ctx );
12899 
12900     /*
12901      * digitally-signed struct {
12902      *     opaque client_random[32];
12903      *     opaque server_random[32];
12904      *     ServerDHParams params;
12905      * };
12906      */
12907     if( ( ret = mbedtls_md_setup( &ctx, md_info, 0 ) ) != 0 )
12908     {
12909         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_setup", ret );
12910         goto exit;
12911     }
12912     if( ( ret = mbedtls_md_starts( &ctx ) ) != 0 )
12913     {
12914         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_starts", ret );
12915         goto exit;
12916     }
12917     if( ( ret = mbedtls_md_update( &ctx, ssl->handshake->randbytes, 64 ) ) != 0 )
12918     {
12919         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_update", ret );
12920         goto exit;
12921     }
12922     if( ( ret = mbedtls_md_update( &ctx, data, data_len ) ) != 0 )
12923     {
12924         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_update", ret );
12925         goto exit;
12926     }
12927     if( ( ret = mbedtls_md_finish( &ctx, hash ) ) != 0 )
12928     {
12929         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_finish", ret );
12930         goto exit;
12931     }
12932 
12933 exit:
12934     mbedtls_md_free( &ctx );
12935 
12936     if( ret != 0 )
12937         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
12938                                         MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
12939 
12940     return( ret );
12941 }
12942 #endif /* MBEDTLS_USE_PSA_CRYPTO */
12943 
12944 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
12945           MBEDTLS_SSL_PROTO_TLS1_2 */
12946 
12947 #endif /* MBEDTLS_SSL_TLS_C */