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