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