xref: /reactos/dll/3rdparty/mbedtls/ssl_tls.c (revision 02e84521)
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 accross 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     /* Check length against bounds of the current transform and version */
3708     if( ssl->transform_in == NULL )
3709     {
3710         if( ssl->in_msglen < 1 ||
3711             ssl->in_msglen > MBEDTLS_SSL_MAX_CONTENT_LEN )
3712         {
3713             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
3714             return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3715         }
3716     }
3717     else
3718     {
3719         if( ssl->in_msglen < ssl->transform_in->minlen )
3720         {
3721             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
3722             return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3723         }
3724 
3725 #if defined(MBEDTLS_SSL_PROTO_SSL3)
3726         if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 &&
3727             ssl->in_msglen > ssl->transform_in->minlen + MBEDTLS_SSL_MAX_CONTENT_LEN )
3728         {
3729             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
3730             return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3731         }
3732 #endif
3733 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
3734     defined(MBEDTLS_SSL_PROTO_TLS1_2)
3735         /*
3736          * TLS encrypted messages can have up to 256 bytes of padding
3737          */
3738         if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 &&
3739             ssl->in_msglen > ssl->transform_in->minlen +
3740                              MBEDTLS_SSL_MAX_CONTENT_LEN + 256 )
3741         {
3742             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
3743             return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3744         }
3745 #endif
3746     }
3747 
3748     /*
3749      * DTLS-related tests done last, because most of them may result in
3750      * silently dropping the record (but not the whole datagram), and we only
3751      * want to consider that after ensuring that the "basic" fields (type,
3752      * version, length) are sane.
3753      */
3754 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3755     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
3756     {
3757         unsigned int rec_epoch = ( ssl->in_ctr[0] << 8 ) | ssl->in_ctr[1];
3758 
3759         /* Drop unexpected ChangeCipherSpec messages */
3760         if( ssl->in_msgtype == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC &&
3761             ssl->state != MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC &&
3762             ssl->state != MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC )
3763         {
3764             MBEDTLS_SSL_DEBUG_MSG( 1, ( "dropping unexpected ChangeCipherSpec" ) );
3765             return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD );
3766         }
3767 
3768         /* Drop unexpected ApplicationData records,
3769          * except at the beginning of renegotiations */
3770         if( ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA &&
3771             ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER
3772 #if defined(MBEDTLS_SSL_RENEGOTIATION)
3773             && ! ( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
3774                    ssl->state == MBEDTLS_SSL_SERVER_HELLO )
3775 #endif
3776             )
3777         {
3778             MBEDTLS_SSL_DEBUG_MSG( 1, ( "dropping unexpected ApplicationData" ) );
3779             return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD );
3780         }
3781 
3782         /* Check epoch (and sequence number) with DTLS */
3783         if( rec_epoch != ssl->in_epoch )
3784         {
3785             MBEDTLS_SSL_DEBUG_MSG( 1, ( "record from another epoch: "
3786                                         "expected %d, received %d",
3787                                         ssl->in_epoch, rec_epoch ) );
3788 
3789 #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
3790             /*
3791              * Check for an epoch 0 ClientHello. We can't use in_msg here to
3792              * access the first byte of record content (handshake type), as we
3793              * have an active transform (possibly iv_len != 0), so use the
3794              * fact that the record header len is 13 instead.
3795              */
3796             if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
3797                 ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER &&
3798                 rec_epoch == 0 &&
3799                 ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
3800                 ssl->in_left > 13 &&
3801                 ssl->in_buf[13] == MBEDTLS_SSL_HS_CLIENT_HELLO )
3802             {
3803                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "possible client reconnect "
3804                                             "from the same port" ) );
3805                 return( ssl_handle_possible_reconnect( ssl ) );
3806             }
3807             else
3808 #endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */
3809                 return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD );
3810         }
3811 
3812 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
3813         /* Replay detection only works for the current epoch */
3814         if( rec_epoch == ssl->in_epoch &&
3815             mbedtls_ssl_dtls_replay_check( ssl ) != 0 )
3816         {
3817             MBEDTLS_SSL_DEBUG_MSG( 1, ( "replayed record" ) );
3818             return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD );
3819         }
3820 #endif
3821     }
3822 #endif /* MBEDTLS_SSL_PROTO_DTLS */
3823 
3824     return( 0 );
3825 }
3826 
3827 /*
3828  * If applicable, decrypt (and decompress) record content
3829  */
3830 static int ssl_prepare_record_content( mbedtls_ssl_context *ssl )
3831 {
3832     int ret, done = 0;
3833 
3834     MBEDTLS_SSL_DEBUG_BUF( 4, "input record from network",
3835                    ssl->in_hdr, mbedtls_ssl_hdr_len( ssl ) + ssl->in_msglen );
3836 
3837 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
3838     if( mbedtls_ssl_hw_record_read != NULL )
3839     {
3840         MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_read()" ) );
3841 
3842         ret = mbedtls_ssl_hw_record_read( ssl );
3843         if( ret != 0 && ret != MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH )
3844         {
3845             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_read", ret );
3846             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
3847         }
3848 
3849         if( ret == 0 )
3850             done = 1;
3851     }
3852 #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
3853     if( !done && ssl->transform_in != NULL )
3854     {
3855         if( ( ret = ssl_decrypt_buf( ssl ) ) != 0 )
3856         {
3857             MBEDTLS_SSL_DEBUG_RET( 1, "ssl_decrypt_buf", ret );
3858             return( ret );
3859         }
3860 
3861         MBEDTLS_SSL_DEBUG_BUF( 4, "input payload after decrypt",
3862                        ssl->in_msg, ssl->in_msglen );
3863 
3864         if( ssl->in_msglen > MBEDTLS_SSL_MAX_CONTENT_LEN )
3865         {
3866             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) );
3867             return( MBEDTLS_ERR_SSL_INVALID_RECORD );
3868         }
3869     }
3870 
3871 #if defined(MBEDTLS_ZLIB_SUPPORT)
3872     if( ssl->transform_in != NULL &&
3873         ssl->session_in->compression == MBEDTLS_SSL_COMPRESS_DEFLATE )
3874     {
3875         if( ( ret = ssl_decompress_buf( ssl ) ) != 0 )
3876         {
3877             MBEDTLS_SSL_DEBUG_RET( 1, "ssl_decompress_buf", ret );
3878             return( ret );
3879         }
3880     }
3881 #endif /* MBEDTLS_ZLIB_SUPPORT */
3882 
3883 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
3884     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
3885     {
3886         mbedtls_ssl_dtls_replay_update( ssl );
3887     }
3888 #endif
3889 
3890     return( 0 );
3891 }
3892 
3893 static void ssl_handshake_wrapup_free_hs_transform( mbedtls_ssl_context *ssl );
3894 
3895 /*
3896  * Read a record.
3897  *
3898  * Silently ignore non-fatal alert (and for DTLS, invalid records as well,
3899  * RFC 6347 4.1.2.7) and continue reading until a valid record is found.
3900  *
3901  */
3902 int mbedtls_ssl_read_record( mbedtls_ssl_context *ssl )
3903 {
3904     int ret;
3905 
3906     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> read record" ) );
3907 
3908     if( ssl->keep_current_message == 0 )
3909     {
3910         do {
3911 
3912             if( ( ret = mbedtls_ssl_read_record_layer( ssl ) ) != 0 )
3913             {
3914                 MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ssl_read_record_layer" ), ret );
3915                 return( ret );
3916             }
3917 
3918             ret = mbedtls_ssl_handle_message_type( ssl );
3919 
3920         } while( MBEDTLS_ERR_SSL_NON_FATAL == ret );
3921 
3922         if( 0 != ret )
3923         {
3924             MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ssl_read_record_layer" ), ret );
3925             return( ret );
3926         }
3927 
3928         if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE )
3929         {
3930             mbedtls_ssl_update_handshake_status( ssl );
3931         }
3932     }
3933     else
3934     {
3935         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= reuse previously read message" ) );
3936         ssl->keep_current_message = 0;
3937     }
3938 
3939     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= read record" ) );
3940 
3941     return( 0 );
3942 }
3943 
3944 int mbedtls_ssl_read_record_layer( mbedtls_ssl_context *ssl )
3945 {
3946     int ret;
3947 
3948     /*
3949      * Step A
3950      *
3951      * Consume last content-layer message and potentially
3952      * update in_msglen which keeps track of the contents'
3953      * consumption state.
3954      *
3955      * (1) Handshake messages:
3956      *     Remove last handshake message, move content
3957      *     and adapt in_msglen.
3958      *
3959      * (2) Alert messages:
3960      *     Consume whole record content, in_msglen = 0.
3961      *
3962      *     NOTE: This needs to be fixed, since like for
3963      *     handshake messages it is allowed to have
3964      *     multiple alerts witin a single record.
3965      *     Internal reference IOTSSL-1321.
3966      *
3967      * (3) Change cipher spec:
3968      *     Consume whole record content, in_msglen = 0.
3969      *
3970      * (4) Application data:
3971      *     Don't do anything - the record layer provides
3972      *     the application data as a stream transport
3973      *     and consumes through mbedtls_ssl_read only.
3974      *
3975      */
3976 
3977     /* Case (1): Handshake messages */
3978     if( ssl->in_hslen != 0 )
3979     {
3980         /* Hard assertion to be sure that no application data
3981          * is in flight, as corrupting ssl->in_msglen during
3982          * ssl->in_offt != NULL is fatal. */
3983         if( ssl->in_offt != NULL )
3984         {
3985             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
3986             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
3987         }
3988 
3989         /*
3990          * Get next Handshake message in the current record
3991          */
3992 
3993         /* Notes:
3994          * (1) in_hslen is *NOT* necessarily the size of the
3995          *     current handshake content: If DTLS handshake
3996          *     fragmentation is used, that's the fragment
3997          *     size instead. Using the total handshake message
3998          *     size here is FAULTY and should be changed at
3999          *     some point. Internal reference IOTSSL-1414.
4000          * (2) While it doesn't seem to cause problems, one
4001          *     has to be very careful not to assume that in_hslen
4002          *     is always <= in_msglen in a sensible communication.
4003          *     Again, it's wrong for DTLS handshake fragmentation.
4004          *     The following check is therefore mandatory, and
4005          *     should not be treated as a silently corrected assertion.
4006          *     Additionally, ssl->in_hslen might be arbitrarily out of
4007          *     bounds after handling a DTLS message with an unexpected
4008          *     sequence number, see mbedtls_ssl_prepare_handshake_record.
4009          */
4010         if( ssl->in_hslen < ssl->in_msglen )
4011         {
4012             ssl->in_msglen -= ssl->in_hslen;
4013             memmove( ssl->in_msg, ssl->in_msg + ssl->in_hslen,
4014                      ssl->in_msglen );
4015 
4016             MBEDTLS_SSL_DEBUG_BUF( 4, "remaining content in record",
4017                                    ssl->in_msg, ssl->in_msglen );
4018         }
4019         else
4020         {
4021             ssl->in_msglen = 0;
4022         }
4023 
4024         ssl->in_hslen   = 0;
4025     }
4026     /* Case (4): Application data */
4027     else if( ssl->in_offt != NULL )
4028     {
4029         return( 0 );
4030     }
4031     /* Everything else (CCS & Alerts) */
4032     else
4033     {
4034         ssl->in_msglen = 0;
4035     }
4036 
4037     /*
4038      * Step B
4039      *
4040      * Fetch and decode new record if current one is fully consumed.
4041      *
4042      */
4043 
4044     if( ssl->in_msglen > 0 )
4045     {
4046         /* There's something left to be processed in the current record. */
4047         return( 0 );
4048     }
4049 
4050     /* Need to fetch a new record */
4051 
4052 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4053 read_record_header:
4054 #endif
4055 
4056     /* Current record either fully processed or to be discarded. */
4057 
4058     if( ( ret = mbedtls_ssl_fetch_input( ssl, mbedtls_ssl_hdr_len( ssl ) ) ) != 0 )
4059     {
4060         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret );
4061         return( ret );
4062     }
4063 
4064     if( ( ret = ssl_parse_record_header( ssl ) ) != 0 )
4065     {
4066 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4067         if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
4068             ret != MBEDTLS_ERR_SSL_CLIENT_RECONNECT )
4069         {
4070             if( ret == MBEDTLS_ERR_SSL_UNEXPECTED_RECORD )
4071             {
4072                 /* Skip unexpected record (but not whole datagram) */
4073                 ssl->next_record_offset = ssl->in_msglen
4074                                         + mbedtls_ssl_hdr_len( ssl );
4075 
4076                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding unexpected record "
4077                                             "(header)" ) );
4078             }
4079             else
4080             {
4081                 /* Skip invalid record and the rest of the datagram */
4082                 ssl->next_record_offset = 0;
4083                 ssl->in_left = 0;
4084 
4085                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding invalid record "
4086                                             "(header)" ) );
4087             }
4088 
4089             /* Get next record */
4090             goto read_record_header;
4091         }
4092 #endif
4093         return( ret );
4094     }
4095 
4096     /*
4097      * Read and optionally decrypt the message contents
4098      */
4099     if( ( ret = mbedtls_ssl_fetch_input( ssl,
4100                                  mbedtls_ssl_hdr_len( ssl ) + ssl->in_msglen ) ) != 0 )
4101     {
4102         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret );
4103         return( ret );
4104     }
4105 
4106     /* Done reading this record, get ready for the next one */
4107 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4108     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
4109         ssl->next_record_offset = ssl->in_msglen + mbedtls_ssl_hdr_len( ssl );
4110     else
4111 #endif
4112         ssl->in_left = 0;
4113 
4114     if( ( ret = ssl_prepare_record_content( ssl ) ) != 0 )
4115     {
4116 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4117         if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
4118         {
4119             /* Silently discard invalid records */
4120             if( ret == MBEDTLS_ERR_SSL_INVALID_RECORD ||
4121                 ret == MBEDTLS_ERR_SSL_INVALID_MAC )
4122             {
4123                 /* Except when waiting for Finished as a bad mac here
4124                  * probably means something went wrong in the handshake
4125                  * (eg wrong psk used, mitm downgrade attempt, etc.) */
4126                 if( ssl->state == MBEDTLS_SSL_CLIENT_FINISHED ||
4127                     ssl->state == MBEDTLS_SSL_SERVER_FINISHED )
4128                 {
4129 #if defined(MBEDTLS_SSL_ALL_ALERT_MESSAGES)
4130                     if( ret == MBEDTLS_ERR_SSL_INVALID_MAC )
4131                     {
4132                         mbedtls_ssl_send_alert_message( ssl,
4133                                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
4134                                 MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC );
4135                     }
4136 #endif
4137                     return( ret );
4138                 }
4139 
4140 #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT)
4141                 if( ssl->conf->badmac_limit != 0 &&
4142                     ++ssl->badmac_seen >= ssl->conf->badmac_limit )
4143                 {
4144                     MBEDTLS_SSL_DEBUG_MSG( 1, ( "too many records with bad MAC" ) );
4145                     return( MBEDTLS_ERR_SSL_INVALID_MAC );
4146                 }
4147 #endif
4148 
4149                 /* As above, invalid records cause
4150                  * dismissal of the whole datagram. */
4151 
4152                 ssl->next_record_offset = 0;
4153                 ssl->in_left = 0;
4154 
4155                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding invalid record (mac)" ) );
4156                 goto read_record_header;
4157             }
4158 
4159             return( ret );
4160         }
4161         else
4162 #endif
4163         {
4164             /* Error out (and send alert) on invalid records */
4165 #if defined(MBEDTLS_SSL_ALL_ALERT_MESSAGES)
4166             if( ret == MBEDTLS_ERR_SSL_INVALID_MAC )
4167             {
4168                 mbedtls_ssl_send_alert_message( ssl,
4169                         MBEDTLS_SSL_ALERT_LEVEL_FATAL,
4170                         MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC );
4171             }
4172 #endif
4173             return( ret );
4174         }
4175     }
4176 
4177     /*
4178      * When we sent the last flight of the handshake, we MUST respond to a
4179      * retransmit of the peer's previous flight with a retransmit. (In
4180      * practice, only the Finished message will make it, other messages
4181      * including CCS use the old transform so they're dropped as invalid.)
4182      *
4183      * If the record we received is not a handshake message, however, it
4184      * means the peer received our last flight so we can clean up
4185      * handshake info.
4186      *
4187      * This check needs to be done before prepare_handshake() due to an edge
4188      * case: if the client immediately requests renegotiation, this
4189      * finishes the current handshake first, avoiding the new ClientHello
4190      * being mistaken for an ancient message in the current handshake.
4191      */
4192 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4193     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
4194         ssl->handshake != NULL &&
4195         ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )
4196     {
4197         if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE &&
4198                 ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED )
4199         {
4200             MBEDTLS_SSL_DEBUG_MSG( 2, ( "received retransmit of last flight" ) );
4201 
4202             if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )
4203             {
4204                 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend", ret );
4205                 return( ret );
4206             }
4207 
4208             return( MBEDTLS_ERR_SSL_WANT_READ );
4209         }
4210         else
4211         {
4212             ssl_handshake_wrapup_free_hs_transform( ssl );
4213         }
4214     }
4215 #endif
4216 
4217     return( 0 );
4218 }
4219 
4220 int mbedtls_ssl_handle_message_type( mbedtls_ssl_context *ssl )
4221 {
4222     int ret;
4223 
4224     /*
4225      * Handle particular types of records
4226      */
4227     if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE )
4228     {
4229         if( ( ret = mbedtls_ssl_prepare_handshake_record( ssl ) ) != 0 )
4230         {
4231             return( ret );
4232         }
4233     }
4234 
4235     if( ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT )
4236     {
4237         if( ssl->in_msglen != 2 )
4238         {
4239             /* Note: Standard allows for more than one 2 byte alert
4240                to be packed in a single message, but Mbed TLS doesn't
4241                currently support this. */
4242             MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid alert message, len: %d",
4243                            ssl->in_msglen ) );
4244             return( MBEDTLS_ERR_SSL_INVALID_RECORD );
4245         }
4246 
4247         MBEDTLS_SSL_DEBUG_MSG( 2, ( "got an alert message, type: [%d:%d]",
4248                        ssl->in_msg[0], ssl->in_msg[1] ) );
4249 
4250         /*
4251          * Ignore non-fatal alerts, except close_notify and no_renegotiation
4252          */
4253         if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_FATAL )
4254         {
4255             MBEDTLS_SSL_DEBUG_MSG( 1, ( "is a fatal alert message (msg %d)",
4256                            ssl->in_msg[1] ) );
4257             return( MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE );
4258         }
4259 
4260         if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&
4261             ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY )
4262         {
4263             MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a close notify message" ) );
4264             return( MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY );
4265         }
4266 
4267 #if defined(MBEDTLS_SSL_RENEGOTIATION_ENABLED)
4268         if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&
4269             ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION )
4270         {
4271             MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a SSLv3 no_cert" ) );
4272             /* Will be handled when trying to parse ServerHello */
4273             return( 0 );
4274         }
4275 #endif
4276 
4277 #if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_SRV_C)
4278         if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 &&
4279             ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
4280             ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING &&
4281             ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_CERT )
4282         {
4283             MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a SSLv3 no_cert" ) );
4284             /* Will be handled in mbedtls_ssl_parse_certificate() */
4285             return( 0 );
4286         }
4287 #endif /* MBEDTLS_SSL_PROTO_SSL3 && MBEDTLS_SSL_SRV_C */
4288 
4289         /* Silently ignore: fetch new message */
4290         return MBEDTLS_ERR_SSL_NON_FATAL;
4291     }
4292 
4293     return( 0 );
4294 }
4295 
4296 int mbedtls_ssl_send_fatal_handshake_failure( mbedtls_ssl_context *ssl )
4297 {
4298     int ret;
4299 
4300     if( ( ret = mbedtls_ssl_send_alert_message( ssl,
4301                     MBEDTLS_SSL_ALERT_LEVEL_FATAL,
4302                     MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ) ) != 0 )
4303     {
4304         return( ret );
4305     }
4306 
4307     return( 0 );
4308 }
4309 
4310 int mbedtls_ssl_send_alert_message( mbedtls_ssl_context *ssl,
4311                             unsigned char level,
4312                             unsigned char message )
4313 {
4314     int ret;
4315 
4316     if( ssl == NULL || ssl->conf == NULL )
4317         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4318 
4319     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> send alert message" ) );
4320     MBEDTLS_SSL_DEBUG_MSG( 3, ( "send alert level=%u message=%u", level, message ));
4321 
4322     ssl->out_msgtype = MBEDTLS_SSL_MSG_ALERT;
4323     ssl->out_msglen = 2;
4324     ssl->out_msg[0] = level;
4325     ssl->out_msg[1] = message;
4326 
4327     if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
4328     {
4329         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
4330         return( ret );
4331     }
4332     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= send alert message" ) );
4333 
4334     return( 0 );
4335 }
4336 
4337 /*
4338  * Handshake functions
4339  */
4340 #if !defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)         && \
4341     !defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)     && \
4342     !defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)     && \
4343     !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED)   && \
4344     !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) && \
4345     !defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED)    && \
4346     !defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
4347 /* No certificate support -> dummy functions */
4348 int mbedtls_ssl_write_certificate( mbedtls_ssl_context *ssl )
4349 {
4350     const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
4351 
4352     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate" ) );
4353 
4354     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
4355         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
4356         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
4357         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
4358     {
4359         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) );
4360         ssl->state++;
4361         return( 0 );
4362     }
4363 
4364     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
4365     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
4366 }
4367 
4368 int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl )
4369 {
4370     const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
4371 
4372     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) );
4373 
4374     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
4375         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
4376         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
4377         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
4378     {
4379         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
4380         ssl->state++;
4381         return( 0 );
4382     }
4383 
4384     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
4385     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
4386 }
4387 
4388 #else
4389 /* Some certificate support -> implement write and parse */
4390 
4391 int mbedtls_ssl_write_certificate( mbedtls_ssl_context *ssl )
4392 {
4393     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
4394     size_t i, n;
4395     const mbedtls_x509_crt *crt;
4396     const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
4397 
4398     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate" ) );
4399 
4400     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
4401         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
4402         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
4403         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
4404     {
4405         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) );
4406         ssl->state++;
4407         return( 0 );
4408     }
4409 
4410 #if defined(MBEDTLS_SSL_CLI_C)
4411     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
4412     {
4413         if( ssl->client_auth == 0 )
4414         {
4415             MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) );
4416             ssl->state++;
4417             return( 0 );
4418         }
4419 
4420 #if defined(MBEDTLS_SSL_PROTO_SSL3)
4421         /*
4422          * If using SSLv3 and got no cert, send an Alert message
4423          * (otherwise an empty Certificate message will be sent).
4424          */
4425         if( mbedtls_ssl_own_cert( ssl )  == NULL &&
4426             ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
4427         {
4428             ssl->out_msglen  = 2;
4429             ssl->out_msgtype = MBEDTLS_SSL_MSG_ALERT;
4430             ssl->out_msg[0]  = MBEDTLS_SSL_ALERT_LEVEL_WARNING;
4431             ssl->out_msg[1]  = MBEDTLS_SSL_ALERT_MSG_NO_CERT;
4432 
4433             MBEDTLS_SSL_DEBUG_MSG( 2, ( "got no certificate to send" ) );
4434             goto write_msg;
4435         }
4436 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
4437     }
4438 #endif /* MBEDTLS_SSL_CLI_C */
4439 #if defined(MBEDTLS_SSL_SRV_C)
4440     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
4441     {
4442         if( mbedtls_ssl_own_cert( ssl ) == NULL )
4443         {
4444             MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no certificate to send" ) );
4445             return( MBEDTLS_ERR_SSL_CERTIFICATE_REQUIRED );
4446         }
4447     }
4448 #endif
4449 
4450     MBEDTLS_SSL_DEBUG_CRT( 3, "own certificate", mbedtls_ssl_own_cert( ssl ) );
4451 
4452     /*
4453      *     0  .  0    handshake type
4454      *     1  .  3    handshake length
4455      *     4  .  6    length of all certs
4456      *     7  .  9    length of cert. 1
4457      *    10  . n-1   peer certificate
4458      *     n  . n+2   length of cert. 2
4459      *    n+3 . ...   upper level cert, etc.
4460      */
4461     i = 7;
4462     crt = mbedtls_ssl_own_cert( ssl );
4463 
4464     while( crt != NULL )
4465     {
4466         n = crt->raw.len;
4467         if( n > MBEDTLS_SSL_MAX_CONTENT_LEN - 3 - i )
4468         {
4469             MBEDTLS_SSL_DEBUG_MSG( 1, ( "certificate too large, %d > %d",
4470                            i + 3 + n, MBEDTLS_SSL_MAX_CONTENT_LEN ) );
4471             return( MBEDTLS_ERR_SSL_CERTIFICATE_TOO_LARGE );
4472         }
4473 
4474         ssl->out_msg[i    ] = (unsigned char)( n >> 16 );
4475         ssl->out_msg[i + 1] = (unsigned char)( n >>  8 );
4476         ssl->out_msg[i + 2] = (unsigned char)( n       );
4477 
4478         i += 3; memcpy( ssl->out_msg + i, crt->raw.p, n );
4479         i += n; crt = crt->next;
4480     }
4481 
4482     ssl->out_msg[4]  = (unsigned char)( ( i - 7 ) >> 16 );
4483     ssl->out_msg[5]  = (unsigned char)( ( i - 7 ) >>  8 );
4484     ssl->out_msg[6]  = (unsigned char)( ( i - 7 )       );
4485 
4486     ssl->out_msglen  = i;
4487     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
4488     ssl->out_msg[0]  = MBEDTLS_SSL_HS_CERTIFICATE;
4489 
4490 #if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_CLI_C)
4491 write_msg:
4492 #endif
4493 
4494     ssl->state++;
4495 
4496     if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
4497     {
4498         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
4499         return( ret );
4500     }
4501 
4502     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write certificate" ) );
4503 
4504     return( ret );
4505 }
4506 
4507 int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl )
4508 {
4509     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
4510     size_t i, n;
4511     const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
4512     int authmode = ssl->conf->authmode;
4513     uint8_t alert;
4514 
4515     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) );
4516 
4517     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
4518         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
4519         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
4520         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
4521     {
4522         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
4523         ssl->state++;
4524         return( 0 );
4525     }
4526 
4527 #if defined(MBEDTLS_SSL_SRV_C)
4528     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
4529         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
4530     {
4531         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
4532         ssl->state++;
4533         return( 0 );
4534     }
4535 
4536 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
4537     if( ssl->handshake->sni_authmode != MBEDTLS_SSL_VERIFY_UNSET )
4538         authmode = ssl->handshake->sni_authmode;
4539 #endif
4540 
4541     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
4542         authmode == MBEDTLS_SSL_VERIFY_NONE )
4543     {
4544         ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_SKIP_VERIFY;
4545         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
4546         ssl->state++;
4547         return( 0 );
4548     }
4549 #endif
4550 
4551     if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
4552     {
4553         /* mbedtls_ssl_read_record may have sent an alert already. We
4554            let it decide whether to alert. */
4555         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
4556         return( ret );
4557     }
4558 
4559     ssl->state++;
4560 
4561 #if defined(MBEDTLS_SSL_SRV_C)
4562 #if defined(MBEDTLS_SSL_PROTO_SSL3)
4563     /*
4564      * Check if the client sent an empty certificate
4565      */
4566     if( ssl->conf->endpoint  == MBEDTLS_SSL_IS_SERVER &&
4567         ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
4568     {
4569         if( ssl->in_msglen  == 2                        &&
4570             ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT            &&
4571             ssl->in_msg[0]  == MBEDTLS_SSL_ALERT_LEVEL_WARNING  &&
4572             ssl->in_msg[1]  == MBEDTLS_SSL_ALERT_MSG_NO_CERT )
4573         {
4574             MBEDTLS_SSL_DEBUG_MSG( 1, ( "SSLv3 client has no certificate" ) );
4575 
4576             /* The client was asked for a certificate but didn't send
4577                one. The client should know what's going on, so we
4578                don't send an alert. */
4579             ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_MISSING;
4580             if( authmode == MBEDTLS_SSL_VERIFY_OPTIONAL )
4581                 return( 0 );
4582             else
4583                 return( MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE );
4584         }
4585     }
4586 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
4587 
4588 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
4589     defined(MBEDTLS_SSL_PROTO_TLS1_2)
4590     if( ssl->conf->endpoint  == MBEDTLS_SSL_IS_SERVER &&
4591         ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_0 )
4592     {
4593         if( ssl->in_hslen   == 3 + mbedtls_ssl_hs_hdr_len( ssl ) &&
4594             ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE    &&
4595             ssl->in_msg[0]  == MBEDTLS_SSL_HS_CERTIFICATE   &&
4596             memcmp( ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ), "\0\0\0", 3 ) == 0 )
4597         {
4598             MBEDTLS_SSL_DEBUG_MSG( 1, ( "TLSv1 client has no certificate" ) );
4599 
4600             /* The client was asked for a certificate but didn't send
4601                one. The client should know what's going on, so we
4602                don't send an alert. */
4603             ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_MISSING;
4604             if( authmode == MBEDTLS_SSL_VERIFY_OPTIONAL )
4605                 return( 0 );
4606             else
4607                 return( MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE );
4608         }
4609     }
4610 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
4611           MBEDTLS_SSL_PROTO_TLS1_2 */
4612 #endif /* MBEDTLS_SSL_SRV_C */
4613 
4614     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
4615     {
4616         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
4617         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
4618                                         MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
4619         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
4620     }
4621 
4622     if( ssl->in_msg[0] != MBEDTLS_SSL_HS_CERTIFICATE ||
4623         ssl->in_hslen < mbedtls_ssl_hs_hdr_len( ssl ) + 3 + 3 )
4624     {
4625         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
4626         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
4627                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
4628         return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
4629     }
4630 
4631     i = mbedtls_ssl_hs_hdr_len( ssl );
4632 
4633     /*
4634      * Same message structure as in mbedtls_ssl_write_certificate()
4635      */
4636     n = ( ssl->in_msg[i+1] << 8 ) | ssl->in_msg[i+2];
4637 
4638     if( ssl->in_msg[i] != 0 ||
4639         ssl->in_hslen != n + 3 + mbedtls_ssl_hs_hdr_len( ssl ) )
4640     {
4641         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
4642         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
4643                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
4644         return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
4645     }
4646 
4647     /* In case we tried to reuse a session but it failed */
4648     if( ssl->session_negotiate->peer_cert != NULL )
4649     {
4650         mbedtls_x509_crt_free( ssl->session_negotiate->peer_cert );
4651         mbedtls_free( ssl->session_negotiate->peer_cert );
4652     }
4653 
4654     if( ( ssl->session_negotiate->peer_cert = mbedtls_calloc( 1,
4655                     sizeof( mbedtls_x509_crt ) ) ) == NULL )
4656     {
4657         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed",
4658                        sizeof( mbedtls_x509_crt ) ) );
4659         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
4660                                         MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
4661         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
4662     }
4663 
4664     mbedtls_x509_crt_init( ssl->session_negotiate->peer_cert );
4665 
4666     i += 3;
4667 
4668     while( i < ssl->in_hslen )
4669     {
4670         if ( i + 3 > ssl->in_hslen ) {
4671             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
4672             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
4673                                            MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
4674             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
4675         }
4676         if( ssl->in_msg[i] != 0 )
4677         {
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 
4684         n = ( (unsigned int) ssl->in_msg[i + 1] << 8 )
4685             | (unsigned int) ssl->in_msg[i + 2];
4686         i += 3;
4687 
4688         if( n < 128 || i + n > ssl->in_hslen )
4689         {
4690             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
4691             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
4692                                             MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
4693             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
4694         }
4695 
4696         ret = mbedtls_x509_crt_parse_der( ssl->session_negotiate->peer_cert,
4697                                   ssl->in_msg + i, n );
4698         switch( ret )
4699         {
4700         case 0: /*ok*/
4701         case MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG + MBEDTLS_ERR_OID_NOT_FOUND:
4702             /* Ignore certificate with an unknown algorithm: maybe a
4703                prior certificate was already trusted. */
4704             break;
4705 
4706         case MBEDTLS_ERR_X509_ALLOC_FAILED:
4707             alert = MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR;
4708             goto crt_parse_der_failed;
4709 
4710         case MBEDTLS_ERR_X509_UNKNOWN_VERSION:
4711             alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
4712             goto crt_parse_der_failed;
4713 
4714         default:
4715             alert = MBEDTLS_SSL_ALERT_MSG_BAD_CERT;
4716         crt_parse_der_failed:
4717             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, alert );
4718             MBEDTLS_SSL_DEBUG_RET( 1, " mbedtls_x509_crt_parse_der", ret );
4719             return( ret );
4720         }
4721 
4722         i += n;
4723     }
4724 
4725     MBEDTLS_SSL_DEBUG_CRT( 3, "peer certificate", ssl->session_negotiate->peer_cert );
4726 
4727     /*
4728      * On client, make sure the server cert doesn't change during renego to
4729      * avoid "triple handshake" attack: https://secure-resumption.com/
4730      */
4731 #if defined(MBEDTLS_SSL_RENEGOTIATION) && defined(MBEDTLS_SSL_CLI_C)
4732     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&
4733         ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
4734     {
4735         if( ssl->session->peer_cert == NULL )
4736         {
4737             MBEDTLS_SSL_DEBUG_MSG( 1, ( "new server cert during renegotiation" ) );
4738             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
4739                                             MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED );
4740             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
4741         }
4742 
4743         if( ssl->session->peer_cert->raw.len !=
4744             ssl->session_negotiate->peer_cert->raw.len ||
4745             memcmp( ssl->session->peer_cert->raw.p,
4746                     ssl->session_negotiate->peer_cert->raw.p,
4747                     ssl->session->peer_cert->raw.len ) != 0 )
4748         {
4749             MBEDTLS_SSL_DEBUG_MSG( 1, ( "server cert changed during renegotiation" ) );
4750             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
4751                                             MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED );
4752             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
4753         }
4754     }
4755 #endif /* MBEDTLS_SSL_RENEGOTIATION && MBEDTLS_SSL_CLI_C */
4756 
4757     if( authmode != MBEDTLS_SSL_VERIFY_NONE )
4758     {
4759         mbedtls_x509_crt *ca_chain;
4760         mbedtls_x509_crl *ca_crl;
4761 
4762 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
4763         if( ssl->handshake->sni_ca_chain != NULL )
4764         {
4765             ca_chain = ssl->handshake->sni_ca_chain;
4766             ca_crl   = ssl->handshake->sni_ca_crl;
4767         }
4768         else
4769 #endif
4770         {
4771             ca_chain = ssl->conf->ca_chain;
4772             ca_crl   = ssl->conf->ca_crl;
4773         }
4774 
4775         /*
4776          * Main check: verify certificate
4777          */
4778         ret = mbedtls_x509_crt_verify_with_profile(
4779                                 ssl->session_negotiate->peer_cert,
4780                                 ca_chain, ca_crl,
4781                                 ssl->conf->cert_profile,
4782                                 ssl->hostname,
4783                                &ssl->session_negotiate->verify_result,
4784                                 ssl->conf->f_vrfy, ssl->conf->p_vrfy );
4785 
4786         if( ret != 0 )
4787         {
4788             MBEDTLS_SSL_DEBUG_RET( 1, "x509_verify_cert", ret );
4789         }
4790 
4791         /*
4792          * Secondary checks: always done, but change 'ret' only if it was 0
4793          */
4794 
4795 #if defined(MBEDTLS_ECP_C)
4796         {
4797             const mbedtls_pk_context *pk = &ssl->session_negotiate->peer_cert->pk;
4798 
4799             /* If certificate uses an EC key, make sure the curve is OK */
4800             if( mbedtls_pk_can_do( pk, MBEDTLS_PK_ECKEY ) &&
4801                 mbedtls_ssl_check_curve( ssl, mbedtls_pk_ec( *pk )->grp.id ) != 0 )
4802             {
4803                 ssl->session_negotiate->verify_result |= MBEDTLS_X509_BADCERT_BAD_KEY;
4804 
4805                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate (EC key curve)" ) );
4806                 if( ret == 0 )
4807                     ret = MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE;
4808             }
4809         }
4810 #endif /* MBEDTLS_ECP_C */
4811 
4812         if( mbedtls_ssl_check_cert_usage( ssl->session_negotiate->peer_cert,
4813                                  ciphersuite_info,
4814                                  ! ssl->conf->endpoint,
4815                                  &ssl->session_negotiate->verify_result ) != 0 )
4816         {
4817             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate (usage extensions)" ) );
4818             if( ret == 0 )
4819                 ret = MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE;
4820         }
4821 
4822         /* mbedtls_x509_crt_verify_with_profile is supposed to report a
4823          * verification failure through MBEDTLS_ERR_X509_CERT_VERIFY_FAILED,
4824          * with details encoded in the verification flags. All other kinds
4825          * of error codes, including those from the user provided f_vrfy
4826          * functions, are treated as fatal and lead to a failure of
4827          * ssl_parse_certificate even if verification was optional. */
4828         if( authmode == MBEDTLS_SSL_VERIFY_OPTIONAL &&
4829             ( ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED ||
4830               ret == MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE ) )
4831         {
4832             ret = 0;
4833         }
4834 
4835         if( ca_chain == NULL && authmode == MBEDTLS_SSL_VERIFY_REQUIRED )
4836         {
4837             MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no CA chain" ) );
4838             ret = MBEDTLS_ERR_SSL_CA_CHAIN_REQUIRED;
4839         }
4840 
4841         if( ret != 0 )
4842         {
4843             /* The certificate may have been rejected for several reasons.
4844                Pick one and send the corresponding alert. Which alert to send
4845                may be a subject of debate in some cases. */
4846             if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_OTHER )
4847                 alert = MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED;
4848             else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_CN_MISMATCH )
4849                 alert = MBEDTLS_SSL_ALERT_MSG_BAD_CERT;
4850             else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_KEY_USAGE )
4851                 alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
4852             else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_EXT_KEY_USAGE )
4853                 alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
4854             else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_NS_CERT_TYPE )
4855                 alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
4856             else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_BAD_PK )
4857                 alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
4858             else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_BAD_KEY )
4859                 alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
4860             else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_EXPIRED )
4861                 alert = MBEDTLS_SSL_ALERT_MSG_CERT_EXPIRED;
4862             else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_REVOKED )
4863                 alert = MBEDTLS_SSL_ALERT_MSG_CERT_REVOKED;
4864             else if( ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_NOT_TRUSTED )
4865                 alert = MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA;
4866             else
4867                 alert = MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN;
4868             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
4869                                             alert );
4870         }
4871 
4872 #if defined(MBEDTLS_DEBUG_C)
4873         if( ssl->session_negotiate->verify_result != 0 )
4874         {
4875             MBEDTLS_SSL_DEBUG_MSG( 3, ( "! Certificate verification flags %x",
4876                                         ssl->session_negotiate->verify_result ) );
4877         }
4878         else
4879         {
4880             MBEDTLS_SSL_DEBUG_MSG( 3, ( "Certificate verification flags clear" ) );
4881         }
4882 #endif /* MBEDTLS_DEBUG_C */
4883     }
4884 
4885     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse certificate" ) );
4886 
4887     return( ret );
4888 }
4889 #endif /* !MBEDTLS_KEY_EXCHANGE_RSA_ENABLED
4890           !MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED
4891           !MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED
4892           !MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED
4893           !MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
4894           !MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED
4895           !MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
4896 
4897 int mbedtls_ssl_write_change_cipher_spec( mbedtls_ssl_context *ssl )
4898 {
4899     int ret;
4900 
4901     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write change cipher spec" ) );
4902 
4903     ssl->out_msgtype = MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC;
4904     ssl->out_msglen  = 1;
4905     ssl->out_msg[0]  = 1;
4906 
4907     ssl->state++;
4908 
4909     if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
4910     {
4911         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
4912         return( ret );
4913     }
4914 
4915     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write change cipher spec" ) );
4916 
4917     return( 0 );
4918 }
4919 
4920 int mbedtls_ssl_parse_change_cipher_spec( mbedtls_ssl_context *ssl )
4921 {
4922     int ret;
4923 
4924     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse change cipher spec" ) );
4925 
4926     if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
4927     {
4928         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
4929         return( ret );
4930     }
4931 
4932     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC )
4933     {
4934         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad change cipher spec message" ) );
4935         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
4936                                         MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
4937         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
4938     }
4939 
4940     if( ssl->in_msglen != 1 || ssl->in_msg[0] != 1 )
4941     {
4942         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad change cipher spec message" ) );
4943         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
4944                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
4945         return( MBEDTLS_ERR_SSL_BAD_HS_CHANGE_CIPHER_SPEC );
4946     }
4947 
4948     /*
4949      * Switch to our negotiated transform and session parameters for inbound
4950      * data.
4951      */
4952     MBEDTLS_SSL_DEBUG_MSG( 3, ( "switching to new transform spec for inbound data" ) );
4953     ssl->transform_in = ssl->transform_negotiate;
4954     ssl->session_in = ssl->session_negotiate;
4955 
4956 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4957     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
4958     {
4959 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
4960         ssl_dtls_replay_reset( ssl );
4961 #endif
4962 
4963         /* Increment epoch */
4964         if( ++ssl->in_epoch == 0 )
4965         {
4966             MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS epoch would wrap" ) );
4967             /* This is highly unlikely to happen for legitimate reasons, so
4968                treat it as an attack and don't send an alert. */
4969             return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
4970         }
4971     }
4972     else
4973 #endif /* MBEDTLS_SSL_PROTO_DTLS */
4974     memset( ssl->in_ctr, 0, 8 );
4975 
4976     /*
4977      * Set the in_msg pointer to the correct location based on IV length
4978      */
4979     if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
4980     {
4981         ssl->in_msg = ssl->in_iv + ssl->transform_negotiate->ivlen -
4982                       ssl->transform_negotiate->fixed_ivlen;
4983     }
4984     else
4985         ssl->in_msg = ssl->in_iv;
4986 
4987 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
4988     if( mbedtls_ssl_hw_record_activate != NULL )
4989     {
4990         if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_INBOUND ) ) != 0 )
4991         {
4992             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret );
4993             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
4994                                             MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
4995             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
4996         }
4997     }
4998 #endif
4999 
5000     ssl->state++;
5001 
5002     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse change cipher spec" ) );
5003 
5004     return( 0 );
5005 }
5006 
5007 void mbedtls_ssl_optimize_checksum( mbedtls_ssl_context *ssl,
5008                             const mbedtls_ssl_ciphersuite_t *ciphersuite_info )
5009 {
5010     ((void) ciphersuite_info);
5011 
5012 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
5013     defined(MBEDTLS_SSL_PROTO_TLS1_1)
5014     if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 )
5015         ssl->handshake->update_checksum = ssl_update_checksum_md5sha1;
5016     else
5017 #endif
5018 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
5019 #if defined(MBEDTLS_SHA512_C)
5020     if( ciphersuite_info->mac == MBEDTLS_MD_SHA384 )
5021         ssl->handshake->update_checksum = ssl_update_checksum_sha384;
5022     else
5023 #endif
5024 #if defined(MBEDTLS_SHA256_C)
5025     if( ciphersuite_info->mac != MBEDTLS_MD_SHA384 )
5026         ssl->handshake->update_checksum = ssl_update_checksum_sha256;
5027     else
5028 #endif
5029 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
5030     {
5031         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
5032         return;
5033     }
5034 }
5035 
5036 void mbedtls_ssl_reset_checksum( mbedtls_ssl_context *ssl )
5037 {
5038 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
5039     defined(MBEDTLS_SSL_PROTO_TLS1_1)
5040      mbedtls_md5_starts_ret( &ssl->handshake->fin_md5  );
5041     mbedtls_sha1_starts_ret( &ssl->handshake->fin_sha1 );
5042 #endif
5043 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
5044 #if defined(MBEDTLS_SHA256_C)
5045     mbedtls_sha256_starts_ret( &ssl->handshake->fin_sha256, 0 );
5046 #endif
5047 #if defined(MBEDTLS_SHA512_C)
5048     mbedtls_sha512_starts_ret( &ssl->handshake->fin_sha512, 1 );
5049 #endif
5050 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
5051 }
5052 
5053 static void ssl_update_checksum_start( mbedtls_ssl_context *ssl,
5054                                        const unsigned char *buf, size_t len )
5055 {
5056 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
5057     defined(MBEDTLS_SSL_PROTO_TLS1_1)
5058      mbedtls_md5_update_ret( &ssl->handshake->fin_md5 , buf, len );
5059     mbedtls_sha1_update_ret( &ssl->handshake->fin_sha1, buf, len );
5060 #endif
5061 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
5062 #if defined(MBEDTLS_SHA256_C)
5063     mbedtls_sha256_update_ret( &ssl->handshake->fin_sha256, buf, len );
5064 #endif
5065 #if defined(MBEDTLS_SHA512_C)
5066     mbedtls_sha512_update_ret( &ssl->handshake->fin_sha512, buf, len );
5067 #endif
5068 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
5069 }
5070 
5071 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
5072     defined(MBEDTLS_SSL_PROTO_TLS1_1)
5073 static void ssl_update_checksum_md5sha1( mbedtls_ssl_context *ssl,
5074                                          const unsigned char *buf, size_t len )
5075 {
5076      mbedtls_md5_update_ret( &ssl->handshake->fin_md5 , buf, len );
5077     mbedtls_sha1_update_ret( &ssl->handshake->fin_sha1, buf, len );
5078 }
5079 #endif
5080 
5081 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
5082 #if defined(MBEDTLS_SHA256_C)
5083 static void ssl_update_checksum_sha256( mbedtls_ssl_context *ssl,
5084                                         const unsigned char *buf, size_t len )
5085 {
5086     mbedtls_sha256_update_ret( &ssl->handshake->fin_sha256, buf, len );
5087 }
5088 #endif
5089 
5090 #if defined(MBEDTLS_SHA512_C)
5091 static void ssl_update_checksum_sha384( mbedtls_ssl_context *ssl,
5092                                         const unsigned char *buf, size_t len )
5093 {
5094     mbedtls_sha512_update_ret( &ssl->handshake->fin_sha512, buf, len );
5095 }
5096 #endif
5097 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
5098 
5099 #if defined(MBEDTLS_SSL_PROTO_SSL3)
5100 static void ssl_calc_finished_ssl(
5101                 mbedtls_ssl_context *ssl, unsigned char *buf, int from )
5102 {
5103     const char *sender;
5104     mbedtls_md5_context  md5;
5105     mbedtls_sha1_context sha1;
5106 
5107     unsigned char padbuf[48];
5108     unsigned char md5sum[16];
5109     unsigned char sha1sum[20];
5110 
5111     mbedtls_ssl_session *session = ssl->session_negotiate;
5112     if( !session )
5113         session = ssl->session;
5114 
5115     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc  finished ssl" ) );
5116 
5117     mbedtls_md5_init( &md5 );
5118     mbedtls_sha1_init( &sha1 );
5119 
5120     mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
5121     mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
5122 
5123     /*
5124      * SSLv3:
5125      *   hash =
5126      *      MD5( master + pad2 +
5127      *          MD5( handshake + sender + master + pad1 ) )
5128      *   + SHA1( master + pad2 +
5129      *         SHA1( handshake + sender + master + pad1 ) )
5130      */
5131 
5132 #if !defined(MBEDTLS_MD5_ALT)
5133     MBEDTLS_SSL_DEBUG_BUF( 4, "finished  md5 state", (unsigned char *)
5134                     md5.state, sizeof(  md5.state ) );
5135 #endif
5136 
5137 #if !defined(MBEDTLS_SHA1_ALT)
5138     MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha1 state", (unsigned char *)
5139                    sha1.state, sizeof( sha1.state ) );
5140 #endif
5141 
5142     sender = ( from == MBEDTLS_SSL_IS_CLIENT ) ? "CLNT"
5143                                        : "SRVR";
5144 
5145     memset( padbuf, 0x36, 48 );
5146 
5147     mbedtls_md5_update_ret( &md5, (const unsigned char *) sender, 4 );
5148     mbedtls_md5_update_ret( &md5, session->master, 48 );
5149     mbedtls_md5_update_ret( &md5, padbuf, 48 );
5150     mbedtls_md5_finish_ret( &md5, md5sum );
5151 
5152     mbedtls_sha1_update_ret( &sha1, (const unsigned char *) sender, 4 );
5153     mbedtls_sha1_update_ret( &sha1, session->master, 48 );
5154     mbedtls_sha1_update_ret( &sha1, padbuf, 40 );
5155     mbedtls_sha1_finish_ret( &sha1, sha1sum );
5156 
5157     memset( padbuf, 0x5C, 48 );
5158 
5159     mbedtls_md5_starts_ret( &md5 );
5160     mbedtls_md5_update_ret( &md5, session->master, 48 );
5161     mbedtls_md5_update_ret( &md5, padbuf, 48 );
5162     mbedtls_md5_update_ret( &md5, md5sum, 16 );
5163     mbedtls_md5_finish_ret( &md5, buf );
5164 
5165     mbedtls_sha1_starts_ret( &sha1 );
5166     mbedtls_sha1_update_ret( &sha1, session->master, 48 );
5167     mbedtls_sha1_update_ret( &sha1, padbuf , 40 );
5168     mbedtls_sha1_update_ret( &sha1, sha1sum, 20 );
5169     mbedtls_sha1_finish_ret( &sha1, buf + 16 );
5170 
5171     MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, 36 );
5172 
5173     mbedtls_md5_free(  &md5  );
5174     mbedtls_sha1_free( &sha1 );
5175 
5176     mbedtls_zeroize(  padbuf, sizeof(  padbuf ) );
5177     mbedtls_zeroize(  md5sum, sizeof(  md5sum ) );
5178     mbedtls_zeroize( sha1sum, sizeof( sha1sum ) );
5179 
5180     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc  finished" ) );
5181 }
5182 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
5183 
5184 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
5185 static void ssl_calc_finished_tls(
5186                 mbedtls_ssl_context *ssl, unsigned char *buf, int from )
5187 {
5188     int len = 12;
5189     const char *sender;
5190     mbedtls_md5_context  md5;
5191     mbedtls_sha1_context sha1;
5192     unsigned char padbuf[36];
5193 
5194     mbedtls_ssl_session *session = ssl->session_negotiate;
5195     if( !session )
5196         session = ssl->session;
5197 
5198     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc  finished tls" ) );
5199 
5200     mbedtls_md5_init( &md5 );
5201     mbedtls_sha1_init( &sha1 );
5202 
5203     mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 );
5204     mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 );
5205 
5206     /*
5207      * TLSv1:
5208      *   hash = PRF( master, finished_label,
5209      *               MD5( handshake ) + SHA1( handshake ) )[0..11]
5210      */
5211 
5212 #if !defined(MBEDTLS_MD5_ALT)
5213     MBEDTLS_SSL_DEBUG_BUF( 4, "finished  md5 state", (unsigned char *)
5214                     md5.state, sizeof(  md5.state ) );
5215 #endif
5216 
5217 #if !defined(MBEDTLS_SHA1_ALT)
5218     MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha1 state", (unsigned char *)
5219                    sha1.state, sizeof( sha1.state ) );
5220 #endif
5221 
5222     sender = ( from == MBEDTLS_SSL_IS_CLIENT )
5223              ? "client finished"
5224              : "server finished";
5225 
5226     mbedtls_md5_finish_ret(  &md5, padbuf );
5227     mbedtls_sha1_finish_ret( &sha1, padbuf + 16 );
5228 
5229     ssl->handshake->tls_prf( session->master, 48, sender,
5230                              padbuf, 36, buf, len );
5231 
5232     MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len );
5233 
5234     mbedtls_md5_free(  &md5  );
5235     mbedtls_sha1_free( &sha1 );
5236 
5237     mbedtls_zeroize(  padbuf, sizeof(  padbuf ) );
5238 
5239     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc  finished" ) );
5240 }
5241 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
5242 
5243 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
5244 #if defined(MBEDTLS_SHA256_C)
5245 static void ssl_calc_finished_tls_sha256(
5246                 mbedtls_ssl_context *ssl, unsigned char *buf, int from )
5247 {
5248     int len = 12;
5249     const char *sender;
5250     mbedtls_sha256_context sha256;
5251     unsigned char padbuf[32];
5252 
5253     mbedtls_ssl_session *session = ssl->session_negotiate;
5254     if( !session )
5255         session = ssl->session;
5256 
5257     mbedtls_sha256_init( &sha256 );
5258 
5259     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc  finished tls sha256" ) );
5260 
5261     mbedtls_sha256_clone( &sha256, &ssl->handshake->fin_sha256 );
5262 
5263     /*
5264      * TLSv1.2:
5265      *   hash = PRF( master, finished_label,
5266      *               Hash( handshake ) )[0.11]
5267      */
5268 
5269 #if !defined(MBEDTLS_SHA256_ALT)
5270     MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha2 state", (unsigned char *)
5271                    sha256.state, sizeof( sha256.state ) );
5272 #endif
5273 
5274     sender = ( from == MBEDTLS_SSL_IS_CLIENT )
5275              ? "client finished"
5276              : "server finished";
5277 
5278     mbedtls_sha256_finish_ret( &sha256, padbuf );
5279 
5280     ssl->handshake->tls_prf( session->master, 48, sender,
5281                              padbuf, 32, buf, len );
5282 
5283     MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len );
5284 
5285     mbedtls_sha256_free( &sha256 );
5286 
5287     mbedtls_zeroize(  padbuf, sizeof(  padbuf ) );
5288 
5289     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc  finished" ) );
5290 }
5291 #endif /* MBEDTLS_SHA256_C */
5292 
5293 #if defined(MBEDTLS_SHA512_C)
5294 static void ssl_calc_finished_tls_sha384(
5295                 mbedtls_ssl_context *ssl, unsigned char *buf, int from )
5296 {
5297     int len = 12;
5298     const char *sender;
5299     mbedtls_sha512_context sha512;
5300     unsigned char padbuf[48];
5301 
5302     mbedtls_ssl_session *session = ssl->session_negotiate;
5303     if( !session )
5304         session = ssl->session;
5305 
5306     mbedtls_sha512_init( &sha512 );
5307 
5308     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc  finished tls sha384" ) );
5309 
5310     mbedtls_sha512_clone( &sha512, &ssl->handshake->fin_sha512 );
5311 
5312     /*
5313      * TLSv1.2:
5314      *   hash = PRF( master, finished_label,
5315      *               Hash( handshake ) )[0.11]
5316      */
5317 
5318 #if !defined(MBEDTLS_SHA512_ALT)
5319     MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha512 state", (unsigned char *)
5320                    sha512.state, sizeof( sha512.state ) );
5321 #endif
5322 
5323     sender = ( from == MBEDTLS_SSL_IS_CLIENT )
5324              ? "client finished"
5325              : "server finished";
5326 
5327     mbedtls_sha512_finish_ret( &sha512, padbuf );
5328 
5329     ssl->handshake->tls_prf( session->master, 48, sender,
5330                              padbuf, 48, buf, len );
5331 
5332     MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len );
5333 
5334     mbedtls_sha512_free( &sha512 );
5335 
5336     mbedtls_zeroize(  padbuf, sizeof( padbuf ) );
5337 
5338     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc  finished" ) );
5339 }
5340 #endif /* MBEDTLS_SHA512_C */
5341 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
5342 
5343 static void ssl_handshake_wrapup_free_hs_transform( mbedtls_ssl_context *ssl )
5344 {
5345     MBEDTLS_SSL_DEBUG_MSG( 3, ( "=> handshake wrapup: final free" ) );
5346 
5347     /*
5348      * Free our handshake params
5349      */
5350     mbedtls_ssl_handshake_free( ssl->handshake );
5351     mbedtls_free( ssl->handshake );
5352     ssl->handshake = NULL;
5353 
5354     /*
5355      * Free the previous transform and swith in the current one
5356      */
5357     if( ssl->transform )
5358     {
5359         mbedtls_ssl_transform_free( ssl->transform );
5360         mbedtls_free( ssl->transform );
5361     }
5362     ssl->transform = ssl->transform_negotiate;
5363     ssl->transform_negotiate = NULL;
5364 
5365     MBEDTLS_SSL_DEBUG_MSG( 3, ( "<= handshake wrapup: final free" ) );
5366 }
5367 
5368 void mbedtls_ssl_handshake_wrapup( mbedtls_ssl_context *ssl )
5369 {
5370     int resume = ssl->handshake->resume;
5371 
5372     MBEDTLS_SSL_DEBUG_MSG( 3, ( "=> handshake wrapup" ) );
5373 
5374 #if defined(MBEDTLS_SSL_RENEGOTIATION)
5375     if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
5376     {
5377         ssl->renego_status =  MBEDTLS_SSL_RENEGOTIATION_DONE;
5378         ssl->renego_records_seen = 0;
5379     }
5380 #endif
5381 
5382     /*
5383      * Free the previous session and switch in the current one
5384      */
5385     if( ssl->session )
5386     {
5387 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
5388         /* RFC 7366 3.1: keep the EtM state */
5389         ssl->session_negotiate->encrypt_then_mac =
5390                   ssl->session->encrypt_then_mac;
5391 #endif
5392 
5393         mbedtls_ssl_session_free( ssl->session );
5394         mbedtls_free( ssl->session );
5395     }
5396     ssl->session = ssl->session_negotiate;
5397     ssl->session_negotiate = NULL;
5398 
5399     /*
5400      * Add cache entry
5401      */
5402     if( ssl->conf->f_set_cache != NULL &&
5403         ssl->session->id_len != 0 &&
5404         resume == 0 )
5405     {
5406         if( ssl->conf->f_set_cache( ssl->conf->p_cache, ssl->session ) != 0 )
5407             MBEDTLS_SSL_DEBUG_MSG( 1, ( "cache did not store session" ) );
5408     }
5409 
5410 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5411     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
5412         ssl->handshake->flight != NULL )
5413     {
5414         /* Cancel handshake timer */
5415         ssl_set_timer( ssl, 0 );
5416 
5417         /* Keep last flight around in case we need to resend it:
5418          * we need the handshake and transform structures for that */
5419         MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip freeing handshake and transform" ) );
5420     }
5421     else
5422 #endif
5423         ssl_handshake_wrapup_free_hs_transform( ssl );
5424 
5425     ssl->state++;
5426 
5427     MBEDTLS_SSL_DEBUG_MSG( 3, ( "<= handshake wrapup" ) );
5428 }
5429 
5430 int mbedtls_ssl_write_finished( mbedtls_ssl_context *ssl )
5431 {
5432     int ret, hash_len;
5433 
5434     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write finished" ) );
5435 
5436     /*
5437      * Set the out_msg pointer to the correct location based on IV length
5438      */
5439     if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
5440     {
5441         ssl->out_msg = ssl->out_iv + ssl->transform_negotiate->ivlen -
5442                        ssl->transform_negotiate->fixed_ivlen;
5443     }
5444     else
5445         ssl->out_msg = ssl->out_iv;
5446 
5447     ssl->handshake->calc_finished( ssl, ssl->out_msg + 4, ssl->conf->endpoint );
5448 
5449     /*
5450      * RFC 5246 7.4.9 (Page 63) says 12 is the default length and ciphersuites
5451      * may define some other value. Currently (early 2016), no defined
5452      * ciphersuite does this (and this is unlikely to change as activity has
5453      * moved to TLS 1.3 now) so we can keep the hardcoded 12 here.
5454      */
5455     hash_len = ( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) ? 36 : 12;
5456 
5457 #if defined(MBEDTLS_SSL_RENEGOTIATION)
5458     ssl->verify_data_len = hash_len;
5459     memcpy( ssl->own_verify_data, ssl->out_msg + 4, hash_len );
5460 #endif
5461 
5462     ssl->out_msglen  = 4 + hash_len;
5463     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
5464     ssl->out_msg[0]  = MBEDTLS_SSL_HS_FINISHED;
5465 
5466     /*
5467      * In case of session resuming, invert the client and server
5468      * ChangeCipherSpec messages order.
5469      */
5470     if( ssl->handshake->resume != 0 )
5471     {
5472 #if defined(MBEDTLS_SSL_CLI_C)
5473         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
5474             ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
5475 #endif
5476 #if defined(MBEDTLS_SSL_SRV_C)
5477         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
5478             ssl->state = MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC;
5479 #endif
5480     }
5481     else
5482         ssl->state++;
5483 
5484     /*
5485      * Switch to our negotiated transform and session parameters for outbound
5486      * data.
5487      */
5488     MBEDTLS_SSL_DEBUG_MSG( 3, ( "switching to new transform spec for outbound data" ) );
5489 
5490 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5491     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
5492     {
5493         unsigned char i;
5494 
5495         /* Remember current epoch settings for resending */
5496         ssl->handshake->alt_transform_out = ssl->transform_out;
5497         memcpy( ssl->handshake->alt_out_ctr, ssl->out_ctr, 8 );
5498 
5499         /* Set sequence_number to zero */
5500         memset( ssl->out_ctr + 2, 0, 6 );
5501 
5502         /* Increment epoch */
5503         for( i = 2; i > 0; i-- )
5504             if( ++ssl->out_ctr[i - 1] != 0 )
5505                 break;
5506 
5507         /* The loop goes to its end iff the counter is wrapping */
5508         if( i == 0 )
5509         {
5510             MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS epoch would wrap" ) );
5511             return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING );
5512         }
5513     }
5514     else
5515 #endif /* MBEDTLS_SSL_PROTO_DTLS */
5516     memset( ssl->out_ctr, 0, 8 );
5517 
5518     ssl->transform_out = ssl->transform_negotiate;
5519     ssl->session_out = ssl->session_negotiate;
5520 
5521 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
5522     if( mbedtls_ssl_hw_record_activate != NULL )
5523     {
5524         if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_OUTBOUND ) ) != 0 )
5525         {
5526             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret );
5527             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
5528         }
5529     }
5530 #endif
5531 
5532 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5533     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
5534         mbedtls_ssl_send_flight_completed( ssl );
5535 #endif
5536 
5537     if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
5538     {
5539         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
5540         return( ret );
5541     }
5542 
5543     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write finished" ) );
5544 
5545     return( 0 );
5546 }
5547 
5548 #if defined(MBEDTLS_SSL_PROTO_SSL3)
5549 #define SSL_MAX_HASH_LEN 36
5550 #else
5551 #define SSL_MAX_HASH_LEN 12
5552 #endif
5553 
5554 int mbedtls_ssl_parse_finished( mbedtls_ssl_context *ssl )
5555 {
5556     int ret;
5557     unsigned int hash_len;
5558     unsigned char buf[SSL_MAX_HASH_LEN];
5559 
5560     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse finished" ) );
5561 
5562     ssl->handshake->calc_finished( ssl, buf, ssl->conf->endpoint ^ 1 );
5563 
5564     if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
5565     {
5566         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
5567         return( ret );
5568     }
5569 
5570     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
5571     {
5572         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
5573         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
5574                                         MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
5575         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
5576     }
5577 
5578     /* There is currently no ciphersuite using another length with TLS 1.2 */
5579 #if defined(MBEDTLS_SSL_PROTO_SSL3)
5580     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
5581         hash_len = 36;
5582     else
5583 #endif
5584         hash_len = 12;
5585 
5586     if( ssl->in_msg[0] != MBEDTLS_SSL_HS_FINISHED ||
5587         ssl->in_hslen  != mbedtls_ssl_hs_hdr_len( ssl ) + hash_len )
5588     {
5589         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
5590         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
5591                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
5592         return( MBEDTLS_ERR_SSL_BAD_HS_FINISHED );
5593     }
5594 
5595     if( mbedtls_ssl_safer_memcmp( ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ),
5596                       buf, hash_len ) != 0 )
5597     {
5598         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) );
5599         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
5600                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
5601         return( MBEDTLS_ERR_SSL_BAD_HS_FINISHED );
5602     }
5603 
5604 #if defined(MBEDTLS_SSL_RENEGOTIATION)
5605     ssl->verify_data_len = hash_len;
5606     memcpy( ssl->peer_verify_data, buf, hash_len );
5607 #endif
5608 
5609     if( ssl->handshake->resume != 0 )
5610     {
5611 #if defined(MBEDTLS_SSL_CLI_C)
5612         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
5613             ssl->state = MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC;
5614 #endif
5615 #if defined(MBEDTLS_SSL_SRV_C)
5616         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
5617             ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
5618 #endif
5619     }
5620     else
5621         ssl->state++;
5622 
5623 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5624     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
5625         mbedtls_ssl_recv_flight_completed( ssl );
5626 #endif
5627 
5628     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse finished" ) );
5629 
5630     return( 0 );
5631 }
5632 
5633 static void ssl_handshake_params_init( mbedtls_ssl_handshake_params *handshake )
5634 {
5635     memset( handshake, 0, sizeof( mbedtls_ssl_handshake_params ) );
5636 
5637 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
5638     defined(MBEDTLS_SSL_PROTO_TLS1_1)
5639      mbedtls_md5_init(   &handshake->fin_md5  );
5640     mbedtls_sha1_init(   &handshake->fin_sha1 );
5641      mbedtls_md5_starts_ret( &handshake->fin_md5  );
5642     mbedtls_sha1_starts_ret( &handshake->fin_sha1 );
5643 #endif
5644 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
5645 #if defined(MBEDTLS_SHA256_C)
5646     mbedtls_sha256_init(   &handshake->fin_sha256    );
5647     mbedtls_sha256_starts_ret( &handshake->fin_sha256, 0 );
5648 #endif
5649 #if defined(MBEDTLS_SHA512_C)
5650     mbedtls_sha512_init(   &handshake->fin_sha512    );
5651     mbedtls_sha512_starts_ret( &handshake->fin_sha512, 1 );
5652 #endif
5653 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
5654 
5655     handshake->update_checksum = ssl_update_checksum_start;
5656 
5657 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
5658     defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
5659     mbedtls_ssl_sig_hash_set_init( &handshake->hash_algs );
5660 #endif
5661 
5662 #if defined(MBEDTLS_DHM_C)
5663     mbedtls_dhm_init( &handshake->dhm_ctx );
5664 #endif
5665 #if defined(MBEDTLS_ECDH_C)
5666     mbedtls_ecdh_init( &handshake->ecdh_ctx );
5667 #endif
5668 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
5669     mbedtls_ecjpake_init( &handshake->ecjpake_ctx );
5670 #if defined(MBEDTLS_SSL_CLI_C)
5671     handshake->ecjpake_cache = NULL;
5672     handshake->ecjpake_cache_len = 0;
5673 #endif
5674 #endif
5675 
5676 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
5677     handshake->sni_authmode = MBEDTLS_SSL_VERIFY_UNSET;
5678 #endif
5679 }
5680 
5681 static void ssl_transform_init( mbedtls_ssl_transform *transform )
5682 {
5683     memset( transform, 0, sizeof(mbedtls_ssl_transform) );
5684 
5685     mbedtls_cipher_init( &transform->cipher_ctx_enc );
5686     mbedtls_cipher_init( &transform->cipher_ctx_dec );
5687 
5688     mbedtls_md_init( &transform->md_ctx_enc );
5689     mbedtls_md_init( &transform->md_ctx_dec );
5690 }
5691 
5692 void mbedtls_ssl_session_init( mbedtls_ssl_session *session )
5693 {
5694     memset( session, 0, sizeof(mbedtls_ssl_session) );
5695 }
5696 
5697 static int ssl_handshake_init( mbedtls_ssl_context *ssl )
5698 {
5699     /* Clear old handshake information if present */
5700     if( ssl->transform_negotiate )
5701         mbedtls_ssl_transform_free( ssl->transform_negotiate );
5702     if( ssl->session_negotiate )
5703         mbedtls_ssl_session_free( ssl->session_negotiate );
5704     if( ssl->handshake )
5705         mbedtls_ssl_handshake_free( ssl->handshake );
5706 
5707     /*
5708      * Either the pointers are now NULL or cleared properly and can be freed.
5709      * Now allocate missing structures.
5710      */
5711     if( ssl->transform_negotiate == NULL )
5712     {
5713         ssl->transform_negotiate = mbedtls_calloc( 1, sizeof(mbedtls_ssl_transform) );
5714     }
5715 
5716     if( ssl->session_negotiate == NULL )
5717     {
5718         ssl->session_negotiate = mbedtls_calloc( 1, sizeof(mbedtls_ssl_session) );
5719     }
5720 
5721     if( ssl->handshake == NULL )
5722     {
5723         ssl->handshake = mbedtls_calloc( 1, sizeof(mbedtls_ssl_handshake_params) );
5724     }
5725 
5726     /* All pointers should exist and can be directly freed without issue */
5727     if( ssl->handshake == NULL ||
5728         ssl->transform_negotiate == NULL ||
5729         ssl->session_negotiate == NULL )
5730     {
5731         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc() of ssl sub-contexts failed" ) );
5732 
5733         mbedtls_free( ssl->handshake );
5734         mbedtls_free( ssl->transform_negotiate );
5735         mbedtls_free( ssl->session_negotiate );
5736 
5737         ssl->handshake = NULL;
5738         ssl->transform_negotiate = NULL;
5739         ssl->session_negotiate = NULL;
5740 
5741         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
5742     }
5743 
5744     /* Initialize structures */
5745     mbedtls_ssl_session_init( ssl->session_negotiate );
5746     ssl_transform_init( ssl->transform_negotiate );
5747     ssl_handshake_params_init( ssl->handshake );
5748 
5749 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5750     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
5751     {
5752         ssl->handshake->alt_transform_out = ssl->transform_out;
5753 
5754         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
5755             ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_PREPARING;
5756         else
5757             ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
5758 
5759         ssl_set_timer( ssl, 0 );
5760     }
5761 #endif
5762 
5763     return( 0 );
5764 }
5765 
5766 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
5767 /* Dummy cookie callbacks for defaults */
5768 static int ssl_cookie_write_dummy( void *ctx,
5769                       unsigned char **p, unsigned char *end,
5770                       const unsigned char *cli_id, size_t cli_id_len )
5771 {
5772     ((void) ctx);
5773     ((void) p);
5774     ((void) end);
5775     ((void) cli_id);
5776     ((void) cli_id_len);
5777 
5778     return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
5779 }
5780 
5781 static int ssl_cookie_check_dummy( void *ctx,
5782                       const unsigned char *cookie, size_t cookie_len,
5783                       const unsigned char *cli_id, size_t cli_id_len )
5784 {
5785     ((void) ctx);
5786     ((void) cookie);
5787     ((void) cookie_len);
5788     ((void) cli_id);
5789     ((void) cli_id_len);
5790 
5791     return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
5792 }
5793 #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY && MBEDTLS_SSL_SRV_C */
5794 
5795 /*
5796  * Initialize an SSL context
5797  */
5798 void mbedtls_ssl_init( mbedtls_ssl_context *ssl )
5799 {
5800     memset( ssl, 0, sizeof( mbedtls_ssl_context ) );
5801 }
5802 
5803 /*
5804  * Setup an SSL context
5805  */
5806 int mbedtls_ssl_setup( mbedtls_ssl_context *ssl,
5807                        const mbedtls_ssl_config *conf )
5808 {
5809     int ret;
5810     const size_t len = MBEDTLS_SSL_BUFFER_LEN;
5811 
5812     ssl->conf = conf;
5813 
5814     /*
5815      * Prepare base structures
5816      */
5817     ssl->in_buf = NULL;
5818     ssl->out_buf = NULL;
5819     if( ( ssl-> in_buf = mbedtls_calloc( 1, len ) ) == NULL ||
5820         ( ssl->out_buf = mbedtls_calloc( 1, len ) ) == NULL )
5821     {
5822         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed", len ) );
5823         ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
5824         goto error;
5825     }
5826 
5827 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5828     if( conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
5829     {
5830         ssl->out_hdr = ssl->out_buf;
5831         ssl->out_ctr = ssl->out_buf +  3;
5832         ssl->out_len = ssl->out_buf + 11;
5833         ssl->out_iv  = ssl->out_buf + 13;
5834         ssl->out_msg = ssl->out_buf + 13;
5835 
5836         ssl->in_hdr = ssl->in_buf;
5837         ssl->in_ctr = ssl->in_buf +  3;
5838         ssl->in_len = ssl->in_buf + 11;
5839         ssl->in_iv  = ssl->in_buf + 13;
5840         ssl->in_msg = ssl->in_buf + 13;
5841     }
5842     else
5843 #endif
5844     {
5845         ssl->out_ctr = ssl->out_buf;
5846         ssl->out_hdr = ssl->out_buf +  8;
5847         ssl->out_len = ssl->out_buf + 11;
5848         ssl->out_iv  = ssl->out_buf + 13;
5849         ssl->out_msg = ssl->out_buf + 13;
5850 
5851         ssl->in_ctr = ssl->in_buf;
5852         ssl->in_hdr = ssl->in_buf +  8;
5853         ssl->in_len = ssl->in_buf + 11;
5854         ssl->in_iv  = ssl->in_buf + 13;
5855         ssl->in_msg = ssl->in_buf + 13;
5856     }
5857 
5858     if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
5859         goto error;
5860 
5861     return( 0 );
5862 
5863 error:
5864     mbedtls_free( ssl->in_buf );
5865     mbedtls_free( ssl->out_buf );
5866 
5867     ssl->conf = NULL;
5868 
5869     ssl->in_buf = NULL;
5870     ssl->out_buf = NULL;
5871 
5872     ssl->in_hdr = NULL;
5873     ssl->in_ctr = NULL;
5874     ssl->in_len = NULL;
5875     ssl->in_iv = NULL;
5876     ssl->in_msg = NULL;
5877 
5878     ssl->out_hdr = NULL;
5879     ssl->out_ctr = NULL;
5880     ssl->out_len = NULL;
5881     ssl->out_iv = NULL;
5882     ssl->out_msg = NULL;
5883 
5884     return( ret );
5885 }
5886 
5887 /*
5888  * Reset an initialized and used SSL context for re-use while retaining
5889  * all application-set variables, function pointers and data.
5890  *
5891  * If partial is non-zero, keep data in the input buffer and client ID.
5892  * (Use when a DTLS client reconnects from the same port.)
5893  */
5894 static int ssl_session_reset_int( mbedtls_ssl_context *ssl, int partial )
5895 {
5896     int ret;
5897 
5898     ssl->state = MBEDTLS_SSL_HELLO_REQUEST;
5899 
5900     /* Cancel any possibly running timer */
5901     ssl_set_timer( ssl, 0 );
5902 
5903 #if defined(MBEDTLS_SSL_RENEGOTIATION)
5904     ssl->renego_status = MBEDTLS_SSL_INITIAL_HANDSHAKE;
5905     ssl->renego_records_seen = 0;
5906 
5907     ssl->verify_data_len = 0;
5908     memset( ssl->own_verify_data, 0, MBEDTLS_SSL_VERIFY_DATA_MAX_LEN );
5909     memset( ssl->peer_verify_data, 0, MBEDTLS_SSL_VERIFY_DATA_MAX_LEN );
5910 #endif
5911     ssl->secure_renegotiation = MBEDTLS_SSL_LEGACY_RENEGOTIATION;
5912 
5913     ssl->in_offt = NULL;
5914 
5915     ssl->in_msg = ssl->in_buf + 13;
5916     ssl->in_msgtype = 0;
5917     ssl->in_msglen = 0;
5918     if( partial == 0 )
5919         ssl->in_left = 0;
5920 #if defined(MBEDTLS_SSL_PROTO_DTLS)
5921     ssl->next_record_offset = 0;
5922     ssl->in_epoch = 0;
5923 #endif
5924 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
5925     ssl_dtls_replay_reset( ssl );
5926 #endif
5927 
5928     ssl->in_hslen = 0;
5929     ssl->nb_zero = 0;
5930 
5931     ssl->keep_current_message = 0;
5932 
5933     ssl->out_msg = ssl->out_buf + 13;
5934     ssl->out_msgtype = 0;
5935     ssl->out_msglen = 0;
5936     ssl->out_left = 0;
5937 #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
5938     if( ssl->split_done != MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED )
5939         ssl->split_done = 0;
5940 #endif
5941 
5942     ssl->transform_in = NULL;
5943     ssl->transform_out = NULL;
5944 
5945     ssl->session_in = NULL;
5946     ssl->session_out = NULL;
5947 
5948     memset( ssl->out_buf, 0, MBEDTLS_SSL_BUFFER_LEN );
5949 
5950     if( partial == 0 )
5951         memset( ssl->in_buf, 0, MBEDTLS_SSL_BUFFER_LEN );
5952 
5953 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
5954     if( mbedtls_ssl_hw_record_reset != NULL )
5955     {
5956         MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_reset()" ) );
5957         if( ( ret = mbedtls_ssl_hw_record_reset( ssl ) ) != 0 )
5958         {
5959             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_reset", ret );
5960             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
5961         }
5962     }
5963 #endif
5964 
5965     if( ssl->transform )
5966     {
5967         mbedtls_ssl_transform_free( ssl->transform );
5968         mbedtls_free( ssl->transform );
5969         ssl->transform = NULL;
5970     }
5971 
5972     if( ssl->session )
5973     {
5974         mbedtls_ssl_session_free( ssl->session );
5975         mbedtls_free( ssl->session );
5976         ssl->session = NULL;
5977     }
5978 
5979 #if defined(MBEDTLS_SSL_ALPN)
5980     ssl->alpn_chosen = NULL;
5981 #endif
5982 
5983 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
5984     if( partial == 0 )
5985     {
5986         mbedtls_free( ssl->cli_id );
5987         ssl->cli_id = NULL;
5988         ssl->cli_id_len = 0;
5989     }
5990 #endif
5991 
5992     if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
5993         return( ret );
5994 
5995     return( 0 );
5996 }
5997 
5998 /*
5999  * Reset an initialized and used SSL context for re-use while retaining
6000  * all application-set variables, function pointers and data.
6001  */
6002 int mbedtls_ssl_session_reset( mbedtls_ssl_context *ssl )
6003 {
6004     return( ssl_session_reset_int( ssl, 0 ) );
6005 }
6006 
6007 /*
6008  * SSL set accessors
6009  */
6010 void mbedtls_ssl_conf_endpoint( mbedtls_ssl_config *conf, int endpoint )
6011 {
6012     conf->endpoint   = endpoint;
6013 }
6014 
6015 void mbedtls_ssl_conf_transport( mbedtls_ssl_config *conf, int transport )
6016 {
6017     conf->transport = transport;
6018 }
6019 
6020 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
6021 void mbedtls_ssl_conf_dtls_anti_replay( mbedtls_ssl_config *conf, char mode )
6022 {
6023     conf->anti_replay = mode;
6024 }
6025 #endif
6026 
6027 #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT)
6028 void mbedtls_ssl_conf_dtls_badmac_limit( mbedtls_ssl_config *conf, unsigned limit )
6029 {
6030     conf->badmac_limit = limit;
6031 }
6032 #endif
6033 
6034 #if defined(MBEDTLS_SSL_PROTO_DTLS)
6035 void mbedtls_ssl_conf_handshake_timeout( mbedtls_ssl_config *conf, uint32_t min, uint32_t max )
6036 {
6037     conf->hs_timeout_min = min;
6038     conf->hs_timeout_max = max;
6039 }
6040 #endif
6041 
6042 void mbedtls_ssl_conf_authmode( mbedtls_ssl_config *conf, int authmode )
6043 {
6044     conf->authmode   = authmode;
6045 }
6046 
6047 #if defined(MBEDTLS_X509_CRT_PARSE_C)
6048 void mbedtls_ssl_conf_verify( mbedtls_ssl_config *conf,
6049                      int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
6050                      void *p_vrfy )
6051 {
6052     conf->f_vrfy      = f_vrfy;
6053     conf->p_vrfy      = p_vrfy;
6054 }
6055 #endif /* MBEDTLS_X509_CRT_PARSE_C */
6056 
6057 void mbedtls_ssl_conf_rng( mbedtls_ssl_config *conf,
6058                   int (*f_rng)(void *, unsigned char *, size_t),
6059                   void *p_rng )
6060 {
6061     conf->f_rng      = f_rng;
6062     conf->p_rng      = p_rng;
6063 }
6064 
6065 void mbedtls_ssl_conf_dbg( mbedtls_ssl_config *conf,
6066                   void (*f_dbg)(void *, int, const char *, int, const char *),
6067                   void  *p_dbg )
6068 {
6069     conf->f_dbg      = f_dbg;
6070     conf->p_dbg      = p_dbg;
6071 }
6072 
6073 void mbedtls_ssl_set_bio( mbedtls_ssl_context *ssl,
6074         void *p_bio,
6075         mbedtls_ssl_send_t *f_send,
6076         mbedtls_ssl_recv_t *f_recv,
6077         mbedtls_ssl_recv_timeout_t *f_recv_timeout )
6078 {
6079     ssl->p_bio          = p_bio;
6080     ssl->f_send         = f_send;
6081     ssl->f_recv         = f_recv;
6082     ssl->f_recv_timeout = f_recv_timeout;
6083 }
6084 
6085 void mbedtls_ssl_conf_read_timeout( mbedtls_ssl_config *conf, uint32_t timeout )
6086 {
6087     conf->read_timeout   = timeout;
6088 }
6089 
6090 void mbedtls_ssl_set_timer_cb( mbedtls_ssl_context *ssl,
6091                                void *p_timer,
6092                                mbedtls_ssl_set_timer_t *f_set_timer,
6093                                mbedtls_ssl_get_timer_t *f_get_timer )
6094 {
6095     ssl->p_timer        = p_timer;
6096     ssl->f_set_timer    = f_set_timer;
6097     ssl->f_get_timer    = f_get_timer;
6098 
6099     /* Make sure we start with no timer running */
6100     ssl_set_timer( ssl, 0 );
6101 }
6102 
6103 #if defined(MBEDTLS_SSL_SRV_C)
6104 void mbedtls_ssl_conf_session_cache( mbedtls_ssl_config *conf,
6105         void *p_cache,
6106         int (*f_get_cache)(void *, mbedtls_ssl_session *),
6107         int (*f_set_cache)(void *, const mbedtls_ssl_session *) )
6108 {
6109     conf->p_cache = p_cache;
6110     conf->f_get_cache = f_get_cache;
6111     conf->f_set_cache = f_set_cache;
6112 }
6113 #endif /* MBEDTLS_SSL_SRV_C */
6114 
6115 #if defined(MBEDTLS_SSL_CLI_C)
6116 int mbedtls_ssl_set_session( mbedtls_ssl_context *ssl, const mbedtls_ssl_session *session )
6117 {
6118     int ret;
6119 
6120     if( ssl == NULL ||
6121         session == NULL ||
6122         ssl->session_negotiate == NULL ||
6123         ssl->conf->endpoint != MBEDTLS_SSL_IS_CLIENT )
6124     {
6125         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6126     }
6127 
6128     if( ( ret = ssl_session_copy( ssl->session_negotiate, session ) ) != 0 )
6129         return( ret );
6130 
6131     ssl->handshake->resume = 1;
6132 
6133     return( 0 );
6134 }
6135 #endif /* MBEDTLS_SSL_CLI_C */
6136 
6137 void mbedtls_ssl_conf_ciphersuites( mbedtls_ssl_config *conf,
6138                                    const int *ciphersuites )
6139 {
6140     conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] = ciphersuites;
6141     conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] = ciphersuites;
6142     conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] = ciphersuites;
6143     conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] = ciphersuites;
6144 }
6145 
6146 void mbedtls_ssl_conf_ciphersuites_for_version( mbedtls_ssl_config *conf,
6147                                        const int *ciphersuites,
6148                                        int major, int minor )
6149 {
6150     if( major != MBEDTLS_SSL_MAJOR_VERSION_3 )
6151         return;
6152 
6153     if( minor < MBEDTLS_SSL_MINOR_VERSION_0 || minor > MBEDTLS_SSL_MINOR_VERSION_3 )
6154         return;
6155 
6156     conf->ciphersuite_list[minor] = ciphersuites;
6157 }
6158 
6159 #if defined(MBEDTLS_X509_CRT_PARSE_C)
6160 void mbedtls_ssl_conf_cert_profile( mbedtls_ssl_config *conf,
6161                                     const mbedtls_x509_crt_profile *profile )
6162 {
6163     conf->cert_profile = profile;
6164 }
6165 
6166 /* Append a new keycert entry to a (possibly empty) list */
6167 static int ssl_append_key_cert( mbedtls_ssl_key_cert **head,
6168                                 mbedtls_x509_crt *cert,
6169                                 mbedtls_pk_context *key )
6170 {
6171     mbedtls_ssl_key_cert *new_cert;
6172 
6173     new_cert = mbedtls_calloc( 1, sizeof( mbedtls_ssl_key_cert ) );
6174     if( new_cert == NULL )
6175         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
6176 
6177     new_cert->cert = cert;
6178     new_cert->key  = key;
6179     new_cert->next = NULL;
6180 
6181     /* Update head is the list was null, else add to the end */
6182     if( *head == NULL )
6183     {
6184         *head = new_cert;
6185     }
6186     else
6187     {
6188         mbedtls_ssl_key_cert *cur = *head;
6189         while( cur->next != NULL )
6190             cur = cur->next;
6191         cur->next = new_cert;
6192     }
6193 
6194     return( 0 );
6195 }
6196 
6197 int mbedtls_ssl_conf_own_cert( mbedtls_ssl_config *conf,
6198                               mbedtls_x509_crt *own_cert,
6199                               mbedtls_pk_context *pk_key )
6200 {
6201     return( ssl_append_key_cert( &conf->key_cert, own_cert, pk_key ) );
6202 }
6203 
6204 void mbedtls_ssl_conf_ca_chain( mbedtls_ssl_config *conf,
6205                                mbedtls_x509_crt *ca_chain,
6206                                mbedtls_x509_crl *ca_crl )
6207 {
6208     conf->ca_chain   = ca_chain;
6209     conf->ca_crl     = ca_crl;
6210 }
6211 #endif /* MBEDTLS_X509_CRT_PARSE_C */
6212 
6213 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
6214 int mbedtls_ssl_set_hs_own_cert( mbedtls_ssl_context *ssl,
6215                                  mbedtls_x509_crt *own_cert,
6216                                  mbedtls_pk_context *pk_key )
6217 {
6218     return( ssl_append_key_cert( &ssl->handshake->sni_key_cert,
6219                                  own_cert, pk_key ) );
6220 }
6221 
6222 void mbedtls_ssl_set_hs_ca_chain( mbedtls_ssl_context *ssl,
6223                                   mbedtls_x509_crt *ca_chain,
6224                                   mbedtls_x509_crl *ca_crl )
6225 {
6226     ssl->handshake->sni_ca_chain   = ca_chain;
6227     ssl->handshake->sni_ca_crl     = ca_crl;
6228 }
6229 
6230 void mbedtls_ssl_set_hs_authmode( mbedtls_ssl_context *ssl,
6231                                   int authmode )
6232 {
6233     ssl->handshake->sni_authmode = authmode;
6234 }
6235 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
6236 
6237 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
6238 /*
6239  * Set EC J-PAKE password for current handshake
6240  */
6241 int mbedtls_ssl_set_hs_ecjpake_password( mbedtls_ssl_context *ssl,
6242                                          const unsigned char *pw,
6243                                          size_t pw_len )
6244 {
6245     mbedtls_ecjpake_role role;
6246 
6247     if( ssl->handshake == NULL || ssl->conf == NULL )
6248         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6249 
6250     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
6251         role = MBEDTLS_ECJPAKE_SERVER;
6252     else
6253         role = MBEDTLS_ECJPAKE_CLIENT;
6254 
6255     return( mbedtls_ecjpake_setup( &ssl->handshake->ecjpake_ctx,
6256                                    role,
6257                                    MBEDTLS_MD_SHA256,
6258                                    MBEDTLS_ECP_DP_SECP256R1,
6259                                    pw, pw_len ) );
6260 }
6261 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
6262 
6263 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
6264 int mbedtls_ssl_conf_psk( mbedtls_ssl_config *conf,
6265                 const unsigned char *psk, size_t psk_len,
6266                 const unsigned char *psk_identity, size_t psk_identity_len )
6267 {
6268     if( psk == NULL || psk_identity == NULL )
6269         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6270 
6271     if( psk_len > MBEDTLS_PSK_MAX_LEN )
6272         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6273 
6274     /* Identity len will be encoded on two bytes */
6275     if( ( psk_identity_len >> 16 ) != 0 ||
6276         psk_identity_len > MBEDTLS_SSL_MAX_CONTENT_LEN )
6277     {
6278         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6279     }
6280 
6281     if( conf->psk != NULL )
6282     {
6283         mbedtls_zeroize( conf->psk, conf->psk_len );
6284 
6285         mbedtls_free( conf->psk );
6286         conf->psk = NULL;
6287         conf->psk_len = 0;
6288     }
6289     if( conf->psk_identity != NULL )
6290     {
6291         mbedtls_free( conf->psk_identity );
6292         conf->psk_identity = NULL;
6293         conf->psk_identity_len = 0;
6294     }
6295 
6296     if( ( conf->psk = mbedtls_calloc( 1, psk_len ) ) == NULL ||
6297         ( conf->psk_identity = mbedtls_calloc( 1, psk_identity_len ) ) == NULL )
6298     {
6299         mbedtls_free( conf->psk );
6300         mbedtls_free( conf->psk_identity );
6301         conf->psk = NULL;
6302         conf->psk_identity = NULL;
6303         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
6304     }
6305 
6306     conf->psk_len = psk_len;
6307     conf->psk_identity_len = psk_identity_len;
6308 
6309     memcpy( conf->psk, psk, conf->psk_len );
6310     memcpy( conf->psk_identity, psk_identity, conf->psk_identity_len );
6311 
6312     return( 0 );
6313 }
6314 
6315 int mbedtls_ssl_set_hs_psk( mbedtls_ssl_context *ssl,
6316                             const unsigned char *psk, size_t psk_len )
6317 {
6318     if( psk == NULL || ssl->handshake == NULL )
6319         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6320 
6321     if( psk_len > MBEDTLS_PSK_MAX_LEN )
6322         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6323 
6324     if( ssl->handshake->psk != NULL )
6325     {
6326         mbedtls_zeroize( ssl->handshake->psk, ssl->handshake->psk_len );
6327         mbedtls_free( ssl->handshake->psk );
6328         ssl->handshake->psk_len = 0;
6329     }
6330 
6331     if( ( ssl->handshake->psk = mbedtls_calloc( 1, psk_len ) ) == NULL )
6332         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
6333 
6334     ssl->handshake->psk_len = psk_len;
6335     memcpy( ssl->handshake->psk, psk, ssl->handshake->psk_len );
6336 
6337     return( 0 );
6338 }
6339 
6340 void mbedtls_ssl_conf_psk_cb( mbedtls_ssl_config *conf,
6341                      int (*f_psk)(void *, mbedtls_ssl_context *, const unsigned char *,
6342                      size_t),
6343                      void *p_psk )
6344 {
6345     conf->f_psk = f_psk;
6346     conf->p_psk = p_psk;
6347 }
6348 #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
6349 
6350 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
6351 
6352 #if !defined(MBEDTLS_DEPRECATED_REMOVED)
6353 int mbedtls_ssl_conf_dh_param( mbedtls_ssl_config *conf, const char *dhm_P, const char *dhm_G )
6354 {
6355     int ret;
6356 
6357     if( ( ret = mbedtls_mpi_read_string( &conf->dhm_P, 16, dhm_P ) ) != 0 ||
6358         ( ret = mbedtls_mpi_read_string( &conf->dhm_G, 16, dhm_G ) ) != 0 )
6359     {
6360         mbedtls_mpi_free( &conf->dhm_P );
6361         mbedtls_mpi_free( &conf->dhm_G );
6362         return( ret );
6363     }
6364 
6365     return( 0 );
6366 }
6367 #endif /* MBEDTLS_DEPRECATED_REMOVED */
6368 
6369 int mbedtls_ssl_conf_dh_param_bin( mbedtls_ssl_config *conf,
6370                                    const unsigned char *dhm_P, size_t P_len,
6371                                    const unsigned char *dhm_G, size_t G_len )
6372 {
6373     int ret;
6374 
6375     if( ( ret = mbedtls_mpi_read_binary( &conf->dhm_P, dhm_P, P_len ) ) != 0 ||
6376         ( ret = mbedtls_mpi_read_binary( &conf->dhm_G, dhm_G, G_len ) ) != 0 )
6377     {
6378         mbedtls_mpi_free( &conf->dhm_P );
6379         mbedtls_mpi_free( &conf->dhm_G );
6380         return( ret );
6381     }
6382 
6383     return( 0 );
6384 }
6385 
6386 int mbedtls_ssl_conf_dh_param_ctx( mbedtls_ssl_config *conf, mbedtls_dhm_context *dhm_ctx )
6387 {
6388     int ret;
6389 
6390     if( ( ret = mbedtls_mpi_copy( &conf->dhm_P, &dhm_ctx->P ) ) != 0 ||
6391         ( ret = mbedtls_mpi_copy( &conf->dhm_G, &dhm_ctx->G ) ) != 0 )
6392     {
6393         mbedtls_mpi_free( &conf->dhm_P );
6394         mbedtls_mpi_free( &conf->dhm_G );
6395         return( ret );
6396     }
6397 
6398     return( 0 );
6399 }
6400 #endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_SRV_C */
6401 
6402 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C)
6403 /*
6404  * Set the minimum length for Diffie-Hellman parameters
6405  */
6406 void mbedtls_ssl_conf_dhm_min_bitlen( mbedtls_ssl_config *conf,
6407                                       unsigned int bitlen )
6408 {
6409     conf->dhm_min_bitlen = bitlen;
6410 }
6411 #endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_CLI_C */
6412 
6413 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
6414 /*
6415  * Set allowed/preferred hashes for handshake signatures
6416  */
6417 void mbedtls_ssl_conf_sig_hashes( mbedtls_ssl_config *conf,
6418                                   const int *hashes )
6419 {
6420     conf->sig_hashes = hashes;
6421 }
6422 #endif /* MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
6423 
6424 #if defined(MBEDTLS_ECP_C)
6425 /*
6426  * Set the allowed elliptic curves
6427  */
6428 void mbedtls_ssl_conf_curves( mbedtls_ssl_config *conf,
6429                              const mbedtls_ecp_group_id *curve_list )
6430 {
6431     conf->curve_list = curve_list;
6432 }
6433 #endif /* MBEDTLS_ECP_C */
6434 
6435 #if defined(MBEDTLS_X509_CRT_PARSE_C)
6436 int mbedtls_ssl_set_hostname( mbedtls_ssl_context *ssl, const char *hostname )
6437 {
6438     /* Initialize to suppress unnecessary compiler warning */
6439     size_t hostname_len = 0;
6440 
6441     /* Check if new hostname is valid before
6442      * making any change to current one */
6443     if( hostname != NULL )
6444     {
6445         hostname_len = strlen( hostname );
6446 
6447         if( hostname_len > MBEDTLS_SSL_MAX_HOST_NAME_LEN )
6448             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6449     }
6450 
6451     /* Now it's clear that we will overwrite the old hostname,
6452      * so we can free it safely */
6453 
6454     if( ssl->hostname != NULL )
6455     {
6456         mbedtls_zeroize( ssl->hostname, strlen( ssl->hostname ) );
6457         mbedtls_free( ssl->hostname );
6458     }
6459 
6460     /* Passing NULL as hostname shall clear the old one */
6461 
6462     if( hostname == NULL )
6463     {
6464         ssl->hostname = NULL;
6465     }
6466     else
6467     {
6468         ssl->hostname = mbedtls_calloc( 1, hostname_len + 1 );
6469         if( ssl->hostname == NULL )
6470             return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
6471 
6472         memcpy( ssl->hostname, hostname, hostname_len );
6473 
6474         ssl->hostname[hostname_len] = '\0';
6475     }
6476 
6477     return( 0 );
6478 }
6479 #endif /* MBEDTLS_X509_CRT_PARSE_C */
6480 
6481 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
6482 void mbedtls_ssl_conf_sni( mbedtls_ssl_config *conf,
6483                   int (*f_sni)(void *, mbedtls_ssl_context *,
6484                                 const unsigned char *, size_t),
6485                   void *p_sni )
6486 {
6487     conf->f_sni = f_sni;
6488     conf->p_sni = p_sni;
6489 }
6490 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
6491 
6492 #if defined(MBEDTLS_SSL_ALPN)
6493 int mbedtls_ssl_conf_alpn_protocols( mbedtls_ssl_config *conf, const char **protos )
6494 {
6495     size_t cur_len, tot_len;
6496     const char **p;
6497 
6498     /*
6499      * RFC 7301 3.1: "Empty strings MUST NOT be included and byte strings
6500      * MUST NOT be truncated."
6501      * We check lengths now rather than later.
6502      */
6503     tot_len = 0;
6504     for( p = protos; *p != NULL; p++ )
6505     {
6506         cur_len = strlen( *p );
6507         tot_len += cur_len;
6508 
6509         if( cur_len == 0 || cur_len > 255 || tot_len > 65535 )
6510             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6511     }
6512 
6513     conf->alpn_list = protos;
6514 
6515     return( 0 );
6516 }
6517 
6518 const char *mbedtls_ssl_get_alpn_protocol( const mbedtls_ssl_context *ssl )
6519 {
6520     return( ssl->alpn_chosen );
6521 }
6522 #endif /* MBEDTLS_SSL_ALPN */
6523 
6524 void mbedtls_ssl_conf_max_version( mbedtls_ssl_config *conf, int major, int minor )
6525 {
6526     conf->max_major_ver = major;
6527     conf->max_minor_ver = minor;
6528 }
6529 
6530 void mbedtls_ssl_conf_min_version( mbedtls_ssl_config *conf, int major, int minor )
6531 {
6532     conf->min_major_ver = major;
6533     conf->min_minor_ver = minor;
6534 }
6535 
6536 #if defined(MBEDTLS_SSL_FALLBACK_SCSV) && defined(MBEDTLS_SSL_CLI_C)
6537 void mbedtls_ssl_conf_fallback( mbedtls_ssl_config *conf, char fallback )
6538 {
6539     conf->fallback = fallback;
6540 }
6541 #endif
6542 
6543 #if defined(MBEDTLS_SSL_SRV_C)
6544 void mbedtls_ssl_conf_cert_req_ca_list( mbedtls_ssl_config *conf,
6545                                           char cert_req_ca_list )
6546 {
6547     conf->cert_req_ca_list = cert_req_ca_list;
6548 }
6549 #endif
6550 
6551 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
6552 void mbedtls_ssl_conf_encrypt_then_mac( mbedtls_ssl_config *conf, char etm )
6553 {
6554     conf->encrypt_then_mac = etm;
6555 }
6556 #endif
6557 
6558 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
6559 void mbedtls_ssl_conf_extended_master_secret( mbedtls_ssl_config *conf, char ems )
6560 {
6561     conf->extended_ms = ems;
6562 }
6563 #endif
6564 
6565 #if defined(MBEDTLS_ARC4_C)
6566 void mbedtls_ssl_conf_arc4_support( mbedtls_ssl_config *conf, char arc4 )
6567 {
6568     conf->arc4_disabled = arc4;
6569 }
6570 #endif
6571 
6572 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
6573 int mbedtls_ssl_conf_max_frag_len( mbedtls_ssl_config *conf, unsigned char mfl_code )
6574 {
6575     if( mfl_code >= MBEDTLS_SSL_MAX_FRAG_LEN_INVALID ||
6576         mfl_code_to_length[mfl_code] > MBEDTLS_SSL_MAX_CONTENT_LEN )
6577     {
6578         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6579     }
6580 
6581     conf->mfl_code = mfl_code;
6582 
6583     return( 0 );
6584 }
6585 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
6586 
6587 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
6588 void mbedtls_ssl_conf_truncated_hmac( mbedtls_ssl_config *conf, int truncate )
6589 {
6590     conf->trunc_hmac = truncate;
6591 }
6592 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
6593 
6594 #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
6595 void mbedtls_ssl_conf_cbc_record_splitting( mbedtls_ssl_config *conf, char split )
6596 {
6597     conf->cbc_record_splitting = split;
6598 }
6599 #endif
6600 
6601 void mbedtls_ssl_conf_legacy_renegotiation( mbedtls_ssl_config *conf, int allow_legacy )
6602 {
6603     conf->allow_legacy_renegotiation = allow_legacy;
6604 }
6605 
6606 #if defined(MBEDTLS_SSL_RENEGOTIATION)
6607 void mbedtls_ssl_conf_renegotiation( mbedtls_ssl_config *conf, int renegotiation )
6608 {
6609     conf->disable_renegotiation = renegotiation;
6610 }
6611 
6612 void mbedtls_ssl_conf_renegotiation_enforced( mbedtls_ssl_config *conf, int max_records )
6613 {
6614     conf->renego_max_records = max_records;
6615 }
6616 
6617 void mbedtls_ssl_conf_renegotiation_period( mbedtls_ssl_config *conf,
6618                                    const unsigned char period[8] )
6619 {
6620     memcpy( conf->renego_period, period, 8 );
6621 }
6622 #endif /* MBEDTLS_SSL_RENEGOTIATION */
6623 
6624 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
6625 #if defined(MBEDTLS_SSL_CLI_C)
6626 void mbedtls_ssl_conf_session_tickets( mbedtls_ssl_config *conf, int use_tickets )
6627 {
6628     conf->session_tickets = use_tickets;
6629 }
6630 #endif
6631 
6632 #if defined(MBEDTLS_SSL_SRV_C)
6633 void mbedtls_ssl_conf_session_tickets_cb( mbedtls_ssl_config *conf,
6634         mbedtls_ssl_ticket_write_t *f_ticket_write,
6635         mbedtls_ssl_ticket_parse_t *f_ticket_parse,
6636         void *p_ticket )
6637 {
6638     conf->f_ticket_write = f_ticket_write;
6639     conf->f_ticket_parse = f_ticket_parse;
6640     conf->p_ticket       = p_ticket;
6641 }
6642 #endif
6643 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
6644 
6645 #if defined(MBEDTLS_SSL_EXPORT_KEYS)
6646 void mbedtls_ssl_conf_export_keys_cb( mbedtls_ssl_config *conf,
6647         mbedtls_ssl_export_keys_t *f_export_keys,
6648         void *p_export_keys )
6649 {
6650     conf->f_export_keys = f_export_keys;
6651     conf->p_export_keys = p_export_keys;
6652 }
6653 #endif
6654 
6655 /*
6656  * SSL get accessors
6657  */
6658 size_t mbedtls_ssl_get_bytes_avail( const mbedtls_ssl_context *ssl )
6659 {
6660     return( ssl->in_offt == NULL ? 0 : ssl->in_msglen );
6661 }
6662 
6663 uint32_t mbedtls_ssl_get_verify_result( const mbedtls_ssl_context *ssl )
6664 {
6665     if( ssl->session != NULL )
6666         return( ssl->session->verify_result );
6667 
6668     if( ssl->session_negotiate != NULL )
6669         return( ssl->session_negotiate->verify_result );
6670 
6671     return( 0xFFFFFFFF );
6672 }
6673 
6674 const char *mbedtls_ssl_get_ciphersuite( const mbedtls_ssl_context *ssl )
6675 {
6676     if( ssl == NULL || ssl->session == NULL )
6677         return( NULL );
6678 
6679     return mbedtls_ssl_get_ciphersuite_name( ssl->session->ciphersuite );
6680 }
6681 
6682 const char *mbedtls_ssl_get_version( const mbedtls_ssl_context *ssl )
6683 {
6684 #if defined(MBEDTLS_SSL_PROTO_DTLS)
6685     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
6686     {
6687         switch( ssl->minor_ver )
6688         {
6689             case MBEDTLS_SSL_MINOR_VERSION_2:
6690                 return( "DTLSv1.0" );
6691 
6692             case MBEDTLS_SSL_MINOR_VERSION_3:
6693                 return( "DTLSv1.2" );
6694 
6695             default:
6696                 return( "unknown (DTLS)" );
6697         }
6698     }
6699 #endif
6700 
6701     switch( ssl->minor_ver )
6702     {
6703         case MBEDTLS_SSL_MINOR_VERSION_0:
6704             return( "SSLv3.0" );
6705 
6706         case MBEDTLS_SSL_MINOR_VERSION_1:
6707             return( "TLSv1.0" );
6708 
6709         case MBEDTLS_SSL_MINOR_VERSION_2:
6710             return( "TLSv1.1" );
6711 
6712         case MBEDTLS_SSL_MINOR_VERSION_3:
6713             return( "TLSv1.2" );
6714 
6715         default:
6716             return( "unknown" );
6717     }
6718 }
6719 
6720 int mbedtls_ssl_get_record_expansion( const mbedtls_ssl_context *ssl )
6721 {
6722     size_t transform_expansion = 0;
6723     const mbedtls_ssl_transform *transform = ssl->transform_out;
6724     unsigned block_size;
6725 
6726     if( transform == NULL )
6727         return( (int) mbedtls_ssl_hdr_len( ssl ) );
6728 
6729 #if defined(MBEDTLS_ZLIB_SUPPORT)
6730     if( ssl->session_out->compression != MBEDTLS_SSL_COMPRESS_NULL )
6731         return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
6732 #endif
6733 
6734     switch( mbedtls_cipher_get_cipher_mode( &transform->cipher_ctx_enc ) )
6735     {
6736         case MBEDTLS_MODE_GCM:
6737         case MBEDTLS_MODE_CCM:
6738         case MBEDTLS_MODE_STREAM:
6739             transform_expansion = transform->minlen;
6740             break;
6741 
6742         case MBEDTLS_MODE_CBC:
6743 
6744             block_size = mbedtls_cipher_get_block_size(
6745                 &transform->cipher_ctx_enc );
6746 
6747             /* Expansion due to the addition of the MAC. */
6748             transform_expansion += transform->maclen;
6749 
6750             /* Expansion due to the addition of CBC padding;
6751              * Theoretically up to 256 bytes, but we never use
6752              * more than the block size of the underlying cipher. */
6753             transform_expansion += block_size;
6754 
6755             /* For TLS 1.1 or higher, an explicit IV is added
6756              * after the record header. */
6757 #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
6758             if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
6759                 transform_expansion += block_size;
6760 #endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */
6761 
6762             break;
6763 
6764         default:
6765             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
6766             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
6767     }
6768 
6769     return( (int)( mbedtls_ssl_hdr_len( ssl ) + transform_expansion ) );
6770 }
6771 
6772 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
6773 size_t mbedtls_ssl_get_max_frag_len( const mbedtls_ssl_context *ssl )
6774 {
6775     size_t max_len;
6776 
6777     /*
6778      * Assume mfl_code is correct since it was checked when set
6779      */
6780     max_len = mfl_code_to_length[ssl->conf->mfl_code];
6781 
6782     /*
6783      * Check if a smaller max length was negotiated
6784      */
6785     if( ssl->session_out != NULL &&
6786         mfl_code_to_length[ssl->session_out->mfl_code] < max_len )
6787     {
6788         max_len = mfl_code_to_length[ssl->session_out->mfl_code];
6789     }
6790 
6791     return max_len;
6792 }
6793 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
6794 
6795 #if defined(MBEDTLS_X509_CRT_PARSE_C)
6796 const mbedtls_x509_crt *mbedtls_ssl_get_peer_cert( const mbedtls_ssl_context *ssl )
6797 {
6798     if( ssl == NULL || ssl->session == NULL )
6799         return( NULL );
6800 
6801     return( ssl->session->peer_cert );
6802 }
6803 #endif /* MBEDTLS_X509_CRT_PARSE_C */
6804 
6805 #if defined(MBEDTLS_SSL_CLI_C)
6806 int mbedtls_ssl_get_session( const mbedtls_ssl_context *ssl, mbedtls_ssl_session *dst )
6807 {
6808     if( ssl == NULL ||
6809         dst == NULL ||
6810         ssl->session == NULL ||
6811         ssl->conf->endpoint != MBEDTLS_SSL_IS_CLIENT )
6812     {
6813         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6814     }
6815 
6816     return( ssl_session_copy( dst, ssl->session ) );
6817 }
6818 #endif /* MBEDTLS_SSL_CLI_C */
6819 
6820 /*
6821  * Perform a single step of the SSL handshake
6822  */
6823 int mbedtls_ssl_handshake_step( mbedtls_ssl_context *ssl )
6824 {
6825     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
6826 
6827     if( ssl == NULL || ssl->conf == NULL )
6828         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6829 
6830 #if defined(MBEDTLS_SSL_CLI_C)
6831     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
6832         ret = mbedtls_ssl_handshake_client_step( ssl );
6833 #endif
6834 #if defined(MBEDTLS_SSL_SRV_C)
6835     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
6836         ret = mbedtls_ssl_handshake_server_step( ssl );
6837 #endif
6838 
6839     return( ret );
6840 }
6841 
6842 /*
6843  * Perform the SSL handshake
6844  */
6845 int mbedtls_ssl_handshake( mbedtls_ssl_context *ssl )
6846 {
6847     int ret = 0;
6848 
6849     if( ssl == NULL || ssl->conf == NULL )
6850         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6851 
6852     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> handshake" ) );
6853 
6854     while( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
6855     {
6856         ret = mbedtls_ssl_handshake_step( ssl );
6857 
6858         if( ret != 0 )
6859             break;
6860     }
6861 
6862     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= handshake" ) );
6863 
6864     return( ret );
6865 }
6866 
6867 #if defined(MBEDTLS_SSL_RENEGOTIATION)
6868 #if defined(MBEDTLS_SSL_SRV_C)
6869 /*
6870  * Write HelloRequest to request renegotiation on server
6871  */
6872 static int ssl_write_hello_request( mbedtls_ssl_context *ssl )
6873 {
6874     int ret;
6875 
6876     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write hello request" ) );
6877 
6878     ssl->out_msglen  = 4;
6879     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
6880     ssl->out_msg[0]  = MBEDTLS_SSL_HS_HELLO_REQUEST;
6881 
6882     if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
6883     {
6884         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
6885         return( ret );
6886     }
6887 
6888     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write hello request" ) );
6889 
6890     return( 0 );
6891 }
6892 #endif /* MBEDTLS_SSL_SRV_C */
6893 
6894 /*
6895  * Actually renegotiate current connection, triggered by either:
6896  * - any side: calling mbedtls_ssl_renegotiate(),
6897  * - client: receiving a HelloRequest during mbedtls_ssl_read(),
6898  * - server: receiving any handshake message on server during mbedtls_ssl_read() after
6899  *   the initial handshake is completed.
6900  * If the handshake doesn't complete due to waiting for I/O, it will continue
6901  * during the next calls to mbedtls_ssl_renegotiate() or mbedtls_ssl_read() respectively.
6902  */
6903 static int ssl_start_renegotiation( mbedtls_ssl_context *ssl )
6904 {
6905     int ret;
6906 
6907     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> renegotiate" ) );
6908 
6909     if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
6910         return( ret );
6911 
6912     /* RFC 6347 4.2.2: "[...] the HelloRequest will have message_seq = 0 and
6913      * the ServerHello will have message_seq = 1" */
6914 #if defined(MBEDTLS_SSL_PROTO_DTLS)
6915     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
6916         ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
6917     {
6918         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
6919             ssl->handshake->out_msg_seq = 1;
6920         else
6921             ssl->handshake->in_msg_seq = 1;
6922     }
6923 #endif
6924 
6925     ssl->state = MBEDTLS_SSL_HELLO_REQUEST;
6926     ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS;
6927 
6928     if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 )
6929     {
6930         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
6931         return( ret );
6932     }
6933 
6934     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= renegotiate" ) );
6935 
6936     return( 0 );
6937 }
6938 
6939 /*
6940  * Renegotiate current connection on client,
6941  * or request renegotiation on server
6942  */
6943 int mbedtls_ssl_renegotiate( mbedtls_ssl_context *ssl )
6944 {
6945     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
6946 
6947     if( ssl == NULL || ssl->conf == NULL )
6948         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6949 
6950 #if defined(MBEDTLS_SSL_SRV_C)
6951     /* On server, just send the request */
6952     if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
6953     {
6954         if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
6955             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6956 
6957         ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_PENDING;
6958 
6959         /* Did we already try/start sending HelloRequest? */
6960         if( ssl->out_left != 0 )
6961             return( mbedtls_ssl_flush_output( ssl ) );
6962 
6963         return( ssl_write_hello_request( ssl ) );
6964     }
6965 #endif /* MBEDTLS_SSL_SRV_C */
6966 
6967 #if defined(MBEDTLS_SSL_CLI_C)
6968     /*
6969      * On client, either start the renegotiation process or,
6970      * if already in progress, continue the handshake
6971      */
6972     if( ssl->renego_status != MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
6973     {
6974         if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
6975             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
6976 
6977         if( ( ret = ssl_start_renegotiation( ssl ) ) != 0 )
6978         {
6979             MBEDTLS_SSL_DEBUG_RET( 1, "ssl_start_renegotiation", ret );
6980             return( ret );
6981         }
6982     }
6983     else
6984     {
6985         if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 )
6986         {
6987             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
6988             return( ret );
6989         }
6990     }
6991 #endif /* MBEDTLS_SSL_CLI_C */
6992 
6993     return( ret );
6994 }
6995 
6996 /*
6997  * Check record counters and renegotiate if they're above the limit.
6998  */
6999 static int ssl_check_ctr_renegotiate( mbedtls_ssl_context *ssl )
7000 {
7001     size_t ep_len = ssl_ep_len( ssl );
7002     int in_ctr_cmp;
7003     int out_ctr_cmp;
7004 
7005     if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ||
7006         ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING ||
7007         ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED )
7008     {
7009         return( 0 );
7010     }
7011 
7012     in_ctr_cmp = memcmp( ssl->in_ctr + ep_len,
7013                         ssl->conf->renego_period + ep_len, 8 - ep_len );
7014     out_ctr_cmp = memcmp( ssl->out_ctr + ep_len,
7015                           ssl->conf->renego_period + ep_len, 8 - ep_len );
7016 
7017     if( in_ctr_cmp <= 0 && out_ctr_cmp <= 0 )
7018     {
7019         return( 0 );
7020     }
7021 
7022     MBEDTLS_SSL_DEBUG_MSG( 1, ( "record counter limit reached: renegotiate" ) );
7023     return( mbedtls_ssl_renegotiate( ssl ) );
7024 }
7025 #endif /* MBEDTLS_SSL_RENEGOTIATION */
7026 
7027 /*
7028  * Receive application data decrypted from the SSL layer
7029  */
7030 int mbedtls_ssl_read( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len )
7031 {
7032     int ret;
7033     size_t n;
7034 
7035     if( ssl == NULL || ssl->conf == NULL )
7036         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
7037 
7038     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> read" ) );
7039 
7040 #if defined(MBEDTLS_SSL_PROTO_DTLS)
7041     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
7042     {
7043         if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
7044             return( ret );
7045 
7046         if( ssl->handshake != NULL &&
7047             ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING )
7048         {
7049             if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )
7050                 return( ret );
7051         }
7052     }
7053 #endif
7054 
7055     /*
7056      * Check if renegotiation is necessary and/or handshake is
7057      * in process. If yes, perform/continue, and fall through
7058      * if an unexpected packet is received while the client
7059      * is waiting for the ServerHello.
7060      *
7061      * (There is no equivalent to the last condition on
7062      *  the server-side as it is not treated as within
7063      *  a handshake while waiting for the ClientHello
7064      *  after a renegotiation request.)
7065      */
7066 
7067 #if defined(MBEDTLS_SSL_RENEGOTIATION)
7068     ret = ssl_check_ctr_renegotiate( ssl );
7069     if( ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO &&
7070         ret != 0 )
7071     {
7072         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_check_ctr_renegotiate", ret );
7073         return( ret );
7074     }
7075 #endif
7076 
7077     if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
7078     {
7079         ret = mbedtls_ssl_handshake( ssl );
7080         if( ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO &&
7081             ret != 0 )
7082         {
7083             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
7084             return( ret );
7085         }
7086     }
7087 
7088     if( ssl->in_offt == NULL )
7089     {
7090         /* Start timer if not already running */
7091         if( ssl->f_get_timer != NULL &&
7092             ssl->f_get_timer( ssl->p_timer ) == -1 )
7093         {
7094             ssl_set_timer( ssl, ssl->conf->read_timeout );
7095         }
7096 
7097         if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
7098         {
7099             if( ret == MBEDTLS_ERR_SSL_CONN_EOF )
7100                 return( 0 );
7101 
7102             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
7103             return( ret );
7104         }
7105 
7106         if( ssl->in_msglen  == 0 &&
7107             ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA )
7108         {
7109             /*
7110              * OpenSSL sends empty messages to randomize the IV
7111              */
7112             if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
7113             {
7114                 if( ret == MBEDTLS_ERR_SSL_CONN_EOF )
7115                     return( 0 );
7116 
7117                 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
7118                 return( ret );
7119             }
7120         }
7121 
7122         if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE )
7123         {
7124             MBEDTLS_SSL_DEBUG_MSG( 1, ( "received handshake message" ) );
7125 
7126             /*
7127              * - For client-side, expect SERVER_HELLO_REQUEST.
7128              * - For server-side, expect CLIENT_HELLO.
7129              * - Fail (TLS) or silently drop record (DTLS) in other cases.
7130              */
7131 
7132 #if defined(MBEDTLS_SSL_CLI_C)
7133             if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&
7134                 ( ssl->in_msg[0] != MBEDTLS_SSL_HS_HELLO_REQUEST ||
7135                   ssl->in_hslen  != mbedtls_ssl_hs_hdr_len( ssl ) ) )
7136             {
7137                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake received (not HelloRequest)" ) );
7138 
7139                 /* With DTLS, drop the packet (probably from last handshake) */
7140 #if defined(MBEDTLS_SSL_PROTO_DTLS)
7141                 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
7142                     return( MBEDTLS_ERR_SSL_WANT_READ );
7143 #endif
7144                 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
7145             }
7146 #endif /* MBEDTLS_SSL_CLI_C */
7147 
7148 #if defined(MBEDTLS_SSL_SRV_C)
7149             if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
7150                 ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_HELLO )
7151             {
7152                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake received (not ClientHello)" ) );
7153 
7154                 /* With DTLS, drop the packet (probably from last handshake) */
7155 #if defined(MBEDTLS_SSL_PROTO_DTLS)
7156                 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
7157                     return( MBEDTLS_ERR_SSL_WANT_READ );
7158 #endif
7159                 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
7160             }
7161 #endif /* MBEDTLS_SSL_SRV_C */
7162 
7163 #if defined(MBEDTLS_SSL_RENEGOTIATION)
7164             /* Determine whether renegotiation attempt should be accepted */
7165             if( ! ( ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED ||
7166                     ( ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
7167                       ssl->conf->allow_legacy_renegotiation ==
7168                                                    MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION ) ) )
7169             {
7170                 /*
7171                  * Accept renegotiation request
7172                  */
7173 
7174                 /* DTLS clients need to know renego is server-initiated */
7175 #if defined(MBEDTLS_SSL_PROTO_DTLS)
7176                 if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
7177                     ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
7178                 {
7179                     ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_PENDING;
7180                 }
7181 #endif
7182                 ret = ssl_start_renegotiation( ssl );
7183                 if( ret != MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO &&
7184                     ret != 0 )
7185                 {
7186                     MBEDTLS_SSL_DEBUG_RET( 1, "ssl_start_renegotiation", ret );
7187                     return( ret );
7188                 }
7189             }
7190             else
7191 #endif /* MBEDTLS_SSL_RENEGOTIATION */
7192             {
7193                 /*
7194                  * Refuse renegotiation
7195                  */
7196 
7197                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "refusing renegotiation, sending alert" ) );
7198 
7199 #if defined(MBEDTLS_SSL_PROTO_SSL3)
7200                 if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
7201                 {
7202                     /* SSLv3 does not have a "no_renegotiation" warning, so
7203                        we send a fatal alert and abort the connection. */
7204                     mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
7205                                                     MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
7206                     return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
7207                 }
7208                 else
7209 #endif /* MBEDTLS_SSL_PROTO_SSL3 */
7210 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
7211     defined(MBEDTLS_SSL_PROTO_TLS1_2)
7212                 if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 )
7213                 {
7214                     if( ( ret = mbedtls_ssl_send_alert_message( ssl,
7215                                     MBEDTLS_SSL_ALERT_LEVEL_WARNING,
7216                                     MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION ) ) != 0 )
7217                     {
7218                         return( ret );
7219                     }
7220                 }
7221                 else
7222 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 ||
7223           MBEDTLS_SSL_PROTO_TLS1_2 */
7224                 {
7225                     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
7226                     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
7227                 }
7228             }
7229 
7230             return( MBEDTLS_ERR_SSL_WANT_READ );
7231         }
7232 #if defined(MBEDTLS_SSL_RENEGOTIATION)
7233         else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
7234         {
7235             if( ssl->conf->renego_max_records >= 0 )
7236             {
7237                 if( ++ssl->renego_records_seen > ssl->conf->renego_max_records )
7238                 {
7239                     MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation requested, "
7240                                         "but not honored by client" ) );
7241                     return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
7242                 }
7243             }
7244         }
7245 #endif /* MBEDTLS_SSL_RENEGOTIATION */
7246 
7247         /* Fatal and closure alerts handled by mbedtls_ssl_read_record() */
7248         if( ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT )
7249         {
7250             MBEDTLS_SSL_DEBUG_MSG( 2, ( "ignoring non-fatal non-closure alert" ) );
7251             return( MBEDTLS_ERR_SSL_WANT_READ );
7252         }
7253 
7254         if( ssl->in_msgtype != MBEDTLS_SSL_MSG_APPLICATION_DATA )
7255         {
7256             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad application data message" ) );
7257             return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
7258         }
7259 
7260         ssl->in_offt = ssl->in_msg;
7261 
7262         /* We're going to return something now, cancel timer,
7263          * except if handshake (renegotiation) is in progress */
7264         if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )
7265             ssl_set_timer( ssl, 0 );
7266 
7267 #if defined(MBEDTLS_SSL_PROTO_DTLS)
7268         /* If we requested renego but received AppData, resend HelloRequest.
7269          * Do it now, after setting in_offt, to avoid taking this branch
7270          * again if ssl_write_hello_request() returns WANT_WRITE */
7271 #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
7272         if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER &&
7273             ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING )
7274         {
7275             if( ( ret = ssl_resend_hello_request( ssl ) ) != 0 )
7276             {
7277                 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_resend_hello_request", ret );
7278                 return( ret );
7279             }
7280         }
7281 #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
7282 #endif /* MBEDTLS_SSL_PROTO_DTLS */
7283     }
7284 
7285     n = ( len < ssl->in_msglen )
7286         ? len : ssl->in_msglen;
7287 
7288     memcpy( buf, ssl->in_offt, n );
7289     ssl->in_msglen -= n;
7290 
7291     if( ssl->in_msglen == 0 )
7292     {
7293         /* all bytes consumed */
7294         ssl->in_offt = NULL;
7295         ssl->keep_current_message = 0;
7296     }
7297     else
7298     {
7299         /* more data available */
7300         ssl->in_offt += n;
7301     }
7302 
7303     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= read" ) );
7304 
7305     return( (int) n );
7306 }
7307 
7308 /*
7309  * Send application data to be encrypted by the SSL layer, taking care of max
7310  * fragment length and buffer size.
7311  *
7312  * According to RFC 5246 Section 6.2.1:
7313  *
7314  *      Zero-length fragments of Application data MAY be sent as they are
7315  *      potentially useful as a traffic analysis countermeasure.
7316  *
7317  * Therefore, it is possible that the input message length is 0 and the
7318  * corresponding return code is 0 on success.
7319  */
7320 static int ssl_write_real( mbedtls_ssl_context *ssl,
7321                            const unsigned char *buf, size_t len )
7322 {
7323     int ret;
7324 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
7325     size_t max_len = mbedtls_ssl_get_max_frag_len( ssl );
7326 #else
7327     size_t max_len = MBEDTLS_SSL_MAX_CONTENT_LEN;
7328 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
7329     if( len > max_len )
7330     {
7331 #if defined(MBEDTLS_SSL_PROTO_DTLS)
7332         if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
7333         {
7334             MBEDTLS_SSL_DEBUG_MSG( 1, ( "fragment larger than the (negotiated) "
7335                                 "maximum fragment length: %d > %d",
7336                                 len, max_len ) );
7337             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
7338         }
7339         else
7340 #endif
7341             len = max_len;
7342     }
7343 
7344     if( ssl->out_left != 0 )
7345     {
7346         /*
7347          * The user has previously tried to send the data and
7348          * MBEDTLS_ERR_SSL_WANT_WRITE or the message was only partially
7349          * written. In this case, we expect the high-level write function
7350          * (e.g. mbedtls_ssl_write()) to be called with the same parameters
7351          */
7352         if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
7353         {
7354             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flush_output", ret );
7355             return( ret );
7356         }
7357     }
7358     else
7359     {
7360         /*
7361          * The user is trying to send a message the first time, so we need to
7362          * copy the data into the internal buffers and setup the data structure
7363          * to keep track of partial writes
7364          */
7365         ssl->out_msglen  = len;
7366         ssl->out_msgtype = MBEDTLS_SSL_MSG_APPLICATION_DATA;
7367         memcpy( ssl->out_msg, buf, len );
7368 
7369         if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
7370         {
7371             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
7372             return( ret );
7373         }
7374     }
7375 
7376     return( (int) len );
7377 }
7378 
7379 /*
7380  * Write application data, doing 1/n-1 splitting if necessary.
7381  *
7382  * With non-blocking I/O, ssl_write_real() may return WANT_WRITE,
7383  * then the caller will call us again with the same arguments, so
7384  * remember whether we already did the split or not.
7385  */
7386 #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
7387 static int ssl_write_split( mbedtls_ssl_context *ssl,
7388                             const unsigned char *buf, size_t len )
7389 {
7390     int ret;
7391 
7392     if( ssl->conf->cbc_record_splitting ==
7393             MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED ||
7394         len <= 1 ||
7395         ssl->minor_ver > MBEDTLS_SSL_MINOR_VERSION_1 ||
7396         mbedtls_cipher_get_cipher_mode( &ssl->transform_out->cipher_ctx_enc )
7397                                 != MBEDTLS_MODE_CBC )
7398     {
7399         return( ssl_write_real( ssl, buf, len ) );
7400     }
7401 
7402     if( ssl->split_done == 0 )
7403     {
7404         if( ( ret = ssl_write_real( ssl, buf, 1 ) ) <= 0 )
7405             return( ret );
7406         ssl->split_done = 1;
7407     }
7408 
7409     if( ( ret = ssl_write_real( ssl, buf + 1, len - 1 ) ) <= 0 )
7410         return( ret );
7411     ssl->split_done = 0;
7412 
7413     return( ret + 1 );
7414 }
7415 #endif /* MBEDTLS_SSL_CBC_RECORD_SPLITTING */
7416 
7417 /*
7418  * Write application data (public-facing wrapper)
7419  */
7420 int mbedtls_ssl_write( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len )
7421 {
7422     int ret;
7423 
7424     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write" ) );
7425 
7426     if( ssl == NULL || ssl->conf == NULL )
7427         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
7428 
7429 #if defined(MBEDTLS_SSL_RENEGOTIATION)
7430     if( ( ret = ssl_check_ctr_renegotiate( ssl ) ) != 0 )
7431     {
7432         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_check_ctr_renegotiate", ret );
7433         return( ret );
7434     }
7435 #endif
7436 
7437     if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER )
7438     {
7439         if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 )
7440         {
7441             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret );
7442             return( ret );
7443         }
7444     }
7445 
7446 #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
7447     ret = ssl_write_split( ssl, buf, len );
7448 #else
7449     ret = ssl_write_real( ssl, buf, len );
7450 #endif
7451 
7452     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write" ) );
7453 
7454     return( ret );
7455 }
7456 
7457 /*
7458  * Notify the peer that the connection is being closed
7459  */
7460 int mbedtls_ssl_close_notify( mbedtls_ssl_context *ssl )
7461 {
7462     int ret;
7463 
7464     if( ssl == NULL || ssl->conf == NULL )
7465         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
7466 
7467     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write close notify" ) );
7468 
7469     if( ssl->out_left != 0 )
7470         return( mbedtls_ssl_flush_output( ssl ) );
7471 
7472     if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER )
7473     {
7474         if( ( ret = mbedtls_ssl_send_alert_message( ssl,
7475                         MBEDTLS_SSL_ALERT_LEVEL_WARNING,
7476                         MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY ) ) != 0 )
7477         {
7478             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_send_alert_message", ret );
7479             return( ret );
7480         }
7481     }
7482 
7483     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write close notify" ) );
7484 
7485     return( 0 );
7486 }
7487 
7488 void mbedtls_ssl_transform_free( mbedtls_ssl_transform *transform )
7489 {
7490     if( transform == NULL )
7491         return;
7492 
7493 #if defined(MBEDTLS_ZLIB_SUPPORT)
7494     deflateEnd( &transform->ctx_deflate );
7495     inflateEnd( &transform->ctx_inflate );
7496 #endif
7497 
7498     mbedtls_cipher_free( &transform->cipher_ctx_enc );
7499     mbedtls_cipher_free( &transform->cipher_ctx_dec );
7500 
7501     mbedtls_md_free( &transform->md_ctx_enc );
7502     mbedtls_md_free( &transform->md_ctx_dec );
7503 
7504     mbedtls_zeroize( transform, sizeof( mbedtls_ssl_transform ) );
7505 }
7506 
7507 #if defined(MBEDTLS_X509_CRT_PARSE_C)
7508 static void ssl_key_cert_free( mbedtls_ssl_key_cert *key_cert )
7509 {
7510     mbedtls_ssl_key_cert *cur = key_cert, *next;
7511 
7512     while( cur != NULL )
7513     {
7514         next = cur->next;
7515         mbedtls_free( cur );
7516         cur = next;
7517     }
7518 }
7519 #endif /* MBEDTLS_X509_CRT_PARSE_C */
7520 
7521 void mbedtls_ssl_handshake_free( mbedtls_ssl_handshake_params *handshake )
7522 {
7523     if( handshake == NULL )
7524         return;
7525 
7526 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
7527     defined(MBEDTLS_SSL_PROTO_TLS1_1)
7528     mbedtls_md5_free(    &handshake->fin_md5  );
7529     mbedtls_sha1_free(   &handshake->fin_sha1 );
7530 #endif
7531 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
7532 #if defined(MBEDTLS_SHA256_C)
7533     mbedtls_sha256_free(   &handshake->fin_sha256    );
7534 #endif
7535 #if defined(MBEDTLS_SHA512_C)
7536     mbedtls_sha512_free(   &handshake->fin_sha512    );
7537 #endif
7538 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
7539 
7540 #if defined(MBEDTLS_DHM_C)
7541     mbedtls_dhm_free( &handshake->dhm_ctx );
7542 #endif
7543 #if defined(MBEDTLS_ECDH_C)
7544     mbedtls_ecdh_free( &handshake->ecdh_ctx );
7545 #endif
7546 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
7547     mbedtls_ecjpake_free( &handshake->ecjpake_ctx );
7548 #if defined(MBEDTLS_SSL_CLI_C)
7549     mbedtls_free( handshake->ecjpake_cache );
7550     handshake->ecjpake_cache = NULL;
7551     handshake->ecjpake_cache_len = 0;
7552 #endif
7553 #endif
7554 
7555 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
7556     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
7557     /* explicit void pointer cast for buggy MS compiler */
7558     mbedtls_free( (void *) handshake->curves );
7559 #endif
7560 
7561 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
7562     if( handshake->psk != NULL )
7563     {
7564         mbedtls_zeroize( handshake->psk, handshake->psk_len );
7565         mbedtls_free( handshake->psk );
7566     }
7567 #endif
7568 
7569 #if defined(MBEDTLS_X509_CRT_PARSE_C) && \
7570     defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
7571     /*
7572      * Free only the linked list wrapper, not the keys themselves
7573      * since the belong to the SNI callback
7574      */
7575     if( handshake->sni_key_cert != NULL )
7576     {
7577         mbedtls_ssl_key_cert *cur = handshake->sni_key_cert, *next;
7578 
7579         while( cur != NULL )
7580         {
7581             next = cur->next;
7582             mbedtls_free( cur );
7583             cur = next;
7584         }
7585     }
7586 #endif /* MBEDTLS_X509_CRT_PARSE_C && MBEDTLS_SSL_SERVER_NAME_INDICATION */
7587 
7588 #if defined(MBEDTLS_SSL_PROTO_DTLS)
7589     mbedtls_free( handshake->verify_cookie );
7590     mbedtls_free( handshake->hs_msg );
7591     ssl_flight_free( handshake->flight );
7592 #endif
7593 
7594     mbedtls_zeroize( handshake, sizeof( mbedtls_ssl_handshake_params ) );
7595 }
7596 
7597 void mbedtls_ssl_session_free( mbedtls_ssl_session *session )
7598 {
7599     if( session == NULL )
7600         return;
7601 
7602 #if defined(MBEDTLS_X509_CRT_PARSE_C)
7603     if( session->peer_cert != NULL )
7604     {
7605         mbedtls_x509_crt_free( session->peer_cert );
7606         mbedtls_free( session->peer_cert );
7607     }
7608 #endif
7609 
7610 #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
7611     mbedtls_free( session->ticket );
7612 #endif
7613 
7614     mbedtls_zeroize( session, sizeof( mbedtls_ssl_session ) );
7615 }
7616 
7617 /*
7618  * Free an SSL context
7619  */
7620 void mbedtls_ssl_free( mbedtls_ssl_context *ssl )
7621 {
7622     if( ssl == NULL )
7623         return;
7624 
7625     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> free" ) );
7626 
7627     if( ssl->out_buf != NULL )
7628     {
7629         mbedtls_zeroize( ssl->out_buf, MBEDTLS_SSL_BUFFER_LEN );
7630         mbedtls_free( ssl->out_buf );
7631     }
7632 
7633     if( ssl->in_buf != NULL )
7634     {
7635         mbedtls_zeroize( ssl->in_buf, MBEDTLS_SSL_BUFFER_LEN );
7636         mbedtls_free( ssl->in_buf );
7637     }
7638 
7639 #if defined(MBEDTLS_ZLIB_SUPPORT)
7640     if( ssl->compress_buf != NULL )
7641     {
7642         mbedtls_zeroize( ssl->compress_buf, MBEDTLS_SSL_BUFFER_LEN );
7643         mbedtls_free( ssl->compress_buf );
7644     }
7645 #endif
7646 
7647     if( ssl->transform )
7648     {
7649         mbedtls_ssl_transform_free( ssl->transform );
7650         mbedtls_free( ssl->transform );
7651     }
7652 
7653     if( ssl->handshake )
7654     {
7655         mbedtls_ssl_handshake_free( ssl->handshake );
7656         mbedtls_ssl_transform_free( ssl->transform_negotiate );
7657         mbedtls_ssl_session_free( ssl->session_negotiate );
7658 
7659         mbedtls_free( ssl->handshake );
7660         mbedtls_free( ssl->transform_negotiate );
7661         mbedtls_free( ssl->session_negotiate );
7662     }
7663 
7664     if( ssl->session )
7665     {
7666         mbedtls_ssl_session_free( ssl->session );
7667         mbedtls_free( ssl->session );
7668     }
7669 
7670 #if defined(MBEDTLS_X509_CRT_PARSE_C)
7671     if( ssl->hostname != NULL )
7672     {
7673         mbedtls_zeroize( ssl->hostname, strlen( ssl->hostname ) );
7674         mbedtls_free( ssl->hostname );
7675     }
7676 #endif
7677 
7678 #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
7679     if( mbedtls_ssl_hw_record_finish != NULL )
7680     {
7681         MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_finish()" ) );
7682         mbedtls_ssl_hw_record_finish( ssl );
7683     }
7684 #endif
7685 
7686 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
7687     mbedtls_free( ssl->cli_id );
7688 #endif
7689 
7690     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= free" ) );
7691 
7692     /* Actually clear after last debug message */
7693     mbedtls_zeroize( ssl, sizeof( mbedtls_ssl_context ) );
7694 }
7695 
7696 /*
7697  * Initialze mbedtls_ssl_config
7698  */
7699 void mbedtls_ssl_config_init( mbedtls_ssl_config *conf )
7700 {
7701     memset( conf, 0, sizeof( mbedtls_ssl_config ) );
7702 }
7703 
7704 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
7705 static int ssl_preset_default_hashes[] = {
7706 #if defined(MBEDTLS_SHA512_C)
7707     MBEDTLS_MD_SHA512,
7708     MBEDTLS_MD_SHA384,
7709 #endif
7710 #if defined(MBEDTLS_SHA256_C)
7711     MBEDTLS_MD_SHA256,
7712     MBEDTLS_MD_SHA224,
7713 #endif
7714 #if defined(MBEDTLS_SHA1_C) && defined(MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_KEY_EXCHANGE)
7715     MBEDTLS_MD_SHA1,
7716 #endif
7717     MBEDTLS_MD_NONE
7718 };
7719 #endif
7720 
7721 static int ssl_preset_suiteb_ciphersuites[] = {
7722     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
7723     MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
7724     0
7725 };
7726 
7727 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
7728 static int ssl_preset_suiteb_hashes[] = {
7729     MBEDTLS_MD_SHA256,
7730     MBEDTLS_MD_SHA384,
7731     MBEDTLS_MD_NONE
7732 };
7733 #endif
7734 
7735 #if defined(MBEDTLS_ECP_C)
7736 static mbedtls_ecp_group_id ssl_preset_suiteb_curves[] = {
7737     MBEDTLS_ECP_DP_SECP256R1,
7738     MBEDTLS_ECP_DP_SECP384R1,
7739     MBEDTLS_ECP_DP_NONE
7740 };
7741 #endif
7742 
7743 /*
7744  * Load default in mbedtls_ssl_config
7745  */
7746 int mbedtls_ssl_config_defaults( mbedtls_ssl_config *conf,
7747                                  int endpoint, int transport, int preset )
7748 {
7749 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
7750     int ret;
7751 #endif
7752 
7753     /* Use the functions here so that they are covered in tests,
7754      * but otherwise access member directly for efficiency */
7755     mbedtls_ssl_conf_endpoint( conf, endpoint );
7756     mbedtls_ssl_conf_transport( conf, transport );
7757 
7758     /*
7759      * Things that are common to all presets
7760      */
7761 #if defined(MBEDTLS_SSL_CLI_C)
7762     if( endpoint == MBEDTLS_SSL_IS_CLIENT )
7763     {
7764         conf->authmode = MBEDTLS_SSL_VERIFY_REQUIRED;
7765 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
7766         conf->session_tickets = MBEDTLS_SSL_SESSION_TICKETS_ENABLED;
7767 #endif
7768     }
7769 #endif
7770 
7771 #if defined(MBEDTLS_ARC4_C)
7772     conf->arc4_disabled = MBEDTLS_SSL_ARC4_DISABLED;
7773 #endif
7774 
7775 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
7776     conf->encrypt_then_mac = MBEDTLS_SSL_ETM_ENABLED;
7777 #endif
7778 
7779 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
7780     conf->extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED;
7781 #endif
7782 
7783 #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
7784     conf->cbc_record_splitting = MBEDTLS_SSL_CBC_RECORD_SPLITTING_ENABLED;
7785 #endif
7786 
7787 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
7788     conf->f_cookie_write = ssl_cookie_write_dummy;
7789     conf->f_cookie_check = ssl_cookie_check_dummy;
7790 #endif
7791 
7792 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
7793     conf->anti_replay = MBEDTLS_SSL_ANTI_REPLAY_ENABLED;
7794 #endif
7795 
7796 #if defined(MBEDTLS_SSL_SRV_C)
7797     conf->cert_req_ca_list = MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED;
7798 #endif
7799 
7800 #if defined(MBEDTLS_SSL_PROTO_DTLS)
7801     conf->hs_timeout_min = MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MIN;
7802     conf->hs_timeout_max = MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MAX;
7803 #endif
7804 
7805 #if defined(MBEDTLS_SSL_RENEGOTIATION)
7806     conf->renego_max_records = MBEDTLS_SSL_RENEGO_MAX_RECORDS_DEFAULT;
7807     memset( conf->renego_period,     0x00, 2 );
7808     memset( conf->renego_period + 2, 0xFF, 6 );
7809 #endif
7810 
7811 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
7812             if( endpoint == MBEDTLS_SSL_IS_SERVER )
7813             {
7814                 const unsigned char dhm_p[] =
7815                     MBEDTLS_DHM_RFC3526_MODP_2048_P_BIN;
7816                 const unsigned char dhm_g[] =
7817                     MBEDTLS_DHM_RFC3526_MODP_2048_G_BIN;
7818 
7819                 if ( ( ret = mbedtls_ssl_conf_dh_param_bin( conf,
7820                                                dhm_p, sizeof( dhm_p ),
7821                                                dhm_g, sizeof( dhm_g ) ) ) != 0 )
7822                 {
7823                     return( ret );
7824                 }
7825             }
7826 #endif
7827 
7828     /*
7829      * Preset-specific defaults
7830      */
7831     switch( preset )
7832     {
7833         /*
7834          * NSA Suite B
7835          */
7836         case MBEDTLS_SSL_PRESET_SUITEB:
7837             conf->min_major_ver = MBEDTLS_SSL_MAJOR_VERSION_3;
7838             conf->min_minor_ver = MBEDTLS_SSL_MINOR_VERSION_3; /* TLS 1.2 */
7839             conf->max_major_ver = MBEDTLS_SSL_MAX_MAJOR_VERSION;
7840             conf->max_minor_ver = MBEDTLS_SSL_MAX_MINOR_VERSION;
7841 
7842             conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] =
7843             conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] =
7844             conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] =
7845             conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] =
7846                                    ssl_preset_suiteb_ciphersuites;
7847 
7848 #if defined(MBEDTLS_X509_CRT_PARSE_C)
7849             conf->cert_profile = &mbedtls_x509_crt_profile_suiteb;
7850 #endif
7851 
7852 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
7853             conf->sig_hashes = ssl_preset_suiteb_hashes;
7854 #endif
7855 
7856 #if defined(MBEDTLS_ECP_C)
7857             conf->curve_list = ssl_preset_suiteb_curves;
7858 #endif
7859             break;
7860 
7861         /*
7862          * Default
7863          */
7864         default:
7865             conf->min_major_ver = ( MBEDTLS_SSL_MIN_MAJOR_VERSION >
7866                                     MBEDTLS_SSL_MIN_VALID_MAJOR_VERSION ) ?
7867                                     MBEDTLS_SSL_MIN_MAJOR_VERSION :
7868                                     MBEDTLS_SSL_MIN_VALID_MAJOR_VERSION;
7869             conf->min_minor_ver = ( MBEDTLS_SSL_MIN_MINOR_VERSION >
7870                                     MBEDTLS_SSL_MIN_VALID_MINOR_VERSION ) ?
7871                                     MBEDTLS_SSL_MIN_MINOR_VERSION :
7872                                     MBEDTLS_SSL_MIN_VALID_MINOR_VERSION;
7873             conf->max_major_ver = MBEDTLS_SSL_MAX_MAJOR_VERSION;
7874             conf->max_minor_ver = MBEDTLS_SSL_MAX_MINOR_VERSION;
7875 
7876 #if defined(MBEDTLS_SSL_PROTO_DTLS)
7877             if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
7878                 conf->min_minor_ver = MBEDTLS_SSL_MINOR_VERSION_2;
7879 #endif
7880 
7881             conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] =
7882             conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] =
7883             conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] =
7884             conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] =
7885                                    mbedtls_ssl_list_ciphersuites();
7886 
7887 #if defined(MBEDTLS_X509_CRT_PARSE_C)
7888             conf->cert_profile = &mbedtls_x509_crt_profile_default;
7889 #endif
7890 
7891 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
7892             conf->sig_hashes = ssl_preset_default_hashes;
7893 #endif
7894 
7895 #if defined(MBEDTLS_ECP_C)
7896             conf->curve_list = mbedtls_ecp_grp_id_list();
7897 #endif
7898 
7899 #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C)
7900             conf->dhm_min_bitlen = 1024;
7901 #endif
7902     }
7903 
7904     return( 0 );
7905 }
7906 
7907 /*
7908  * Free mbedtls_ssl_config
7909  */
7910 void mbedtls_ssl_config_free( mbedtls_ssl_config *conf )
7911 {
7912 #if defined(MBEDTLS_DHM_C)
7913     mbedtls_mpi_free( &conf->dhm_P );
7914     mbedtls_mpi_free( &conf->dhm_G );
7915 #endif
7916 
7917 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
7918     if( conf->psk != NULL )
7919     {
7920         mbedtls_zeroize( conf->psk, conf->psk_len );
7921         mbedtls_zeroize( conf->psk_identity, conf->psk_identity_len );
7922         mbedtls_free( conf->psk );
7923         mbedtls_free( conf->psk_identity );
7924         conf->psk_len = 0;
7925         conf->psk_identity_len = 0;
7926     }
7927 #endif
7928 
7929 #if defined(MBEDTLS_X509_CRT_PARSE_C)
7930     ssl_key_cert_free( conf->key_cert );
7931 #endif
7932 
7933     mbedtls_zeroize( conf, sizeof( mbedtls_ssl_config ) );
7934 }
7935 
7936 #if defined(MBEDTLS_PK_C) && \
7937     ( defined(MBEDTLS_RSA_C) || defined(MBEDTLS_ECDSA_C) )
7938 /*
7939  * Convert between MBEDTLS_PK_XXX and SSL_SIG_XXX
7940  */
7941 unsigned char mbedtls_ssl_sig_from_pk( mbedtls_pk_context *pk )
7942 {
7943 #if defined(MBEDTLS_RSA_C)
7944     if( mbedtls_pk_can_do( pk, MBEDTLS_PK_RSA ) )
7945         return( MBEDTLS_SSL_SIG_RSA );
7946 #endif
7947 #if defined(MBEDTLS_ECDSA_C)
7948     if( mbedtls_pk_can_do( pk, MBEDTLS_PK_ECDSA ) )
7949         return( MBEDTLS_SSL_SIG_ECDSA );
7950 #endif
7951     return( MBEDTLS_SSL_SIG_ANON );
7952 }
7953 
7954 unsigned char mbedtls_ssl_sig_from_pk_alg( mbedtls_pk_type_t type )
7955 {
7956     switch( type ) {
7957         case MBEDTLS_PK_RSA:
7958             return( MBEDTLS_SSL_SIG_RSA );
7959         case MBEDTLS_PK_ECDSA:
7960         case MBEDTLS_PK_ECKEY:
7961             return( MBEDTLS_SSL_SIG_ECDSA );
7962         default:
7963             return( MBEDTLS_SSL_SIG_ANON );
7964     }
7965 }
7966 
7967 mbedtls_pk_type_t mbedtls_ssl_pk_alg_from_sig( unsigned char sig )
7968 {
7969     switch( sig )
7970     {
7971 #if defined(MBEDTLS_RSA_C)
7972         case MBEDTLS_SSL_SIG_RSA:
7973             return( MBEDTLS_PK_RSA );
7974 #endif
7975 #if defined(MBEDTLS_ECDSA_C)
7976         case MBEDTLS_SSL_SIG_ECDSA:
7977             return( MBEDTLS_PK_ECDSA );
7978 #endif
7979         default:
7980             return( MBEDTLS_PK_NONE );
7981     }
7982 }
7983 #endif /* MBEDTLS_PK_C && ( MBEDTLS_RSA_C || MBEDTLS_ECDSA_C ) */
7984 
7985 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
7986     defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
7987 
7988 /* Find an entry in a signature-hash set matching a given hash algorithm. */
7989 mbedtls_md_type_t mbedtls_ssl_sig_hash_set_find( mbedtls_ssl_sig_hash_set_t *set,
7990                                                  mbedtls_pk_type_t sig_alg )
7991 {
7992     switch( sig_alg )
7993     {
7994         case MBEDTLS_PK_RSA:
7995             return( set->rsa );
7996         case MBEDTLS_PK_ECDSA:
7997             return( set->ecdsa );
7998         default:
7999             return( MBEDTLS_MD_NONE );
8000     }
8001 }
8002 
8003 /* Add a signature-hash-pair to a signature-hash set */
8004 void mbedtls_ssl_sig_hash_set_add( mbedtls_ssl_sig_hash_set_t *set,
8005                                    mbedtls_pk_type_t sig_alg,
8006                                    mbedtls_md_type_t md_alg )
8007 {
8008     switch( sig_alg )
8009     {
8010         case MBEDTLS_PK_RSA:
8011             if( set->rsa == MBEDTLS_MD_NONE )
8012                 set->rsa = md_alg;
8013             break;
8014 
8015         case MBEDTLS_PK_ECDSA:
8016             if( set->ecdsa == MBEDTLS_MD_NONE )
8017                 set->ecdsa = md_alg;
8018             break;
8019 
8020         default:
8021             break;
8022     }
8023 }
8024 
8025 /* Allow exactly one hash algorithm for each signature. */
8026 void mbedtls_ssl_sig_hash_set_const_hash( mbedtls_ssl_sig_hash_set_t *set,
8027                                           mbedtls_md_type_t md_alg )
8028 {
8029     set->rsa   = md_alg;
8030     set->ecdsa = md_alg;
8031 }
8032 
8033 #endif /* MBEDTLS_SSL_PROTO_TLS1_2) &&
8034           MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
8035 
8036 /*
8037  * Convert from MBEDTLS_SSL_HASH_XXX to MBEDTLS_MD_XXX
8038  */
8039 mbedtls_md_type_t mbedtls_ssl_md_alg_from_hash( unsigned char hash )
8040 {
8041     switch( hash )
8042     {
8043 #if defined(MBEDTLS_MD5_C)
8044         case MBEDTLS_SSL_HASH_MD5:
8045             return( MBEDTLS_MD_MD5 );
8046 #endif
8047 #if defined(MBEDTLS_SHA1_C)
8048         case MBEDTLS_SSL_HASH_SHA1:
8049             return( MBEDTLS_MD_SHA1 );
8050 #endif
8051 #if defined(MBEDTLS_SHA256_C)
8052         case MBEDTLS_SSL_HASH_SHA224:
8053             return( MBEDTLS_MD_SHA224 );
8054         case MBEDTLS_SSL_HASH_SHA256:
8055             return( MBEDTLS_MD_SHA256 );
8056 #endif
8057 #if defined(MBEDTLS_SHA512_C)
8058         case MBEDTLS_SSL_HASH_SHA384:
8059             return( MBEDTLS_MD_SHA384 );
8060         case MBEDTLS_SSL_HASH_SHA512:
8061             return( MBEDTLS_MD_SHA512 );
8062 #endif
8063         default:
8064             return( MBEDTLS_MD_NONE );
8065     }
8066 }
8067 
8068 /*
8069  * Convert from MBEDTLS_MD_XXX to MBEDTLS_SSL_HASH_XXX
8070  */
8071 unsigned char mbedtls_ssl_hash_from_md_alg( int md )
8072 {
8073     switch( md )
8074     {
8075 #if defined(MBEDTLS_MD5_C)
8076         case MBEDTLS_MD_MD5:
8077             return( MBEDTLS_SSL_HASH_MD5 );
8078 #endif
8079 #if defined(MBEDTLS_SHA1_C)
8080         case MBEDTLS_MD_SHA1:
8081             return( MBEDTLS_SSL_HASH_SHA1 );
8082 #endif
8083 #if defined(MBEDTLS_SHA256_C)
8084         case MBEDTLS_MD_SHA224:
8085             return( MBEDTLS_SSL_HASH_SHA224 );
8086         case MBEDTLS_MD_SHA256:
8087             return( MBEDTLS_SSL_HASH_SHA256 );
8088 #endif
8089 #if defined(MBEDTLS_SHA512_C)
8090         case MBEDTLS_MD_SHA384:
8091             return( MBEDTLS_SSL_HASH_SHA384 );
8092         case MBEDTLS_MD_SHA512:
8093             return( MBEDTLS_SSL_HASH_SHA512 );
8094 #endif
8095         default:
8096             return( MBEDTLS_SSL_HASH_NONE );
8097     }
8098 }
8099 
8100 #if defined(MBEDTLS_ECP_C)
8101 /*
8102  * Check if a curve proposed by the peer is in our list.
8103  * Return 0 if we're willing to use it, -1 otherwise.
8104  */
8105 int mbedtls_ssl_check_curve( const mbedtls_ssl_context *ssl, mbedtls_ecp_group_id grp_id )
8106 {
8107     const mbedtls_ecp_group_id *gid;
8108 
8109     if( ssl->conf->curve_list == NULL )
8110         return( -1 );
8111 
8112     for( gid = ssl->conf->curve_list; *gid != MBEDTLS_ECP_DP_NONE; gid++ )
8113         if( *gid == grp_id )
8114             return( 0 );
8115 
8116     return( -1 );
8117 }
8118 #endif /* MBEDTLS_ECP_C */
8119 
8120 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
8121 /*
8122  * Check if a hash proposed by the peer is in our list.
8123  * Return 0 if we're willing to use it, -1 otherwise.
8124  */
8125 int mbedtls_ssl_check_sig_hash( const mbedtls_ssl_context *ssl,
8126                                 mbedtls_md_type_t md )
8127 {
8128     const int *cur;
8129 
8130     if( ssl->conf->sig_hashes == NULL )
8131         return( -1 );
8132 
8133     for( cur = ssl->conf->sig_hashes; *cur != MBEDTLS_MD_NONE; cur++ )
8134         if( *cur == (int) md )
8135             return( 0 );
8136 
8137     return( -1 );
8138 }
8139 #endif /* MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
8140 
8141 #if defined(MBEDTLS_X509_CRT_PARSE_C)
8142 int mbedtls_ssl_check_cert_usage( const mbedtls_x509_crt *cert,
8143                           const mbedtls_ssl_ciphersuite_t *ciphersuite,
8144                           int cert_endpoint,
8145                           uint32_t *flags )
8146 {
8147     int ret = 0;
8148 #if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
8149     int usage = 0;
8150 #endif
8151 #if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
8152     const char *ext_oid;
8153     size_t ext_len;
8154 #endif
8155 
8156 #if !defined(MBEDTLS_X509_CHECK_KEY_USAGE) &&          \
8157     !defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
8158     ((void) cert);
8159     ((void) cert_endpoint);
8160     ((void) flags);
8161 #endif
8162 
8163 #if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
8164     if( cert_endpoint == MBEDTLS_SSL_IS_SERVER )
8165     {
8166         /* Server part of the key exchange */
8167         switch( ciphersuite->key_exchange )
8168         {
8169             case MBEDTLS_KEY_EXCHANGE_RSA:
8170             case MBEDTLS_KEY_EXCHANGE_RSA_PSK:
8171                 usage = MBEDTLS_X509_KU_KEY_ENCIPHERMENT;
8172                 break;
8173 
8174             case MBEDTLS_KEY_EXCHANGE_DHE_RSA:
8175             case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
8176             case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
8177                 usage = MBEDTLS_X509_KU_DIGITAL_SIGNATURE;
8178                 break;
8179 
8180             case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:
8181             case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:
8182                 usage = MBEDTLS_X509_KU_KEY_AGREEMENT;
8183                 break;
8184 
8185             /* Don't use default: we want warnings when adding new values */
8186             case MBEDTLS_KEY_EXCHANGE_NONE:
8187             case MBEDTLS_KEY_EXCHANGE_PSK:
8188             case MBEDTLS_KEY_EXCHANGE_DHE_PSK:
8189             case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK:
8190             case MBEDTLS_KEY_EXCHANGE_ECJPAKE:
8191                 usage = 0;
8192         }
8193     }
8194     else
8195     {
8196         /* Client auth: we only implement rsa_sign and mbedtls_ecdsa_sign for now */
8197         usage = MBEDTLS_X509_KU_DIGITAL_SIGNATURE;
8198     }
8199 
8200     if( mbedtls_x509_crt_check_key_usage( cert, usage ) != 0 )
8201     {
8202         *flags |= MBEDTLS_X509_BADCERT_KEY_USAGE;
8203         ret = -1;
8204     }
8205 #else
8206     ((void) ciphersuite);
8207 #endif /* MBEDTLS_X509_CHECK_KEY_USAGE */
8208 
8209 #if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
8210     if( cert_endpoint == MBEDTLS_SSL_IS_SERVER )
8211     {
8212         ext_oid = MBEDTLS_OID_SERVER_AUTH;
8213         ext_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_SERVER_AUTH );
8214     }
8215     else
8216     {
8217         ext_oid = MBEDTLS_OID_CLIENT_AUTH;
8218         ext_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_CLIENT_AUTH );
8219     }
8220 
8221     if( mbedtls_x509_crt_check_extended_key_usage( cert, ext_oid, ext_len ) != 0 )
8222     {
8223         *flags |= MBEDTLS_X509_BADCERT_EXT_KEY_USAGE;
8224         ret = -1;
8225     }
8226 #endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE */
8227 
8228     return( ret );
8229 }
8230 #endif /* MBEDTLS_X509_CRT_PARSE_C */
8231 
8232 /*
8233  * Convert version numbers to/from wire format
8234  * and, for DTLS, to/from TLS equivalent.
8235  *
8236  * For TLS this is the identity.
8237  * For DTLS, use 1's complement (v -> 255 - v, and then map as follows:
8238  * 1.0 <-> 3.2      (DTLS 1.0 is based on TLS 1.1)
8239  * 1.x <-> 3.x+1    for x != 0 (DTLS 1.2 based on TLS 1.2)
8240  */
8241 void mbedtls_ssl_write_version( int major, int minor, int transport,
8242                         unsigned char ver[2] )
8243 {
8244 #if defined(MBEDTLS_SSL_PROTO_DTLS)
8245     if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
8246     {
8247         if( minor == MBEDTLS_SSL_MINOR_VERSION_2 )
8248             --minor; /* DTLS 1.0 stored as TLS 1.1 internally */
8249 
8250         ver[0] = (unsigned char)( 255 - ( major - 2 ) );
8251         ver[1] = (unsigned char)( 255 - ( minor - 1 ) );
8252     }
8253     else
8254 #else
8255     ((void) transport);
8256 #endif
8257     {
8258         ver[0] = (unsigned char) major;
8259         ver[1] = (unsigned char) minor;
8260     }
8261 }
8262 
8263 void mbedtls_ssl_read_version( int *major, int *minor, int transport,
8264                        const unsigned char ver[2] )
8265 {
8266 #if defined(MBEDTLS_SSL_PROTO_DTLS)
8267     if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
8268     {
8269         *major = 255 - ver[0] + 2;
8270         *minor = 255 - ver[1] + 1;
8271 
8272         if( *minor == MBEDTLS_SSL_MINOR_VERSION_1 )
8273             ++*minor; /* DTLS 1.0 stored as TLS 1.1 internally */
8274     }
8275     else
8276 #else
8277     ((void) transport);
8278 #endif
8279     {
8280         *major = ver[0];
8281         *minor = ver[1];
8282     }
8283 }
8284 
8285 int mbedtls_ssl_set_calc_verify_md( mbedtls_ssl_context *ssl, int md )
8286 {
8287 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
8288     if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
8289         return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
8290 
8291     switch( md )
8292     {
8293 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
8294 #if defined(MBEDTLS_MD5_C)
8295         case MBEDTLS_SSL_HASH_MD5:
8296             return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
8297 #endif
8298 #if defined(MBEDTLS_SHA1_C)
8299         case MBEDTLS_SSL_HASH_SHA1:
8300             ssl->handshake->calc_verify = ssl_calc_verify_tls;
8301             break;
8302 #endif
8303 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
8304 #if defined(MBEDTLS_SHA512_C)
8305         case MBEDTLS_SSL_HASH_SHA384:
8306             ssl->handshake->calc_verify = ssl_calc_verify_tls_sha384;
8307             break;
8308 #endif
8309 #if defined(MBEDTLS_SHA256_C)
8310         case MBEDTLS_SSL_HASH_SHA256:
8311             ssl->handshake->calc_verify = ssl_calc_verify_tls_sha256;
8312             break;
8313 #endif
8314         default:
8315             return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
8316     }
8317 
8318     return 0;
8319 #else /* !MBEDTLS_SSL_PROTO_TLS1_2 */
8320     (void) ssl;
8321     (void) md;
8322 
8323     return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
8324 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
8325 }
8326 
8327 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
8328     defined(MBEDTLS_SSL_PROTO_TLS1_1)
8329 int mbedtls_ssl_get_key_exchange_md_ssl_tls( mbedtls_ssl_context *ssl,
8330                                         unsigned char *output,
8331                                         unsigned char *data, size_t data_len )
8332 {
8333     int ret = 0;
8334     mbedtls_md5_context mbedtls_md5;
8335     mbedtls_sha1_context mbedtls_sha1;
8336 
8337     mbedtls_md5_init( &mbedtls_md5 );
8338     mbedtls_sha1_init( &mbedtls_sha1 );
8339 
8340     /*
8341      * digitally-signed struct {
8342      *     opaque md5_hash[16];
8343      *     opaque sha_hash[20];
8344      * };
8345      *
8346      * md5_hash
8347      *     MD5(ClientHello.random + ServerHello.random
8348      *                            + ServerParams);
8349      * sha_hash
8350      *     SHA(ClientHello.random + ServerHello.random
8351      *                            + ServerParams);
8352      */
8353     if( ( ret = mbedtls_md5_starts_ret( &mbedtls_md5 ) ) != 0 )
8354     {
8355         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md5_starts_ret", ret );
8356         goto exit;
8357     }
8358     if( ( ret = mbedtls_md5_update_ret( &mbedtls_md5,
8359                                         ssl->handshake->randbytes, 64 ) ) != 0 )
8360     {
8361         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md5_update_ret", ret );
8362         goto exit;
8363     }
8364     if( ( ret = mbedtls_md5_update_ret( &mbedtls_md5, data, data_len ) ) != 0 )
8365     {
8366         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md5_update_ret", ret );
8367         goto exit;
8368     }
8369     if( ( ret = mbedtls_md5_finish_ret( &mbedtls_md5, output ) ) != 0 )
8370     {
8371         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md5_finish_ret", ret );
8372         goto exit;
8373     }
8374 
8375     if( ( ret = mbedtls_sha1_starts_ret( &mbedtls_sha1 ) ) != 0 )
8376     {
8377         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha1_starts_ret", ret );
8378         goto exit;
8379     }
8380     if( ( ret = mbedtls_sha1_update_ret( &mbedtls_sha1,
8381                                          ssl->handshake->randbytes, 64 ) ) != 0 )
8382     {
8383         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha1_update_ret", ret );
8384         goto exit;
8385     }
8386     if( ( ret = mbedtls_sha1_update_ret( &mbedtls_sha1, data,
8387                                          data_len ) ) != 0 )
8388     {
8389         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha1_update_ret", ret );
8390         goto exit;
8391     }
8392     if( ( ret = mbedtls_sha1_finish_ret( &mbedtls_sha1,
8393                                          output + 16 ) ) != 0 )
8394     {
8395         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_sha1_finish_ret", ret );
8396         goto exit;
8397     }
8398 
8399 exit:
8400     mbedtls_md5_free( &mbedtls_md5 );
8401     mbedtls_sha1_free( &mbedtls_sha1 );
8402 
8403     if( ret != 0 )
8404         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
8405                                         MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
8406 
8407     return( ret );
8408 
8409 }
8410 #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
8411           MBEDTLS_SSL_PROTO_TLS1_1 */
8412 
8413 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
8414     defined(MBEDTLS_SSL_PROTO_TLS1_2)
8415 int mbedtls_ssl_get_key_exchange_md_tls1_2( mbedtls_ssl_context *ssl,
8416                                        unsigned char *output,
8417                                        unsigned char *data, size_t data_len,
8418                                        mbedtls_md_type_t md_alg )
8419 {
8420     int ret = 0;
8421     mbedtls_md_context_t ctx;
8422     const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type( md_alg );
8423 
8424     mbedtls_md_init( &ctx );
8425 
8426     /*
8427      * digitally-signed struct {
8428      *     opaque client_random[32];
8429      *     opaque server_random[32];
8430      *     ServerDHParams params;
8431      * };
8432      */
8433     if( ( ret = mbedtls_md_setup( &ctx, md_info, 0 ) ) != 0 )
8434     {
8435         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_setup", ret );
8436         goto exit;
8437     }
8438     if( ( ret = mbedtls_md_starts( &ctx ) ) != 0 )
8439     {
8440         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_starts", ret );
8441         goto exit;
8442     }
8443     if( ( ret = mbedtls_md_update( &ctx, ssl->handshake->randbytes, 64 ) ) != 0 )
8444     {
8445         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_update", ret );
8446         goto exit;
8447     }
8448     if( ( ret = mbedtls_md_update( &ctx, data, data_len ) ) != 0 )
8449     {
8450         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_update", ret );
8451         goto exit;
8452     }
8453     if( ( ret = mbedtls_md_finish( &ctx, output ) ) != 0 )
8454     {
8455         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_finish", ret );
8456         goto exit;
8457     }
8458 
8459 exit:
8460     mbedtls_md_free( &ctx );
8461 
8462     if( ret != 0 )
8463         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
8464                                         MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
8465 
8466     return( ret );
8467 }
8468 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
8469           MBEDTLS_SSL_PROTO_TLS1_2 */
8470 
8471 #endif /* MBEDTLS_SSL_TLS_C */
8472