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