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