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