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