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