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