mbed TLS Build

Dependents:   Encypting_Funcional

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